Skip to content

Latest commit

 

History

History
59 lines (40 loc) · 1.78 KB

10.equal.md

File metadata and controls

59 lines (40 loc) · 1.78 KB

10. Equal

Problem

https://bigfrontend.dev/quiz/Equal-1

Problem Description

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);

Answer

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

Explanation

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 is true and +0 if it is false.
  • 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() or toString() 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.

Reference

Equality (==)