Contents
The other day on Twitter,@TaneoKoyama was doing an interesting tweet, so I’m going to go into this one step deeper.
console.log(2==1==0); // => true
This is really true when you try it.
interesting.
Let’s disassemble and examine one by one.
console.log(2==1); // => false
↑ At this stage, it will be false …
console.log(false==0); // => true
but this is true, it is Kimo of this code.
According to the JavaScript specification, “number 0” is false.
As a result, 2==1==0there will be situations where it becomes true.
console.log(0==1==2); // => false
The result is false.
When disassembling, it is processing ….
console.log(0==1); // => false
console.log(false==2); // => false
You can confirm that the process is being performed from the left.
console.log(2===1===0); // => false
Yes, it has been false.
Difference between equality operator (==) and strict equality operator (===)
Although it is the equivalence operator “==” which is usually used casually, there was a characteristic that can be judged by type conversion.
As a result, false (boolean type) is converted to “0”, so0=0It will be judged that.
On the other hand, the strict equality operator (===) does not perform type conversion.
So false is false and 0 is 0.
In other words, even if it judges, this is not equivalent.
In the case of a similar example
console.log(null == undefined); // => true console.log(null === undefined); // => false
console.log(0 == ''); // => true console.log(0 === ''); // => false
- x==y==z, it is processed from the left
- “==” and “===” are clearly different operators.
- Be careful about type conversion of “==” In
- JS, 0 (numeric value), null, undefined, ” (empty character) are treated as false
that’s all.
Thank you until the end.
Discussion about this post