Coercion in JavaScript

Bang and Double Bang

To me, coercion in JavaScript is another topic I’ve found interesting to explore. unexpected results. When using the bang (!)–also known as logical not–or double bang (!!) before a value, JavaScript coerces the value to a boolean and yields the opposite value:

!false                      //true
!0;                         //true
!!0;                        //false
typeof !!0                  //boolean
typeof !!0 == "boolean"     //true

Now to take it a step further by comparing the coerced values with the double equals operator:

!!0 == false    //true
!!'' == ''      //true
!!0 == 0        //true
!!1 == 1        //true
!!'0' == '0'    //false

How about that last line?

JavaScript coerces the first operand and then evaluates the entire expression. The first operand coerces to true leaving true == '0' as the expression to be evaluated. Under this scenario, the types of each value are different and one of them is a boolean, so JavaScript tries to convert each to a number. This results in 1 === NaN, which is obviously false. For another look at how the double equals comparison operator works in JavaScript, read this blog post.

If Blocks

In the context of if blocks, coercion applies very similarly.

if ('hi') { 
	console.log('hi');  //hi
if (1) { 
	console.log(1);     //1
if ('') { 
	console.log('');    // statement never reached

JavaScript coerces the string 'hi' the same way it would if we put !!'hi'. We could pass in a variable and it would be coerced the same way as well.

var val = 'hi';
if (val) { 
	console.log(val);	//hi


if ('hi') { 
	console.log('hi' == false);	//false
	console.log('hi' == true);	//false

Wait a second. Shouldn’t console.log('hi' == true); produce true? This is mostly a mind trick. We see 'hi' is truthy in the if statement, but when it’s compared to true with the double equals operator, it behaves similar to the example above–JS tries to convert 'hi' to a number first which results in NaN and then the whole expression is evaluated and it produces false. If this doesn’t make sense, you really need to read up on the double equals operator to understand how it works.

Why !!

So why would you ever use !!? It’s mostly a concise way of converting a value to a boolean or making sure it is a boolean. Alternatively, you could use the Boolean function, but it’s important to understand this has some tricks too. Before revealing the result below or reading any further, take a guess at what each line yields:

!!new Boolean(false)
hover for result


The new prefix constructs a boolean object. An object coerced yields true.

!new Boolean(false) !== !!!{}
hover for result


More JavaScript