changing the type of a value - coercion in javascript

Using a value in a comparison can be confusing sometimes because JavaScript tries to be helpful and implicitly change the type for you.

The type of a value can be changed implicitly and explicitly.

Implicit coercion plays a huge role when using double equals in comparisons.

explicit vs implicit coercion

Explicit coercion is telling JavaScript to change the type.

Implicit coercion is not telling JavaScript to change the type directly.

JavaScript

let number = 42;
let explicitToString = String(number) // "42"
let implicitToString = number + ""; // "42"

The String() object wrapper is used to change 42 type explicitly to a string.

To change 42 type implicitly to a string we added a double quote to the number.

== vs ===

Values can be compared using the double equals or triple equals.

The problem with double equal is what you expect to happen might not happen.

A good understanding of type coercion is needed to fully utilize double equal and everyone else reading your code will as well need to have a good understanding.

Here is a table showing equalities. link to source

equality in javascript

javascript
changing the type of a value - coercion in javascript

Using a value in a comparison can be confusing sometimes because JavaScript tries to be helpful and implicitly change the type for you.

javascript
testing for NaN

NaN, Not a Number, is returned when doing math operations with values that aren't numbers.