I am confused by the following code:
Boolean(' '); // true
Boolean(''); // false
+' '; // 0
+''; // 0
My assumptions:
- Since
Boolean(' ')evaluates totrue,' 'is a truthy value. - Since
Boolean('')evaluates tofalse,''is a falsy value. - Since the unary
+operator attempts to convert its operand into a number, it should convert a falsy value to 0, and a truthy value to 1.
Question:
Why does the unary + operator convert a truthy value (i.e. ' ') to 0?
Please feel free to point out everything that is wrong about my assumptions, and anything that I am missing. Thank you so much!
=================
EDIT AFTER INITIAL THREE REPLIES
Thank you guys, you are great, and your are right! Here's what I found in the ES6 specs:
"The conversion of a String to a Number value (...:) This value is determined in two steps: first, a mathematical value (MV) is derived from the String numeric literal; second, this mathematical value is rounded as described below. The MV on any grammar symbol, not provided below, is the MV for that symbol defined in 11.8.3.1.
The MV of StringNumericLiteral ::: [empty] is 0.
The MV of StringNumericLiteral ::: StrWhiteSpace is 0.
The MV of StringNumericLiteral ::: StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt is the MV of StrNumericLiteral, no matter whether white space is present or not."
(Source: https://262.ecma-international.org/6.0/#sec-runtime-semantics-mv-s)
So that would explain why both +'' and +' ' evaluate to 0.
I was also confused why Boolean() did not evaluate both to false:
The abstract operation ToBoolean converts argument to a value of type Boolean according to Table 10: (...) String: Return false if argument is the empty String (its length is zero); otherwise return true.
Source: https://262.ecma-international.org/6.0/#sec-toboolean
So that's why Boolean(''); // false and Boolean(' '); // true.
Thank you so much for your help! :)