Careeroza
Predict the Output
1. var in a loop with setTimeout
Example
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}Output
3 3 3
One shared var i; by the time the callbacks run, the loop has finished and i is 3. With let it prints 0, 1, 2.
2. Event loop order
Example
console.log(1);
setTimeout(() => console.log(2), 0);
Promise.resolve().then(() => console.log(3));
console.log(4);Output
1 4 3 2
Synchronous code first (1, 4), then microtasks (3), then the timer (2).
3. Type coercion
Example
console.log("2" + 2 * "2");
console.log([] + []);
console.log(typeof NaN);
console.log(0.1 + 0.2 === 0.3);Output
24 number false
* converts to numbers first (4), then + with a string concatenates: "24". Empty arrays become empty strings. NaN is a number. Floating-point rounding makes the last one false.
4. Hoisting
Example
console.log(typeof hoisted, typeof notHoisted);
function hoisted() {}
var notHoisted = function () {};Output
function undefined
The function declaration is fully hoisted; the var exists but is still undefined.
5. this in a callback
Example
const obj = {
name: "Asha",
regular() { return [1].map(function () { return this?.name; }); },
arrow() { return [1].map(() => this.name); },
};
console.log(obj.regular(), obj.arrow());Output
[ undefined ] [ 'Asha' ]
The regular callback is called without an object, so this is not obj; the arrow function uses this from arrow(), which is obj.
6. Object references
Example
const a = { x: 1 };
const b = a;
b.x = 2;
const c = { ...a };
c.x = 3;
console.log(a.x, b.x, c.x);Output
2 2 3
a and b are the same object; c is a shallow copy.