https://bigfrontend.dev/quiz/Equal-1
What does the code snippet below output by console.log
?
console.log(0 == false);
console.log('' == false);
console.log([] == false);
console.log(undefined == false);
console.log(null == false);
console.log('1' == true);
console.log(1n == true);
console.log(' 1 ' == true);
console.log(0 == false); // true
console.log('' == false); // true
console.log([] == false); // true
console.log(undefined == false); // false
console.log(null == false); // false
console.log('1' == true); // true
console.log(1n == true); // true
console.log(' 1 ' == true); // true
When two values are compared with ==
(and !=
), the Abstract Equality Comparison Algorithm is used.
If the two values are of different types, JavaScript converts them to the same type before comparing:
- If one of the operands is
Boolean
, the Boolean is converted to 1 if it istrue
and +0 if it isfalse
. - When comparing a number to a string, JavaScript tries to convert the string to a numeric value.
- If one of the operands is an object or an array, JavaScript tries to convert it to a primitive value using the
valueOf()
ortoString()
method.
[]
is converted to ''
using toString()
, so [] == false
returns true
.
null
is only comparable to undefined
in the Abstract Equality Comparison Algorithm, therefore undefined == false
and null == false
both return false
.
Since true
is converted to 1
, 2 == true
returns false
.