Skip to content

Latest commit

 

History

History
63 lines (45 loc) · 2.35 KB

11.Implicit-Coercion-II.md

File metadata and controls

63 lines (45 loc) · 2.35 KB

11. Implicit Coercion II

Problem

https://bigfrontend.dev/quiz/Implicit-Conversion-II

Problem Description

What does the code snippet below output by console.log?

console.log([] + []);
console.log([] + 1);
console.log([[]] + 1);
console.log([[1]] + 1);
console.log([[[[2]]]] + 1);
console.log([] - 1);
console.log([[]] - 1);
console.log([[1]] - 1);
console.log([[[[2]]]] - 1);
console.log([] + {});
console.log({} + {});
console.log({} - {});

Answer

console.log([] + []); // ""
console.log([] + 1); // "1"
console.log([[]] + 1); // "1"
console.log([[1]] + 1); // "11"
console.log([[[[2]]]] + 1); // "21"
console.log([] - 1); // -1
console.log([[]] - 1); // -1
console.log([[1]] - 1); // 0
console.log([[[[2]]]] - 1); // 1
console.log([] + {}); // "[object Object]"
console.log({} + {}); // "[object Object][object Object]"
console.log({} - {}); // NaN

Explanation

  • [] + [] returns "", because [] is coerced to an empty string using Array's toString() method. First, + operator tries to convert [] into a primitive value with Array's valueOf() method, but it returns the array itself, so the valueOf() method is ignored. Then + uses Array's toString() as fallback and it returns an empty string.

  • [] + 1 returns "1", because + operator tries string concatenation before numeric addition, if one of the operands is a string.. The same logic also applies to [[]] + 1, [[1]] + 1 and [[[[2]]]] + 1.

  • [] - 1 returns -1, because - operator triggers numeric conversion for []: first, [] is converted to an empty string using the toString() method; then the empty string is converted to 0. The same logic applies to [[]] - 1, [[1]] - 1 and [[[[2]]]] - 1.

  • [] + {} returns "[object Object]", because + operator tries to convert both [] and {} to primitive values. Since Object's valueOf() method returns the object itself, {} is converted to "[object Object]" using the toString() method. The same logic applies to {} + {}.

  • {} - {} returns NaN, because - operator triggers numeric conversion for {}: first, {} is coerced to "[object Object]" using the toString() method; then "[object Object]" is converted to NaN.

Reference

JavaScript type coercion explained