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,23 10 52 3 true false true object number
[1,2,3] 10 7 3 false false false null NaN
1,23 10 52 3 false false true object number
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 == 0isfalsebecausenullonly loosely equalsundefined, yetnull >= 0convertsnullto0→true.typeof nullis"object"(a historical bug);NaNis a"number".
Use === and explicit conversions (Number(x), String(x)) in real code.
More Gotchas problems
- var in a Loop with setTimeout · Easy
- Microtasks vs Macrotasks · Medium
- Numeric Enums at Runtime · Medium
- Type Assertions Don't Convert · Easy
- readonly and as const at Runtime · Medium
- Mutable Default Arguments · Easy