Predict the output · Node.js

Type Coercion Surprises

Medium Predict the output Seen at Amazon, Atlassian

What are the four lines of output?

What does this print?

console.log([1, 2] + [3]);
console.log("5" * "2", "5" + 2, "5" - 2);
console.log([] == false, null == 0, null >= 0);
console.log(typeof null, typeof NaN);
  1. 1,23
    10 52 3
    true false true
    object number
  2. [1,2,3]
    10 7 3
    false false false
    null NaN
  3. 1,23
    10 52 3
    false false true
    object number
  4. 1,2,3
    10 52 3
    true true true
    null number

Check your answer

Loading the editor… (JavaScript is required to run code in your browser.)

Solution

Show the answer

The output is:

1,23
10 52 3
true false true
object number
  • Arrays are converted to strings for +: "1,2" + "3" → "1,23".
  • * and - convert strings to numbers (10, 3), but + with a string concatenates ("52").
  • [] == false → "" == 0 → 0 == 0 → true. null == 0 is false because null only loosely equals undefined, yet null >= 0 converts null to 0 → true.
  • typeof null is "object" (a historical bug); NaN is a "number".

Use === and explicit conversions (Number(x), String(x)) in real code.