Today is the first day of the JavaScript course of qiwu front-end training camp. In the afternoon, I introduced the basic types of JavaScript to the students. There was an interesting question in the example. Due to the short time, I failed to explain it in detail. So write an article to explain, just as you:
Question: why [] == false, and!! [] == true?
This is a very confusing question. At first glance, no way? If [] == false then! [] equivalent to!! False, isn’t it false, why is it true? Could it be an engine bug, a mistake?
console.log([] == false, !! [] == true); // true, trueCopy the code
It’s not actually a bug, it has to do with the ECMA specification and type conversions. We know that the non-strict comparison operator == does a cast, so according to ECMA 262 its rule is:
Source:www.ecma-international.org
Take note:
- If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
- Article 9: If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.
So the comparison of [] == false is to perform ToPrimitive(x) on x and then compare it to ToNumber(false) (0).
Look at ToPrimitive:
Source:www.ecma-international.org
Source:www.ecma-international.org
Source:www.ecma-international.org
For ToPrimitive([]), execute [].valueof (), return result [], continue with [].toString(), return “” because Type(result) is Object.
So you actually end up comparing “” == 0, which is true.
Look at!!!!! [] = = false:
Execute first according to priority!! [], according to the specification, actually!! (ToBoolean ([])) :
The ToBoolean rule is:
So ToBoolean([]) is converted to true,!! True is true.
So this is [] == false and!! [] == true That’s why we can’t use if(! If (array.length === 0); if(array.length == 0);
Also, [0] == false and!! [0] == true, now you can figure it out for yourself.
That’s all for today. If you have any questions, please leave a comment