Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Are the Semantics of Javascripts If Statement

Tags:

javascript

I always thought that an if statement essentially compared it's argument similar to == true. However the following experiment in Firebug confirmed my worst fears—after writing Javascript for 15 years I still have no clue WTF is going on:

>>> " " == true
false
>>> if(" ") console.log("wtf")
wtf

My worldview is in shambles here. I could run some experiments to learn more, but even then I would be losing sleep for fear of browser quirks. Is this in a spec somewhere? Is it consistent cross-browser? Will I ever master javascript?

like image 433
gtd Avatar asked Oct 23 '09 21:10

gtd


2 Answers

"If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers; if either operand is a string, the other one is converted to a string."

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators

So the first one does:

Number(" ")==Number(true)

While the second one is evaluated like this:

if(Boolean(" ")==true) console.log("wtf")
like image 103
kloffy Avatar answered Sep 22 '22 10:09

kloffy


I am guessing that it is the first part that is a problem, not the second.

It probably does some weird casting (most likely, true is cast to a string instead of " " being cast to a boolean value.

What does FireBug return for Boolean(" ") ?

like image 30
DVK Avatar answered Sep 24 '22 10:09

DVK