3 ms·
if (2) { console.log('yes') } > yes > undefined if (2==true) { console.log('yes') } > undefined I would have thought these would be the same - what's t
by farnsworth 12y ago
if (2) { console.log('yes') }
> yes
> undefined
if (2==true) { console.log('yes') }
> undefined
I would have thought these would be the same - what's the difference between being "truthy" in the first case, and being ==true, as in the second?
- Xophmeister 12y ago`2` is truthy, but `==` forces a coercion, which ends up converting Boolean `true` to a number, which is 1 (`ToNumber(true) := 1` [1]), which is ostensibly not equal to 2. 1. http://www.ecma-international.org/ecma-262/5.1/#sec-9.3 http://www.ecma-international.org/ecma-262/5.1/#sec-9.3
- Groxx 12y agoI forget the specifics of Javascript, but in many languages "truthy" (used in ifs) is usually closer to "!= false" than "== true". e.g. any object or non-zero number is truthy (except "" in JS), but only a handful are actually == true or == false.
- deleted 12y ago[deleted]
- farnsworth 12y agoGood point, same in JS: if (2 != false) console.log('yes') > yes false goes to 0 and 2 != 0.
- farnsworth 12y agoWell I can answer that myself thanks to sheetjs' link to the spec. Case 1: From the section for 'if ()', http://www.ecma-international.org/ecma-262/5.1/#sec-12.5 http://www.ecma-international.org/ecma-262/5.1/#sec-12.5, If ToBoolean(GetValue(exprRef)) is true, ... new Boolean(2) => true, so 2 is 'truthy' alone inside if (). Case 2: From the == section, http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3 http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3, If Type(y) is Boolean, return the result of the comparison x == ToNumber(y). So the boolean is coerced to a number, and new Number(true) => 1. I wonder why they didn't do it the other way around, and make the number a boolean like above. You're losing seemingly useful information with new Number(<boolean>)
- deleted 12y ago[deleted]
- deleted 12y ago[deleted]