Back to blog
Mar 17, 2024
2 min read

Javascript: Primitives

Primitives

Primitives

Type conversion / Coercion

Implicit coercion vs Explicit coercion

Explicit coercion is where value is forcibly converted to a different type than its original type:

const a = "55"
const b = Number(a);

console.log(a); // "55"
console.log(b); // 55

Using the built-in function Number(..), the string was converted to a number.

Implicit coercion is however not visible and the following is a scenario in which it could happen.

const a = "99.99";
const b = 99.99;

if (a == b) {
    console.log("same price");
} else {
    console.log("different price");
}

99.99 and “99.99” are basically the same value but in two different representations. (We can call them loosely equal, == is called as loose eqality operator).

In JS the when the if statement is evaluated, the string “99.99” is implicitly coerced to the number 99.99 prior to the evaluation, which results in values a and b to be the same, which would print a “same price” output.

To avoid this, you can use “strict equality operator” === this would result in a different outcome as it will compare both the value and the data type of the variables.

This loose equality can be confusing when writing JS programs. Therefore implicit coercion has to be learned properly.