Common JavaScript Confusions
A collection of surprising JavaScript behaviors that trip up almost everyone at some point.
What is it?
JavaScript mostly behaves as you'd expect. But it has a few well-known quirks, left over from decades-old design decisions, that surprise even experienced developers. Knowing them ahead of time turns a confusing bug into "oh, that's just how it works."
Explain like I'm 10
Think of the odd exceptions in English spelling. 'i before e except after c' has plenty of exceptions, but once you've been warned, they stop being surprises and become 'the known weird parts.'
Examples
A handful of classic surprises
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(NaN === NaN); // false
console.log(typeof null); // "object"
console.log([] + []); // "" (empty string)
console.log([1, 2] + [3, 4]); // "1,23,4"More surprises: closures in loops, and array holes
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// logs: 3, 3, 3 — not 0, 1, 2 (all three closures share the same "var i")
console.log([1, , 3].length); // 3 — the missing middle slot still countsWith var, every callback closes over the same variable, and the loop has already finished by the time they run. Switching to let fixes it, because each iteration gets its own binding.
How it works
Each one comes from a specific rule:
- Floating-point numbers are stored in binary and can't represent every decimal exactly.
NaNis defined to be unequal to everything, including itself.typeof nullreturning "object" is a bug from JavaScript's first version, never fixed so existing code keeps working.+on non-numbers converts its operands to primitives (often strings) before combining them.
Why does it exist?
These aren't bugs in your program. They're decisions (or accidents) built into the language decades ago, and changing them would break the web. Learn them once and you'll spot the pattern instantly instead of losing an hour.
When to use it
Remember this list whenever a result looks "obviously wrong": comparing floating-point numbers for exact equality, checking for NaN, or using typeof for a null check.
When not to use it
Don't add workarounds everywhere up front; most code never hits float precision or NaN in a way that matters. Add the specific safeguard (Number.isNaN, rounding, an explicit null check) only where the code depends on it.
Common mistakes
Comparing floating-point calculations with
===instead of checking they're 'close enough' (within a small tolerance).Using
someValue === NaNto check for NaN. It's always false; useNumber.isNaN(someValue)instead.Checking
typeof value === "object"to detect an object and forgetting thatnullpasses that check too.
Practice exercises
- Easy:
Predict, then verify, the result of
0.1 + 0.2 === 0.3. - Medium:
Write a function
isNullOrObject(value)that correctly distinguishesnullfrom a real object. - Hard:
Write a function
safeEquals(a, b)that correctly returns true forNaN, NaNwhile behaving like===for everything else.
Interview questions
Why doesn't `0.1 + 0.2` equal `0.3` exactly in JavaScript?
Numbers are stored as binary floating-point, and most decimal fractions (including 0.1 and 0.2) can't be stored exactly in binary. The tiny rounding error makes the sum 0.30000000000000004 instead of 0.3.
Given floating-point imprecision, how should you actually compare two computed decimal numbers for "equality"?
Check that their difference is below a small tolerance (an 'epsilon'), like Math.abs(a - b) < 0.00001, instead of using === on results of floating-point math.
Why is `NaN === NaN` false, and how do you correctly check whether a value is `NaN`?
NaN is defined to be unequal to every value, including itself, so === can never confirm it. Use Number.isNaN(value), which doesn't rely on equality.
Why does `typeof null` return `"object"` even though `null` isn't really an object?
It's a bug from JavaScript's first version: null and objects happened to share an internal type tag. It was never fixed because too much existing code would break.
Given that `typeof anArray` also returns `"object"`, how do you actually detect whether a value is specifically an array?
Use Array.isArray(value). typeof can't tell an array from a plain object or any other non-primitive; they're all "object" to it.
Why does `typeof someFunction` return `"function"` instead of `"object"`, given that functions are technically objects too?
typeof reports anything callable as "function" for convenience, even though a function really is an object (with extra internal behavior for being called).
Predict the output: `console.log([] + []);`
"" (an empty string). When neither operand is a number, + converts both to primitives. An empty array becomes "", and two empty strings joined are still "".
Predict the output: `console.log([1, 2] + [3, 4]);`
"1,23,4". Each array becomes a string ("1,2" and "3,4"), and + joins them with no separator.
Predict the output: `console.log([] == false);`
true. Comparing an object with a boolean, == coerces both toward numbers: false becomes 0, and the array becomes the string "", then the number 0. So 0 == 0 is true.
What's the difference between `null == undefined` and `null === undefined`?
null == undefined is true: they're defined to loosely equal each other and nothing else. null === undefined is false, because === never coerces and they're different types.
Predict the output: `console.log("0" == false);` versus `console.log("0" === false);`
== gives true: both sides become numbers, false to 0 and "0" to 0. === gives false, because a string and a boolean are never strictly equal.
Predict the output: `console.log([1] == 1);`
true. [1] becomes the string "1", then the number 1, which equals 1.
Why is `{} === {}` always false, even when both object literals look identical?
=== on objects compares identity (the same object in memory), not contents. Two separately created objects are always different references, however alike they look.
Predict the output: `console.log([25, 1, 10, 2].sort());`
[1, 10, 2, 25]. The default .sort() converts elements to strings and compares them character by character, so "10" comes before "2" because "1" comes before "2". Use a numeric compare function like (a, b) => a - b to sort numbers.
Does `Array.prototype.sort()` mutate the original array, or return a new one?
It sorts in place, mutating the original, and returns that same array. To keep the original order, copy first, e.g. [...arr].sort().
Why does `[NaN].indexOf(NaN)` return `-1`, and what should you use instead?
.indexOf() compares with ===, and NaN === NaN is always false, so it never finds NaN. .includes() uses SameValueZero, which treats NaN as equal to itself, so [NaN].includes(NaN) returns true.
Predict the output: `for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }` versus the same loop with `let` instead of `var`.
With var: 3, 3, 3. All three callbacks share one i, which is already 3 when the loop ends and they run. With let: 0, 1, 2, because let creates a new i for each iteration, so each callback captures its own value.
What is the "temporal dead zone" for `let` and `const`?
The stretch of code from the start of a scope to the let/const declaration line. The variable exists (it's hoisted), but accessing it throws a ReferenceError instead of giving undefined. A var is set to undefined immediately.
Predict the output: `console.log(x); let x = 5;`
It throws a ReferenceError ("Cannot access 'x' before initialization"). x is in the temporal dead zone until its declaration runs, so it fails loudly instead of returning undefined like a var would.
How can forgetting `var`/`let`/`const` before an assignment accidentally create a global variable?
In non-strict ('sloppy') mode, assigning to a name that was never declared creates a new property on the global object instead of throwing. Strict mode (and modules, which are strict by default) throws a ReferenceError instead.
Predict the output: `console.log("5" - 2); console.log("5" + 2);`
3 and "52". - is only numeric, so it converts both sides to numbers: 5 - 2 = 3. + also means string concatenation, so when either side is a string it joins them: "5" + "2" = "52".
Why are `[]` and `{}` both truthy in an `if` check, even though they're both "empty"?
The falsy values are a fixed list: false, 0, -0, "", null, undefined and NaN. Every object, including empty arrays and plain objects, is truthy no matter what it holds.
Predict the output: `console.log(new Array(3).length); console.log(new Array(3));`
3 for the length, but the array is [ <3 empty items> ]: three holes, not three undefined elements. .forEach() and .map() skip holes, unlike an array actually filled with undefined (like Array(3).fill(undefined)).
Predict the output: `function f() { return { ok: true }; } console.log(f());`
undefined. Automatic semicolon insertion adds a semicolon right after return when a newline follows it, making it return;. The object literal on the next line is unreachable.
Predict the output: `console.log(Object.keys({ b: 1, 2: "x", a: 3, 1: "y" }));`
["1", "2", "b", "a"]. Keys that look like non-negative integers always come first, in ascending numeric order. The other string keys follow in insertion order.
Why has it historically been important to always pass an explicit radix to `parseInt`, like `parseInt(str, 10)`?
Without a radix, older engines guessed the base from the string. A leading 0 could make parseInt("08") parse as octal (base 8), where 8 isn't even a valid digit. Modern engines default to base 10 unless there's a leading 0x, but passing the radix removes any doubt.
Predict the output: `console.log("10" < "9");`
true. Two strings are compared character by character, not by numeric value. "1" comes before "9", so "10" is 'less than' "9" as text.
Why can you call a function before its definition appears later in the same scope, if it's a function declaration but not if it's a function expression assigned to a `var`?
A function declaration is hoisted with its body, so it works from the top of its scope. A var holding a function expression is hoisted only as a name set to undefined; the function isn't assigned until that line runs. Calling it earlier throws ('is not a function') because the value is still undefined.
Why doesn't `typeof someUndeclaredVariable` throw an error, while directly referencing `someUndeclaredVariable` does?
typeof is designed to return "undefined" for a name that was never declared, a legacy safety net for checking whether a global exists. Using that name in any other expression throws a ReferenceError.
Why might `delete obj.someProperty` silently do nothing instead of removing the property or throwing?
If the property is non-configurable (as many built-in and some explicitly defined properties are), delete fails without throwing in non-strict mode. It returns false, but code that ignores the return value never notices, and the property stays.