Paul Kent

.NET Developer (AngularJS, jQuery, C#, Dependency Injection, Unit Testing, Onion Architecture, Azure Cloud)

Why does ("string" == true) return false in JavaScript if a string evaluates to a truthy value?

Let's look at the example code below and its output in JS Bin:

var x = "string";

console.log("!!x is " + (!!x));
console.log("x == true is " + (x == true));

You might be surprised that the second statement actually prints false instead of true, even though both sides of the == operator are truthy values. So why is this the case?

This is because when you're using the double equals operator (==) and you're comparing a string with a boolean, both values first get converted to a Number and then they are compared.

If we convert a boolean to a number then a true converts to 1 and false converts to 0. A string like '1' can be converted to 1 but a string like 'string' can't be converted to a number so it gets converted to NaN.

So in the above code example the comparison becomes:


NaN == 1

Now NaN compared to anything is false. Hence the expression ends up being false.

If you want to see if a value is truthy, use the not operator twice (!!). This is also known as 'double bang'.

For example:

var x = "string";

console.log(!!x)
;

This would print true.

Reference:

http://stackoverflow.com/questions/4923631/why-does-ifstring-evaluate-string-as-true-but-if-string-true-does-not

Dependency Injection in under 10 minutes

I made this short video to explain what Dependency Injection is and how to use it to create loosely coupled and easily Unit Testable components.