Skip to content

Latest commit

 

History

History
52 lines (40 loc) · 1.7 KB

30.Equal-II.md

File metadata and controls

52 lines (40 loc) · 1.7 KB

30. Equal II

Problem

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

Problem Description

What does the code snippet below output by console.log? ref to the The Abstract Equality Comparison Algorithm

console.log([1] == 1);
console.log([1] == '1');
console.log(['1'] == '1');
console.log(['1'] == 1);
console.log([1] == ['1']);
console.log(new Boolean(true) == 1);
console.log(new Boolean(true) == new Boolean(true));
console.log(Boolean(true) == '1');
console.log(Boolean(false) == [0]);
console.log(new Boolean(true) == '1');
console.log(new Boolean(false) == [0]);
console.log(null == undefined);

Answer

console.log([1] == 1); // true
console.log([1] == '1'); // true
console.log(['1'] == '1'); // true
console.log(['1'] == 1); // true
console.log([1] == ['1']); // false
console.log(new Boolean(true) == 1); // true
console.log(new Boolean(true) == new Boolean(true)); // false
console.log(Boolean(true) == '1'); // true
console.log(Boolean(false) == [0]); // true
console.log(new Boolean(true) == '1'); // true
console.log(new Boolean(false) == [0]); // false
console.log(null == undefined); // true

Explanation

  • == tries to convert the operands if they are of different types. In [1] == ['1'], the operands are of the same type, so type coercion doesn't happen. Since arrays are the reference data types, we are comparing two references that point to different memory location, thus [1] === ['1'] returns false. The same logic applies to the new Boolean(true) == new Boolean(true) case and the new Boolean(false) == [0] case.

  • new Boolean(true).valueOf() returns true, so new Boolean(true) == 1 returns true.