marijnh / Eloquent-JavaScript

The sources for the Eloquent JavaScript book
https://eloquentjavascript.net
3.01k stars 793 forks source link

Discrepancy in Chapter 1 about Boolean coercion #442

Closed gareys closed 6 years ago

gareys commented 6 years ago

I mentioned this in gitter, but realized this is probably a better place to discuss things.

While reading chapter 1 in the 3rd edition, a reader in our Dev Book Club discord server pointed out that the statement below is not entirely true.

The rules for converting strings and numbers to Boolean values state that 0, NaN, and the empty string ("") count as false, while all the other values count as true. Because of this, expressions like 0 == false and "" == false are also true.

Reference: https://eloquentjavascript.net/01_values.html#p_N4OuWeYOwF

Focusing on the part about "" == false we found there is a lot more going on.

In this case, the right hand side of the equality comparison, false, is first coerced to 0. Then, the left hand side "" is coerced to 0. Then, they are compared. the final form of "" == false is +0 == +0.

While in most cases, "" (empty string) is coerced to a Boolean false value, as mentioned in 7.1.2 of the ECMAscript spec. It is not coerced to a Boolean in the comparison to false as seen in the comparison expression "" == false. So it is not an example of Boolean coercion as used in your statement in Chapter 1.

Here are my sources: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf Sections 7.1.2, 7.2.13 https://stackoverflow.com/a/42770966

LeoSantos7 commented 6 years ago

This may be relevant since thinking that those values are converted to booleans in those comparisons would be inconsistent when comparing stuff like ( "0" == false ) and ( " \n\t " == false). They both return true even though Boolean("0") and Boolean(" \n\t ") are true.

marijnh commented 6 years ago

That section has nothing to do with ==. It is about converting to boolean type. I.e. what happens if you put such values as the condition to if.

gareys commented 6 years ago

@marijnh the point we are trying to make is that your use of "" == false as an example of converting to Boolean type is not an example of converting to Boolean type. It is actually coercing both values to a number. I provided the ECMAscript spec and some more details to explain why this happens, but this example doesn't really go along with your topic of Boolean coercion.

marijnh commented 6 years ago

That's not an example of converting to boolean, it's an example of == not doing what you want. I can see how it can confuse people. I'll take another look at it.

gareys commented 6 years ago

Thank you, @marijnh

marijnh commented 6 years ago

Does patch 69e8e8e improve things for you?

LeoSantos7 commented 6 years ago

Awesome! Thanks @marijnh

gareys commented 6 years ago

@marijnh this looks great.