Javascript Coercions

Beware of Javascript Coercions

Javascript is a very powerful language, but you all may know, “with great power comes great responsibilities“. Javascript Coercions is very tensile and doesn’t not need to be statically typed like in another languages like Java or C++. Many languages consider the below expression as error.

3 + true; //4

But in Javascript, not only it’s a valid expression but also it’ll yield 4 as result.

Javascript coercions consfusion

There are many cases in Javascript, where it’ll throw a immediate error when you try to access field of a null object or accessing undefined objects. But, Javascript Coercion has a different set of automatic conversion protocols. For example, the arithmetic operators +,-,*,/ and {8a5cad2dd9b6176f06827a78cde44fd8d19c8ce4ea2d8f5b1cc01d3f877cfcae} all attempt to convert their arguments to number before doing their calculation. However, the arithmetic operator +, stands out a little as it does either numeric addition or string concatenation, depending on the type of its arguments.


3 + 4; //5

"hello " + "world"; //"hello world"

This is pretty straightforward, but are you curious to know what happens when we change the type of arguments?

"2" + 3; //"23"

Strange, but Javascript turns the arguments to String.

1 + 2 + "3"; //"33"

The result is 33 because additions sums up to the left (left-associative). It is similar to this:

(1 + 2) + "3"; //"33"

What if we try this:

1 + "2" + 3; //"123"

Above expression evaluates to “123” because of left-associative nature.

NaN (Not a Number)

In Javascript, an undefined variable will convert to a special floating-point value named NaN.  Javascript follows the IEEE floating-point standard, which treats NaN to be unequal to itself. So testing a value equal to NaN doesn’t work at all.

var x = NaN;
x === NaN; // false

Even the standard isNaN library is little deceptive because it has its own implicit coercion, converting the argument to number before testing the value. Ensure the variable is number before using the isNaN.

isNaN(NaN); //true

Well the deception lies when you use isNaN against a non-number. It’ll evaluate any non-number to NaN.

isNaN("Javascript"); //true

isNaN(undefined); //true

isNaN({key: “value”}); //true

However, there’s a dependable workaround to test NaN values. Since NaN is the only Javascript value that is unequal to itselt, you can test if a value is NaN by checking it for equality to itself.

var x = NaN;
x !== x; //true
var y = "Javascript";
y !== y; //false

This is one of the few quirks in Javascript, and we’ll come up with more in the future. Tell us how do you like it in the comments section below