# Classic JS Gotchas

> Survive the technical interview. Master the famous JavaScript quirks surrounding Type Coercion, asynchronous loops, and the 'this' keyword.

Subject: JavaScript | Lesson 63 of 63 | 9 min read
Interactive lesson: https://codewithanimation.in/javascript/interview-gotchas
Previous: [Data Structures & Big-O](https://codewithanimation.in/javascript/data-structures-and-big-o.md)

## 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!
```

## Common mistake: Type Coercion Madness

When you use the loose equality operator (`==`), JavaScript will try to forcefully convert the types so they match before comparing them.

`[] == 0` is `true`. `[]` converts to an empty string `""`, which then converts to the number `0`.

Never use `==`. Always use strict equality `===`, which checks both the value AND the type without mutating them.

## Tip: Fixing the var loop

To fix the classic `setTimeout` loop trap, simply change `var` to `let`. Because `let` is block-scoped, it creates a brand new binding for `i` in memory for every single iteration of the loop, preserving the correct value for the timeouts.

## Try it: 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 animation is on the lesson page and is not part of this text version: https://codewithanimation.in/javascript/interview-gotchas

## Check yourself

### Question 1

What is the output of `typeof null`?

- A. 'object'
- B. 'null'
- C. 'undefined'

Correct answer: A

It returns 'object'. This is a famous bug from the very first version of JavaScript in 1995. Fixing it now would break millions of legacy websites, so it remains forever.

- Why not B: Incorrect. While logical, JavaScript has a famous legacy bug that classifies null as an object.
- Why not C: Incorrect. null and undefined are different.

### Question 2

Why does `for (var i=0; i<3; i++) { setTimeout(()=>console.log(i), 0); }` log `3, 3, 3`?

- A. Because `var` is function/globally scoped, so there is only one `i` in memory. By the time the asynchronous timeouts run, the loop has already finished and `i` is 3.
- B. Because `setTimeout` runs backwards.
- C. Because `0` is passed as the delay.

Correct answer: A

The loop runs instantly. `i` becomes 3. Then, the Event Loop pushes the three timeout callbacks onto the Call Stack. They all look up the single global `i`, which is now 3.

- Why not B: Incorrect. It runs based on the event loop queue.
- Why not C: Incorrect. Even with a 0ms delay, callbacks are pushed to the Web API queue and must wait for the main thread to finish.

### Question 3

How do you extract a method from an object without losing its `this` context?

- A. Use `.bind()`: `const fn = obj.method.bind(obj);`
- B. Use `.toString()`: `const fn = obj.method.toString();`
- C. You can just extract it normally: `const fn = obj.method;`

Correct answer: A

The `.bind()` method creates a brand new function that is permanently hard-coded to use the object you pass in as its `this` context.

- Why not B: Incorrect. That converts the function to text.
- Why not C: Incorrect. Doing this strips the function of its object context, making `this` point to the global window.

## Remember this

- `typeof null` is `'object'` due to a historical bug.
- `typeof NaN` is `'number'` (Not-A-Number is a numeric data type).
- Always use strict equality (`===`) to avoid bizarre Type Coercion bugs.
- Loops with `var` and `setTimeout` will share a single variable. Use `let` to bind a new variable per iteration.
- Extracting a function from an object strips its `this` context. Use `.bind()` to lock it down.
