Classic JS Gotchas
Survive the technical interview. Master the famous JavaScript quirks surrounding Type Coercion, asynchronous loops, and the 'this' keyword.
The JavaScript Quirks
JavaScript was created in just 10 days in 1995. To make it forgiving for beginners, its creator added aggressive Type Coercion and relaxed scoping rules. Decades later, these features have become famous 'gotchas' that interviewers love to test.
A 'Gotcha' is a piece of code where the obvious, intuitive answer is completely wrong because of a hidden engine mechanic.
Why interviewers care
Interviewers don't ask these questions to trick you; they ask them to see if you understand the underlying engine. If you know *why* 0 == false but 0 !== false, it proves you understand Type Coercion versus Strict Equality.
Memorizing the answers isn't enough. You must understand the mechanics.
The Three Classic Traps
**1. The typeof Trap:**
javascript
typeof null; // 'object' (A famous bug from 1995)
typeof NaN; // 'number' (Not-A-Number is technically a numeric type)
**2. The var Loop Trap:**
javascript
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Logs: 3, 3, 3. Because 'var' is globally scoped, the loop finishes before the timeouts run, leaving 'i' at 3.
**3. The Context Trap:**
javascript
const dog = { sound: 'woof', bark() { return this.sound; } };
const looseBark = dog.bark;
looseBark(); // undefined. The function lost its object context!
The Hot Seat
Welcome to your technical interview. Pick a famous trap below, make your prediction, and then run the engine evaluation to see how JavaScript actually interprets the code.
The Engine Decoder
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
typeof nullis'object'due to a historical bug.typeof NaNis'number'(Not-A-Number is a numeric data type).- Always use strict equality (
===) to avoid bizarre Type Coercion bugs. - Loops with
varandsetTimeoutwill share a single variable. Useletto bind a new variable per iteration. - Extracting a function from an object strips its
thiscontext. Use.bind()to lock it down.
Done with this concept?
Mark it complete to track your progress. No login needed.