How does Implicit coercion differs from Explicit coercion in JavaScript ?


In JavaScript, coercion is the process of converting a value from one data type to another. There are two types of coercion: implicit and explicit.

Implicit Coercion:

Implicit coercion is the automatic conversion of a value from one data type to another, performed by JavaScript behind the scenes. This happens when an operator or function expects a certain data type, but receives a different one. JavaScript will try to convert the value to the expected data type before performing the operation.

For example, when we use the + operator with a string and a number, JavaScript will implicitly convert the number to a string and concatenate the two values:

const num = 10;
const str = "20";
const result = num + str; // "1020"

In this example, the number 10 is implicitly coerced into a string and concatenated with the string "20".

Explicit Coercion:

Explicit coercion is the manual conversion of a value from one data type to another, performed by the developer using built-in functions or operators. This is done when we want to convert a value to a specific data type, or when we want to ensure that a value is of a certain data type before performing an operation.

There are several built-in functions and operators that can be used for explicit coercion:

  • Number(): converts a value to a number data type
  • String(): converts a value to a string data type
  • Boolean(): converts a value to a boolean data type

For example, we can use the Number() function to explicitly convert a string to a number:

const str = "10";
const num = Number(str); // 10

In this example, the string "10" is explicitly coerced into a number using the Number() function.

Another example is using the parseInt() function to convert a string to an integer:

const str = "10";
const num = parseInt(str); // 10

In this example, the string "10" is explicitly coerced into an integer using the parseInt() function.

Overall, the main difference between implicit and explicit coercion is that implicit coercion is done automatically by JavaScript, while explicit coercion is done manually by the developer using built-in functions or operators.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.