How does Implicit coercion differ from Explicit coercion in JavaScript?


In this article, you will understand how implicit coercion differs from Explicit coercion in JavaScript.

An implicit coercion is an automatic conversion of values from one datatype to another. It is also known as type conversion.

An explicit coercion is the conversion of data type depending on the user's necessity.

Example 1

In this example, let us learn about implicit coercion.

let inputValue = "5"
console.log("The input variable is defined as: ")
console.log(inputValue, typeof inputValue);
let resultValue = Number(inputValue);
console.log("
The input variable is defined as: ") console.log(resultValue, typeof resultValue);

Explanation

  • Step 1 −Define a variable: inputValue and assign an integer.

  • Step 2 −Add an empty string to ‘inputValue’. Now the type of ‘inputValue’ is changed from number to string.

  • Step 3 −Display the value and its type as result.

Example 2

In this example, let us learn about explicit coercion.

let inputValue = "5"
console.log("The input value is defined as a string with value: ", inputValue)
let resultValue = Number(inputValue);
console.log("The result value after conversion to a number is :", resultValue)

Explanation

  • Step 1 −Define a variable: inputValue and assign a string value to it.

  • Step 2 −Typecast the string value to integer. Now the type of ‘inputValue’ is changed from string to number.

  • Step 3 −Display the value and its type as result.

Updated on: 16-Feb-2023

963 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements