JavaScript can sometimes behave in unexpected ways. Below are 10 tricky questions with detailed explanations that will help you better understand the quirks of the language.
Not a Medium member? Read this article here
1. What will the following output?
console.log(0.1 + 0.2 === 0.3);
Answer: false
Explanation:
In JavaScript (and most programming languages), floating-point arithmetic isn’t always precise.0.1 + 0.2
results in 0.30000000000000004
, not exactly 0.3
.
2. What’s the output?
console.log([] + []);
console.log([] + {});
console.log({} + []);
Answer:
""
"[object Object]"
0
Explanation:
[] + []
returns an empty string because JavaScript converts arrays to strings during concatenation.[] + {}
becomes"[object Object]"
because{}
is converted to its string representation.{}
when placed at the beginning of a line is interpreted as a block, so{} + []
returns0
.
3. What will this code log?
console.log(typeof null);
Answer: "object"
Explanation:
This is a well-known bug in JavaScript. Although null
represents the absence…