Technical Articles
Funny JavaScript
We all know that JavaScript is quite a funny language with tricky parts. Some of them can quickly turn our everyday job into hell, and some of them can make us laugh out loud.
Let’s start:
a) [] is equal ![].
[] == ![]; // -> true
Explanation:
The abstract equality operator converts both sides to numbers to compare them, and both sides become the number 0 for different reasons. Arrays are truthy, so on the right, the opposite of a truthy value is false, which is then coerced to 0. On the left, however, an empty array is coerced to a number without becoming a boolean first, and empty arrays are coerced to 0, despite being truthy.
Also please check :
1): 12.5.9 – Logical NOT Operator(!)
2): 7.2.13 – Abstract Equality Comparison
Try to play:
+[] == +![]
0 == +false
b) true is not equal ![], but not equal [] too.
true == []; // -> false
true == ![]; // -> false
false == []; // -> true
false == ![]; // -> true
Explanation:
true == []; // -> false
true == ![]; // -> false
// According to the specification
true == []; // -> false
toNumber(true); // -> 1
toNumber([]); // -> 0
1 == 0; // -> false
true == ![]; // -> false
![]; // -> false
false == []; // -> true
false == ![]; // -> true
// According to the specification
false == []; // -> true
toNumber(false); // -> 0
toNumber([]); // -> 0
0 == 0; // -> true
false == ![]; // -> false
![]; // -> false
false == false; // -> true
c) NaN is a Number
typeof NaN; // -> 'number'
instanceof NaN; // -> 'SyntaxError'
Check:
Try to play:
NaN === NaN; -> ?
d) null and [] are objects
typeof []; // -> 'object'
typeof null; // -> 'object'
null instanceof Object; // false
Explanation:
As section c) described, For null, ordinary, standard exotic and non-standard exotic objects, which do not implement [[Call]], it returns the string object.
So we can use toString function to check the type of an object.
Object.prototype.toString.call(null); // -> '[object Null]'
Object.prototype.toString.call([]); // -> '[object Array]'
e) null and relational operators
null > 0; // false
null == 0; // false
null >= 0; // true
Explanation:
if null is less than 0 is false, then null >= 0 is true. Read in-depth explanation for this here.
Have fun, please check here for more details, also about Denys Dovhan.
Good
great post