Tricky JS Output Questions


1️⃣ Hoisting + var

console.log(a);
var a = 10;

Output:

undefined

Why?
var a is hoisted → initialized with undefined


2️⃣ Hoisting + let

console.log(a);
let a = 10;

Output:

ReferenceError

Why?
let is in Temporal Dead Zone


3️⃣ Function vs Variable Hoisting

var a = 10;function a() {
console.log("Hello");
}console.log(a);

Output:

10

Why?
Function is hoisted first, but var a = 10 overrides it


4️⃣ Closure Trick

function test() {
var a = 1;

return function () {
console.log(a);
};
}var fn = test();
test()();
fn();

Output:

1
1

Why?
Closure remembers a


5️⃣ setTimeout + var (Classic 🔥)

for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}

Output:

3
3
3

Why?
var is function-scoped → same i


6️⃣ setTimeout + let

for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}

Output:

0
1
2

Why?
let creates new block scope each iteration


7️⃣ this Keyword

const obj = {
name: "Aditya",
greet: function () {
console.log(this.name);
}
};const fn = obj.greet;
fn();

Output:

undefined (or window.name)

Why?
Function is called without object → this lost


8️⃣ Arrow Function this

const obj = {
name: "Aditya",
greet: () => {
console.log(this.name);
}
};obj.greet();

Output:

undefined

Why?
Arrow function doesn’t have its own this


9️⃣ == vs ===

console.log(0 == false);
console.log(0 === false);

Output:

true
false

🔟 NaN Trick

console.log(NaN == NaN);
console.log(NaN === NaN);

Output:

false
false

👉 Use:

isNaN(NaN); // true

1️⃣1️⃣ typeof null

console.log(typeof null);

Output:

object

👉 This is a JavaScript bug


1️⃣2️⃣ Implicit Coercion

console.log("5" + 2);
console.log("5" - 2);

Output:

"52"
3

1️⃣3️⃣ Array + Object

console.log([] + []);
console.log([] + {});
console.log({} + []);

Output:

""
"[object Object]"
0 // tricky!

1️⃣4️⃣ Boolean Conversion

console.log(Boolean("0"));
console.log(Boolean(0));

Output:

true
false

1️⃣5️⃣ Closures in Loop (Fix Version)

for (var i = 0; i < 3; i++) {
(function (i) {
setTimeout(() => console.log(i), 1000);
})(i);
}

Output:

0
1
2

1️⃣6️⃣ Function Inside Block

if (true) {
function test() {
console.log("Hello");
}
}
test();

Output:

Hello

👉 (Behavior can vary in strict mode)


1️⃣7️⃣ Chained Assignment

var a = b = 10;
console.log(b);

Output:

10

👉 b becomes global variable (bad practice)


1️⃣8️⃣ Object Reference

let obj1 = { name: "A" };
let obj2 = obj1;obj2.name = "B";console.log(obj1.name);

Output:

B

👉 Objects are assigned by reference


1️⃣9️⃣ Event Loop Order 🔥

console.log("Start");setTimeout(() => console.log("Timeout"), 0);Promise.resolve().then(() => console.log("Promise"));console.log("End");

Output:

Start
End
Promise
Timeout

2️⃣0️⃣ Function Length

function test(a, b, c = 3) {}
console.log(test.length);

Output:

2

👉 Default params are not counted


🚀 Interview Strategy

If you master these:

  • Hoisting
  • Closures
  • this
  • Event Loop
  • Type coercion

👉 You can clear 90% JS interviews