开发者

What Are the Semantics of Javascripts If Statement

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 somewhe开发者_StackOverflow中文版re? Is it consistent cross-browser? Will I ever master javascript?


"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")


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(" ") ?


JavaScript can be quirky with things like this. Note that JavaScript has == but also ===. I would have thought that

" " == true

would be true, but

" " === true

would be false. The === operator doesn't do conversions; it checks if the value and the type on both sides of the operator are the same. The == does convert 'truthy' values to true and 'falsy' values to false.

This might be the answer - from JavaScript Comparison Operators (Mozilla documentation):

Equal (==)

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

Highly recommended: Douglas Crockford on JavaScript.


Answer: aTruthyValue and true are not the same.

The semantic of the if statement is easy:

if(aTruthyValue) {
  doThis
} else {
  doThat
}

Now it's just the definition of what a truthy value is. A truthy value is, unfortunately, not something that is simply "== true" or "=== true".

ECMA-262 1.5 Setion 9.2 explains what values are truthy and which are not.


I recommend using === whenever possible, if only to avoid having existential crises.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜