101 JavaScript Output-Based Interview Questions (With Options & Explanations)
Output-based JavaScript questions are a staple of frontend interviews at top tech companies. They test whether you truly understand how the JS engine parses, hoists, coerces, and executes code — beyond just memorizing syntax.
Below is a curated list of 101 JavaScript output-based questions. Each question comes with 4 options and a collapsible answer with a detailed explanation. Try predicting the output before opening the answer!
Part 1: Hoisting, Scope & Temporal Dead Zone (Q1–Q15)
1. var and let hoisting
function sayHi() {
console.log(name);
console.log(age);
var name = "Lydia";
let age = 21;
}
sayHi();
- A)
Lydiaandundefined - B)
LydiaandReferenceError - C)
ReferenceErrorandReferenceError - D)
undefinedandReferenceError
Show Answer & Explanation
Answer: D) undefined and ReferenceError
Explanation: Inside sayHi, var name is hoisted and initialized with undefined, so console.log(name) prints undefined. let age is also hoisted, but it remains in the Temporal Dead Zone (TDZ) until its declaration line is reached, throwing a ReferenceError.
2. Function declaration vs var expression
console.log(typeof foo);
var foo = "hello";
function foo() {}
- A)
"string" - B)
"function" - C)
"undefined" - D)
ReferenceError
Show Answer & Explanation
Answer: B) "function"
Explanation: During the creation phase, function declarations are hoisted with their full body before var declarations. Since foo is already bound to a function, var foo is a no-op during hoisting; the assignment foo = "hello" happens later at runtime.
3. Variable shadowing with let
let x = 10;
{
let x = 20;
console.log(x);
}
console.log(x);
- A)
20and20 - B)
10and10 - C)
20and10 - D)
SyntaxError
Show Answer & Explanation
Answer: C) 20 and 10
Explanation: let is block-scoped. The inner let x = 20 creates a separate variable inside the block { ... } that shadows the outer x. Once the block exits, the outer x (10) is unchanged.
4. var inside a block
var a = 1;
{
var a = 2;
}
console.log(a);
- A)
1 - B)
2 - C)
undefined - D)
SyntaxError
Show Answer & Explanation
Answer: B) 2
Explanation: var is function-scoped (or global-scoped), not block-scoped. Both var a declarations refer to the exact same variable, so a = 2 overwrites 1.
5. TDZ with default parameters
function test(a = b, b = 2) {
return a + b;
}
console.log(test());
- A)
4 - B)
NaN - C)
undefined - D)
ReferenceError
Show Answer & Explanation
Answer: D) ReferenceError
Explanation: Default parameters are evaluated left-to-right in their own parameter scope. When a = b runs, b has not been initialized yet and is in the TDZ, throwing ReferenceError: Cannot access 'b' before initialization.
6. Function expression hoisting
bar();
var bar = function () {
console.log("hi");
};
- A)
"hi" - B)
undefined - C)
TypeError - D)
ReferenceError
Show Answer & Explanation
Answer: C) TypeError
Explanation: var bar is hoisted as undefined. Calling bar() attempts undefined(), which throws TypeError: bar is not a function.
7. Named function expression scope
const fn = function myFunc() {
return typeof myFunc;
};
console.log(fn(), typeof myFunc);
- A)
"function"and"function" - B)
"function"and"undefined" - C)
"undefined"and"undefined" - D)
ReferenceError
Show Answer & Explanation
Answer: B) "function" and "undefined"
Explanation: In a named function expression, the name myFunc is only in scope inside the function body itself. Outside, myFunc is not declared, so typeof myFunc safely returns "undefined".
8. Implicit global vs let
function check() {
let a = (b = 0);
a++;
return a;
}
check();
console.log(typeof a, typeof b);
- A)
"undefined"and"undefined" - B)
"number"and"number" - C)
"undefined"and"number" - D)
ReferenceError
Show Answer & Explanation
Answer: C) "undefined" and "number"
Explanation: let a = (b = 0) assigns 0 to b without let/var/const, creating an implicit global b = 0 (in non-strict mode), while a is local to check. Outside, typeof a is "undefined" and typeof b is "number".
9. Hoisting inside if (false)
var x = 1;
function foo() {
if (false) {
var x = 2;
}
console.log(x);
}
foo();
- A)
1 - B)
2 - C)
undefined - D)
ReferenceError
Show Answer & Explanation
Answer: C) undefined
Explanation: var x inside if (false) is still hoisted to the top of foo's function scope and initialized to undefined, shadowing the outer x = 1. Because the if block never executes, x remains undefined.
10. const object mutation
const user = { name: "Alice" };
user.name = "Bob";
console.log(user.name);
- A)
"Alice" - B)
"Bob" - C)
TypeError - D)
SyntaxError
Show Answer & Explanation
Answer: B) "Bob"
Explanation: const prevents reassigning the variable binding (user = ...), not mutating the properties of the object it references.
11. typeof on a TDZ variable
{
console.log(typeof value);
let value = 42;
}
- A)
"undefined" - B)
"number" - C)
ReferenceError - D)
TypeError
Show Answer & Explanation
Answer: C) ReferenceError
Explanation: typeof is safe on undeclared variables, but value IS declared in this block via let value. Accessing it in the TDZ before its initialization throws ReferenceError.
12. Re-declaring var without assignment
var num = 10;
var num;
console.log(num);
- A)
undefined - B)
10 - C)
SyntaxError - D)
ReferenceError
Show Answer & Explanation
Answer: B) 10
Explanation: Re-declaring a var without an initializer does not reset its existing value. num stays 10.
13. Function parameter vs var inside function
function test(x) {
var x;
console.log(x);
}
test(5);
- A)
undefined - B)
5 - C)
SyntaxError - D)
ReferenceError
Show Answer & Explanation
Answer: B) 5
Explanation: var x without an initializer inside the function does not overwrite the parameter x (5).
14. Dynamic scope vs lexical scope
const a = 10;
function foo() {
console.log(a);
}
function bar() {
const a = 20;
foo();
}
bar();
- A)
20 - B)
10 - C)
undefined - D)
ReferenceError
Show Answer & Explanation
Answer: B) 10
Explanation: JavaScript uses lexical (static) scoping. foo was defined in the global scope where a = 10, not inside bar, so it resolves a from its definition environment.
15. delete on a var variable
var x = 10;
console.log(delete x, x);
- A)
trueandundefined - B)
falseand10 - C)
trueandReferenceError - D)
TypeError
Show Answer & Explanation
Answer: B) false and 10
Explanation: Variables declared with var, let, or const cannot be deleted with the delete operator (in non-strict mode delete x returns false; in strict mode it throws a SyntaxError).
Part 2: Closures & Loops (Q16–Q25)
16. Classic var in setTimeout loop
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
- A)
0 1 2 - B)
0 0 0 - C)
3 3 3 - D)
1 2 3
Show Answer & Explanation
Answer: C) 3 3 3
Explanation: var i is shared across all iterations. By the time the setTimeout callbacks run after the loop finishes, i has reached 3, so all three callbacks log 3.
17. let in setTimeout loop
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
- A)
3 3 3 - B)
0 1 2 - C)
0 0 0 - D)
1 2 3
Show Answer & Explanation
Answer: B) 0 1 2
Explanation: let creates a fresh lexical binding for each iteration of the for loop, so each arrow function closes over its own i (0, 1, 2).
18. Closure counter sharing
function makeCounter() {
let count = 0;
return () => ++count;
}
const c1 = makeCounter();
const c2 = makeCounter();
console.log(c1(), c1(), c2());
- A)
1 2 3 - B)
1 1 1 - C)
1 2 1 - D)
0 1 0
Show Answer & Explanation
Answer: C) 1 2 1
Explanation: Each call to makeCounter() creates a new execution context with its own independent count variable. c1 increments its own count (1, 2), while c2 has a separate count starting at 0 (1).
19. Closure capturing stale vs updated variable
function outer() {
let x = 1;
function inner() {
console.log(x);
}
x = 2;
return inner;
}
outer()();
- A)
1 - B)
2 - C)
undefined - D)
ReferenceError
Show Answer & Explanation
Answer: B) 2
Explanation: Closures capture references to variables, not snapshots of their values. When outer() updates x = 2, calling inner() later reads the updated x (2).
20. IIFE fixing var loop
for (var i = 0; i < 3; i++) {
((j) => {
setTimeout(() => console.log(j), 0);
})(i);
}
- A)
3 3 3 - B)
0 1 2 - C)
undefined undefined undefined - D)
2 1 0
Show Answer & Explanation
Answer: B) 0 1 2
Explanation: Passing i by value into an Immediately Invoked Function Expression (IIFE) creates a new parameter j per iteration, preserving 0, 1, and 2.
21. Closure with let inside outer
let count = 0;
(function immediate() {
if (count === 0) {
let count = 1;
console.log(count);
}
console.log(count);
})();
- A)
1and1 - B)
0and0 - C)
1and0 - D)
0and1
Show Answer & Explanation
Answer: C) 1 and 0
Explanation: Inside the if block, let count = 1 shadows the outer count. Outside the if block, console.log(count) accesses the outer count, which is still 0.
22. Multiple functions sharing one closure
function create() {
let n = 10;
return [() => n++, () => n];
}
const [inc, get] = create();
inc();
inc();
console.log(get());
- A)
10 - B)
11 - C)
12 - D)
13
Show Answer & Explanation
Answer: C) 12
Explanation: Both inc and get share the same lexical environment created by create(). Two calls to inc() increment n from 10 to 12, so get() returns 12.
23. Curried closure
function add(a) {
return function (b) {
return function (c) {
return a + b + c;
};
};
}
console.log(add(1)(2)(3));
- A)
6 - B)
123 - C)
NaN - D)
TypeError
Show Answer & Explanation
Answer: A) 6
Explanation: Each returned inner function closes over the arguments of the outer functions (a = 1, b = 2), and the innermost function computes 1 + 2 + 3 = 6.
24. Closure once pattern
function once(fn) {
let called = false;
let result;
return function (...args) {
if (!called) {
called = true;
result = fn(...args);
}
return result;
};
}
const init = once((x) => x * 2);
console.log(init(5), init(10));
- A)
10and20 - B)
10and10 - C)
10andundefined - D)
undefinedandundefined
Show Answer & Explanation
Answer: B) 10 and 10
Explanation: The first call sets called = true and caches result = 10. The second call skips fn(...args) and returns the cached result (10).
25. var inside for with let condition
for (let i = 0; i < 3; i++) {
var x = i;
}
console.log(x);
- A)
ReferenceError - B)
undefined - C)
2 - D)
3
Show Answer & Explanation
Answer: C) 2
Explanation: var x is hoisted outside the for block into the enclosing scope. On the final iteration (i = 2), x is assigned 2, and remains 2 after the loop ends.
Part 3: this, call, apply, bind & Arrow Functions (Q26–Q38)
26. Arrow function vs regular method this
const shape = {
radius: 10,
diameter() {
return this.radius * 2;
},
perimeter: () => 2 * Math.PI * this.radius,
};
console.log(shape.diameter(), Number.isNaN(shape.perimeter()));
- A)
20andfalse - B)
20andtrue - C)
NaNandtrue - D)
TypeError
Show Answer & Explanation
Answer: B) 20 and true
Explanation: diameter() is a regular method, so this refers to shape (10 * 2 = 20). perimeter is an arrow function, so its this comes from the outer scope where this.radius is undefined, resulting in NaN.
27. Detached method loses this
const person = {
name: "Sam",
greet() {
return this.name;
},
};
const greet = person.greet;
console.log(greet());
- A)
"Sam" - B)
undefined(orTypeErrorin strict mode) - C)
null - D)
ReferenceError
Show Answer & Explanation
Answer: B) undefined (or TypeError in strict mode)
Explanation: Assigning person.greet to greet detaches the function from person. Calling greet() as a standalone function sets this to undefined (strict mode, throwing TypeError) or the global object (non-strict mode, where this.name is undefined or "").
28. bind chaining
function getName() {
return this.name;
}
const bound = getName.bind({ name: "A" }).bind({ name: "B" });
console.log(bound());
- A)
"B" - B)
"A" - C)
undefined - D)
TypeError
Show Answer & Explanation
Answer: B) "A"
Explanation: A function bound with .bind() cannot be re-bound. The first .bind({ name: "A" }) permanently locks this to { name: "A" }, so the second .bind() has no effect on this.
29. call on an arrow function
const obj = { name: "Alex" };
const say = () => this?.name;
console.log(say.call(obj));
- A)
"Alex" - B)
undefined - C)
TypeError - D)
null
Show Answer & Explanation
Answer: B) undefined
Explanation: Arrow functions do not have their own this binding; .call(), .apply(), and .bind() cannot change an arrow function's this.
30. new keyword vs bind precedence
function User(name) {
this.name = name;
}
const BoundUser = User.bind({ name: "Ignored" });
const u = new BoundUser("Alice");
console.log(u.name);
- A)
"Ignored" - B)
"Alice" - C)
undefined - D)
TypeError
Show Answer & Explanation
Answer: B) "Alice"
Explanation: new binding has higher precedence than explicit bind() binding. Calling new BoundUser("Alice") creates a fresh this object and sets this.name = "Alice".
31. this inside a nested regular function
const obj = {
val: 42,
show() {
function inner() {
return this?.val;
}
return inner();
},
};
console.log(obj.show());
- A)
42 - B)
undefined - C)
null - D)
ReferenceError
Show Answer & Explanation
Answer: B) undefined
Explanation: Even though inner is defined inside show(), it is called as a plain function inner(). Therefore this inside inner is undefined (strict) or global (sloppy), not obj.
32. this inside a nested arrow function
const obj = {
val: 42,
show() {
const inner = () => this.val;
return inner();
},
};
console.log(obj.show());
- A)
42 - B)
undefined - C)
TypeError - D)
ReferenceError
Show Answer & Explanation
Answer: A) 42
Explanation: inner is an arrow function, so it lexically inherits this from show(). When obj.show() is called, this is obj, so this.val is 42.
33. call vs bind execution
const person = { name: "Lydia" };
function sayHi(age) {
return `${this.name} is ${age}`;
}
console.log(sayHi.call(person, 21));
console.log(typeof sayHi.bind(person, 21));
- A)
"Lydia is 21"and"string" - B)
"Lydia is 21"and"function" - C)
"function"and"Lydia is 21" - D)
TypeError
Show Answer & Explanation
Answer: B) "Lydia is 21" and "function"
Explanation: .call() invokes the function immediately and returns the string "Lydia is 21". .bind() returns a new bound function without invoking it, so typeof is "function".
34. apply with array arguments
function sum(a, b, c) {
return a + b + c;
}
console.log(sum.apply(null, [1, 2, 3]));
- A)
"1,2,3undefinedundefined" - B)
NaN - C)
6 - D)
TypeError
Show Answer & Explanation
Answer: C) 6
Explanation: Function.prototype.apply accepts arguments as an array and spreads them into parameters a = 1, b = 2, c = 3, returning 6.
35. this with null in strict vs non-strict mode
"use strict";
function fn() {
return this;
}
console.log(fn.call(null));
- A)
globalThis/window - B)
null - C)
undefined - D)
TypeError
Show Answer & Explanation
Answer: B) null
Explanation: In strict mode, fn.call(null) passes null as this without boxing or substituting globalThis. (In non-strict mode, null and undefined default to globalThis.)
36. Object method passed as callback
const user = {
name: "Maya",
log() {
console.log(this?.name);
},
};
setTimeout(user.log, 0);
- A)
"Maya" - B)
undefined - C)
TypeError - D)
null
Show Answer & Explanation
Answer: B) undefined
Explanation: Passing user.log to setTimeout passes the raw function reference without user. When setTimeout invokes it, this is globalThis (or undefined), so this?.name is undefined.
37. this in a getter
const obj = {
a: 2,
b: 3,
get sum() {
return this.a + this.b;
},
};
console.log(obj.sum);
- A)
5 - B)
NaN - C)
[Function: sum] - D)
undefined
Show Answer & Explanation
Answer: A) 5
Explanation: When accessing a getter property obj.sum, the getter runs with this bound to obj, returning 2 + 3 = 5.
38. Implicit this with comma operator
const obj = {
x: 10,
getX() {
return this?.x;
},
};
console.log((0, obj.getX)());
- A)
10 - B)
undefined - C)
0 - D)
TypeError
Show Answer & Explanation
Answer: B) undefined
Explanation: The comma operator (0, obj.getX) evaluates to the bare function reference, stripping the obj receiver. Calling it invokes getX with this as undefined/global, returning undefined.
Part 4: Event Loop, Promises & async/await (Q39–Q55)
39. Sync vs Microtask vs Macrotask
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
- A)
1 2 3 4 - B)
1 4 2 3 - C)
1 4 3 2 - D)
1 3 4 2
Show Answer & Explanation
Answer: C) 1 4 3 2
Explanation: Synchronous logs (1, 4) run first. Next, the microtask queue (Promise .then) drains completely (3) before the macrotask queue (setTimeout) runs (2).
40. Promise executor runs synchronously
console.log("start");
const p = new Promise((resolve) => {
console.log("inside promise");
resolve("done");
});
p.then((res) => console.log(res));
console.log("end");
- A)
start,end,inside promise,done - B)
start,inside promise,end,done - C)
start,inside promise,done,end - D)
inside promise,start,end,done
Show Answer & Explanation
Answer: B) start, inside promise, end, done
Explanation: The executor function passed to new Promise(...) runs synchronously when the promise is constructed. Only the .then callback is queued as a microtask.
41. async function with await
async function foo() {
console.log("A");
await Promise.resolve();
console.log("B");
}
console.log("1");
foo();
console.log("2");
- A)
1 A B 2 - B)
1 A 2 B - C)
1 2 A B - D)
A 1 2 B
Show Answer & Explanation
Answer: B) 1 A 2 B
Explanation: Code before await runs synchronously (A). Reaching await suspends foo and schedules the remainder (B) as a microtask, allowing synchronous code (2) to run next, followed by B.
42. Promise chaining with throw and .catch
Promise.resolve(1)
.then((x) => x + 1)
.then(() => {
throw new Error("boom");
})
.catch(() => 10)
.then((x) => console.log(x));
- A)
2 - B)
10 - C)
undefined - D) Unhandled rejection
Show Answer & Explanation
Answer: B) 10
Explanation: .catch() handles the thrown error and returns 10, which resolves the promise chain with 10 for the subsequent .then().
43. .finally() return value
Promise.resolve("hello")
.finally(() => "ignored")
.then((val) => console.log(val));
- A)
"ignored" - B)
"hello" - C)
undefined - D)
TypeError
Show Answer & Explanation
Answer: B) "hello"
Explanation: .finally() does not receive the resolved value and its return value is ignored (unless it throws or returns a rejected promise). The original value "hello" passes through.
44. Promise.race with rejection
const p1 = new Promise((_, rej) => setTimeout(() => rej("err"), 10));
const p2 = new Promise((res) => setTimeout(() => res("ok"), 50));
Promise.race([p1, p2])
.then((v) => console.log("then:", v))
.catch((e) => console.log("catch:", e));
- A)
then: ok - B)
catch: err - C)
then: undefined - D) Nothing logs
Show Answer & Explanation
Answer: B) catch: err
Explanation: Promise.race settles as soon as the first promise settles (whether fulfilled or rejected). p1 rejects at 10ms before p2 resolves at 50ms.
45. Promise.any with rejection and fulfillment
const p1 = Promise.reject("err1");
const p2 = Promise.resolve("success");
const p3 = Promise.resolve("later");
Promise.any([p1, p2, p3]).then(console.log);
- A)
"err1" - B)
"success" - C)
["success", "later"] - D)
AggregateError
Show Answer & Explanation
Answer: B) "success"
Explanation: Promise.any ignores rejections unless all promises reject, and resolves with the first fulfilled value ("success").
46. Promise.all short-circuiting
Promise.all([
Promise.resolve(1),
Promise.reject("fail"),
Promise.resolve(3),
])
.then((res) => console.log("res:", res))
.catch((err) => console.log("err:", err));
- A)
res: [1, "fail", 3] - B)
res: [1, 3] - C)
err: fail - D)
err: AggregateError
Show Answer & Explanation
Answer: C) err: fail
Explanation: Promise.all fails fast: as soon as any input promise rejects, the returned promise immediately rejects with that reason ("fail").
47. Returning a value from async function
async function getVal() {
return 42;
}
console.log(getVal() instanceof Promise);
- A)
false - B)
true - C)
42 - D)
TypeError
Show Answer & Explanation
Answer: B) true
Explanation: An async function always returns a Promise. Even returning a primitive 42 wraps it in Promise.resolve(42).
48. Microtask inside a microtask
Promise.resolve().then(() => {
console.log("1");
Promise.resolve().then(() => console.log("2"));
});
Promise.resolve().then(() => console.log("3"));
- A)
1 2 3 - B)
1 3 2 - C)
3 1 2 - D)
2 1 3
Show Answer & Explanation
Answer: B) 1 3 2
Explanation: Both outer .then callbacks are initially queued (1, 3). When 1 runs, it queues 2 at the back of the microtask queue, after 3. So the order is 1, 3, 2.
49. Promise.resolve with a Promise argument
const p1 = new Promise((res) => res(10));
const p2 = Promise.resolve(p1);
console.log(p1 === p2);
- A)
false - B)
true - C)
undefined - D)
TypeError
Show Answer & Explanation
Answer: B) true
Explanation: When you pass a native Promise to Promise.resolve(), it returns the exact same Promise instance unchanged (p1 === p2 is true).
50. resolve called multiple times
const p = new Promise((resolve, reject) => {
resolve("first");
reject("error");
resolve("second");
});
p.then(console.log).catch(console.log);
- A)
"second" - B)
"error" - C)
"first" - D)
"first"then"error"
Show Answer & Explanation
Answer: C) "first"
Explanation: A Promise can only settle once. Subsequent calls to resolve or reject are silently ignored.
51. await on a non-promise value
async function run() {
const res = await 100;
console.log(res);
}
run();
console.log("after");
- A)
100then"after" - B)
"after"then100 - C)
TypeError - D)
undefinedthen"after"
Show Answer & Explanation
Answer: B) "after" then 100
Explanation: await 100 wraps 100 in Promise.resolve(100) and still suspends the async function, scheduling the continuation as a microtask. Synchronous "after" runs first, then 100.
52. Promise.allSettled output shape
Promise.allSettled([Promise.resolve(1), Promise.reject("no")]).then((res) =>
console.log(res.map((r) => r.status))
);
- A)
["resolved", "rejected"] - B)
["fulfilled", "rejected"] - C)
[1, "no"] - D) Rejects with
"no"
Show Answer & Explanation
Answer: B) ["fulfilled", "rejected"]
Explanation: Promise.allSettled waits for all promises to settle and returns objects with status: "fulfilled" (with value) or status: "rejected" (with reason).
53. throw inside async function
async function fail() {
throw new Error("oops");
}
fail()
.then(() => console.log("ok"))
.catch((e) => console.log(e.message));
- A)
"ok" - B)
"oops" - C) Uncaught synchronous error
- D)
undefined
Show Answer & Explanation
Answer: B) "oops"
Explanation: Throwing inside an async function automatically turns the exception into a rejected Promise, which is caught by .catch().
54. queueMicrotask vs setTimeout
setTimeout(() => console.log("timeout"), 0);
queueMicrotask(() => console.log("microtask"));
console.log("sync");
- A)
sync,timeout,microtask - B)
sync,microtask,timeout - C)
microtask,sync,timeout - D)
timeout,microtask,sync
Show Answer & Explanation
Answer: B) sync, microtask, timeout
Explanation: queueMicrotask schedules a callback in the microtask queue, which runs right after the synchronous call stack clears and before any macrotask (setTimeout).
55. .then(null, handler) vs .then(handler)
Promise.reject("err")
.then(
() => console.log("ok"),
(e) => console.log("handled:", e)
)
.catch(() => console.log("catch"));
- A)
catch - B)
handled: errandcatch - C)
handled: err - D)
ok
Show Answer & Explanation
Answer: C) handled: err
Explanation: The second argument to .then() handles the rejection and returns undefined (a fulfilled promise), so the subsequent .catch() is skipped.
Part 5: Type Coercion, Equality & Operators (Q56–Q70)
56. typeof null and typeof NaN
console.log(typeof null, typeof NaN);
- A)
"null"and"NaN" - B)
"object"and"number" - C)
"object"and"NaN" - D)
"undefined"and"number"
Show Answer & Explanation
Answer: B) "object" and "number"
Explanation: typeof null === "object" is a famous legacy bug from JS's first implementation. NaN (Not-a-Number) is still a numeric value in IEEE 754, so typeof NaN === "number".
57. + vs - with strings and numbers
console.log("5" + 3, "5" - 3);
- A)
8and2 - B)
"53"and"5-3" - C)
"53"and2 - D)
NaNand2
Show Answer & Explanation
Answer: C) "53" and 2
Explanation: The + operator performs string concatenation if either operand is a string ("5" + "3" = "53"). The - operator only performs numeric subtraction, coercing "5" to 5 (5 - 3 = 2).
58. Unary + and !
console.log(+true, !"Lydia");
- A)
1andfalse - B)
trueandfalse - C)
1andtrue - D)
NaNandfalse
Show Answer & Explanation
Answer: A) 1 and false
Explanation: Unary + converts true to 1. A non-empty string "Lydia" is truthy, so ! negates it to false.
59. == vs === with null and undefined
console.log(null == undefined, null === undefined);
- A)
trueandtrue - B)
trueandfalse - C)
falseandfalse - D)
falseandtrue
Show Answer & Explanation
Answer: B) true and false
Explanation: Abstract equality (==) defines null == undefined as true (and neither equals anything else). Strict equality (===) checks types first, returning false.
60. NaN === NaN and Object.is(NaN, NaN)
console.log(NaN === NaN, Object.is(NaN, NaN));
- A)
trueandtrue - B)
falseandfalse - C)
falseandtrue - D)
trueandfalse
Show Answer & Explanation
Answer: C) false and true
Explanation: By IEEE 754 spec, NaN is never equal to anything, including itself (=== returns false). Object.is treats NaN as equal to NaN (true) and distinguishes +0 from -0.
61. [] == ![]
console.log([] == ![]);
- A)
false - B)
true - C)
TypeError - D)
undefined
Show Answer & Explanation
Answer: B) true
Explanation: ![] evaluates to false (arrays are truthy). Then [] == false coerces both sides to numbers: [] -> "" -> 0, and false -> 0. 0 == 0 is true.
62. 1 < 2 < 3 and 3 > 2 > 1
console.log(1 < 2 < 3, 3 > 2 > 1);
- A)
trueandtrue - B)
trueandfalse - C)
falseandfalse - D)
falseandtrue
Show Answer & Explanation
Answer: B) true and false
Explanation: Comparison operators evaluate left-to-right: (1 < 2) < 3 -> true < 3 -> 1 < 3 -> true. For 3 > 2 > 1: (3 > 2) > 1 -> true > 1 -> 1 > 1 -> false.
63. Post-increment vs pre-increment
let num = 0;
console.log(num++);
console.log(++num);
console.log(num);
- A)
0,1,1 - B)
0,2,2 - C)
1,2,2 - D)
0,1,2
Show Answer & Explanation
Answer: B) 0, 2, 2
Explanation: num++ returns 0 and then increments num to 1. ++num increments num to 2 and then returns 2.
64. Logical && and || return values
console.log("cat" && "dog", "" || "fallback");
- A)
trueandtrue - B)
"dog"and"fallback" - C)
"cat"and"" - D)
"dog"andtrue
Show Answer & Explanation
Answer: B) "dog" and "fallback"
Explanation: && and || return one of the actual operand values, not necessarily a boolean. && returns the first falsy value or the last value ("dog"). || returns the first truthy value ("fallback").
65. Nullish coalescing ?? vs ||
const count = 0;
console.log(count || 10, count ?? 10);
- A)
0and0 - B)
10and10 - C)
10and0 - D)
0and10
Show Answer & Explanation
Answer: C) 10 and 0
Explanation: || checks for any falsy value (0 is falsy, so it falls back to 10). ?? only falls back when the left side is null or undefined, so 0 ?? 10 returns 0.
66. [] + [] and [] + {}
console.log(typeof ([] + []), [] + {});
- A)
"object"and"[object Object]" - B)
"string"and"[object Object]" - C)
"string"and"{}" - D)
"undefined"andNaN
Show Answer & Explanation
Answer: B) "string" and "[object Object]"
Explanation: + converts objects to primitives via toString(): [].toString() is "", so "" + "" is "" ("string"). {}.toString() is "[object Object]", so "" + "[object Object]" is "[object Object]".
67. Number("") vs parseInt("")
console.log(Number(""), parseInt(""));
- A)
0and0 - B)
NaNandNaN - C)
0andNaN - D)
NaNand0
Show Answer & Explanation
Answer: C) 0 and NaN
Explanation: Number("") converts an empty/whitespace string to 0. parseInt("") looks for leading digits and returns NaN when none are found.
68. Floating-point precision
console.log(0.1 + 0.2 === 0.3);
- A)
true - B)
false - C)
NaN - D)
TypeError
Show Answer & Explanation
Answer: B) false
Explanation: In IEEE 754 binary floating-point, 0.1 + 0.2 equals 0.30000000000000004, which is not strictly equal to 0.3.
69. Boolean wrapper object
const flag = new Boolean(false);
console.log(flag ? "truthy" : "falsy", typeof flag);
- A)
"falsy"and"boolean" - B)
"truthy"and"object" - C)
"falsy"and"object" - D)
"truthy"and"boolean"
Show Answer & Explanation
Answer: B) "truthy" and "object"
Explanation: new Boolean(false) creates an object wrapper (typeof flag === "object"). All objects in JavaScript are truthy, even when wrapping false.
70. Chained assignment right-to-left
let a = 1;
let b = 2;
a = b = 5;
console.log(a, b);
- A)
1and2 - B)
2and5 - C)
5and5 - D)
5and2
Show Answer & Explanation
Answer: C) 5 and 5
Explanation: The assignment operator = is right-associative. b = 5 evaluates to 5, which is then assigned to a.
Part 6: Objects, Prototypes & Classes (Q71–Q82)
71. Object keys are converted to strings
const obj = { 1: "a", 2: "b" };
const set = new Set([1, 2]);
console.log(obj.hasOwnProperty("1"), set.has("1"));
- A)
trueandtrue - B)
trueandfalse - C)
falseandfalse - D)
falseandtrue
Show Answer & Explanation
Answer: B) true and false
Explanation: Plain object keys (other than Symbols) are always converted to strings (1 -> "1"). Set preserves strict types, so set.has("1") is false because 1 !== "1".
72. Object used as an object key
const a = {};
const b = { key: "b" };
const c = { key: "c" };
a[b] = 123;
a[c] = 456;
console.log(a[b]);
- A)
123 - B)
456 - C)
undefined - D)
TypeError
Show Answer & Explanation
Answer: B) 456
Explanation: Both b and c stringify to "[object Object]". Thus a[b] and a[c] both write to a["[object Object]"], overwriting 123 with 456.
73. Shallow copy with spread { ...obj }
const original = { a: 1, nested: { b: 2 } };
const copy = { ...original };
copy.a = 99;
copy.nested.b = 88;
console.log(original.a, original.nested.b);
- A)
99and88 - B)
1and2 - C)
1and88 - D)
99and2
Show Answer & Explanation
Answer: C) 1 and 88
Explanation: Object spread { ...original } creates a shallow copy. Top-level primitives (a) are independent, while nested objects (nested) still share the same reference.
74. Object.freeze on nested objects
const person = { name: "Leo", address: { city: "BLR" } };
Object.freeze(person);
person.name = "Max";
person.address.city = "DEL";
console.log(person.name, person.address.city);
- A)
"Max"and"DEL" - B)
"Leo"and"BLR" - C)
"Leo"and"DEL" - D)
TypeError
Show Answer & Explanation
Answer: C) "Leo" and "DEL"
Explanation: Object.freeze() is shallow: it prevents changing person.name, but nested objects like person.address can still be mutated unless frozen recursively.
75. Constructor returning an object
function Car() {
this.brand = "Tesla";
return { brand: "Ford" };
}
const c = new Car();
console.log(c.brand);
- A)
"Tesla" - B)
"Ford" - C)
undefined - D)
TypeError
Show Answer & Explanation
Answer: B) "Ford"
Explanation: If a constructor function explicitly returns a non-primitive object, new Car() returns that object instead of this. (If it returns a primitive like 42, this is returned.)
76. Constructor without new
function Person(name) {
this.name = name;
}
const p = Person("Sara");
console.log(p);
- A)
Person { name: "Sara" } - B)
undefined - C)
{ name: "Sara" } - D)
null
Show Answer & Explanation
Answer: B) undefined
Explanation: Without new, Person("Sara") runs as a normal function with no return statement, so p is undefined (in strict mode it throws TypeError on this.name).
77. Prototype method vs instance method
function Dog(name) {
this.name = name;
}
Dog.prototype.bark = function () {
return this.name + " woof";
};
const d = new Dog("Rex");
console.log(d.hasOwnProperty("bark"), "bark" in d);
- A)
trueandtrue - B)
falseandtrue - C)
falseandfalse - D)
trueandfalse
Show Answer & Explanation
Answer: B) false and true
Explanation: hasOwnProperty checks only own properties (false because bark lives on Dog.prototype), while the in operator walks the prototype chain (true).
78. static method in ES6 class
class MathUtil {
static double(n) {
return n * 2;
}
}
const util = new MathUtil();
console.log(typeof util.double, MathUtil.double(5));
- A)
"function"and10 - B)
"undefined"and10 - C)
"function"andTypeError - D)
"undefined"andundefined
Show Answer & Explanation
Answer: B) "undefined" and 10
Explanation: static methods belong to the class constructor itself (MathUtil.double), not to instances (util.double is undefined).
79. Object.create(null) and toString
const dict = Object.create(null);
console.log(typeof dict.toString);
- A)
"function" - B)
"undefined" - C)
"object" - D)
TypeError
Show Answer & Explanation
Answer: B) "undefined"
Explanation: Object.create(null) creates an object with no prototype, so it does not inherit Object.prototype.toString or hasOwnProperty.
80. JSON.stringify with undefined and functions
const data = { a: 1, b: undefined, c: () => 2, d: null };
console.log(JSON.stringify(data));
- A)
'{"a":1,"b":undefined,"c":null,"d":null}' - B)
'{"a":1,"d":null}' - C)
'{"a":1,"b":null,"d":null}' - D)
TypeError
Show Answer & Explanation
Answer: B) '{"a":1,"d":null}'
Explanation: JSON.stringify omits object properties whose values are undefined, functions, or Symbols, while keeping null.
81. Object.keys property ordering
const obj = { b: 1, 2: "two", a: 3, 1: "one" };
console.log(Object.keys(obj));
- A)
["b", "2", "a", "1"] - B)
["1", "2", "b", "a"] - C)
["1", "2", "a", "b"] - D)
["a", "b", "1", "2"]
Show Answer & Explanation
Answer: B) ["1", "2", "b", "a"]
Explanation: JS iterates integer-index keys in ascending numeric order first ("1", "2"), followed by remaining string keys in insertion order ("b", "a").
82. delete on prototype property
function Foo() {}
Foo.prototype.x = 10;
const f = new Foo();
delete f.x;
console.log(f.x);
- A)
undefined - B)
10 - C)
null - D)
TypeError
Show Answer & Explanation
Answer: B) 10
Explanation: delete f.x only deletes an own property on f. It does not affect Foo.prototype.x, so f.x still resolves to 10 via the prototype chain.
Part 7: Arrays, Destructuring & Spread (Q83–Q92)
83. Array.prototype.sort without comparator
const nums = [10, 2, 30, 4];
nums.sort();
console.log(nums);
- A)
[2, 4, 10, 30] - B)
[10, 2, 30, 4] - C)
[10, 30, 2, 4] - D)
[30, 10, 4, 2]
Show Answer & Explanation
Answer: B) [10, 2, 30, 4]
Explanation: Without a compare function, Array.prototype.sort() converts elements to strings and sorts lexicographically ("10" < "2" < "30" < "4").
84. Sparse array length and map
const arr = [1, 2, 3];
arr[5] = 6;
console.log(arr.length, arr.map((x) => x * 2).length);
- A)
4and4 - B)
6and4 - C)
6and6 - D)
4and6
Show Answer & Explanation
Answer: C) 6 and 6
Explanation: Assigning arr[5] = 6 creates empty slots at indices 3 and 4, making arr.length === 6. map() skips empty slots when calling the callback, but preserves the array's length of 6.
85. delete on an array element
const arr = ["a", "b", "c"];
delete arr[1];
console.log(arr.length, arr[1]);
- A)
2and"c" - B)
3andundefined - C)
2andundefined - D)
3andnull
Show Answer & Explanation
Answer: B) 3 and undefined
Explanation: delete arr[1] leaves an empty hole at index 1 without shifting elements or updating arr.length. Reading arr[1] returns undefined.
86. map with parseInt
console.log(["1", "2", "3"].map(parseInt));
- A)
[1, 2, 3] - B)
[1, NaN, NaN] - C)
[1, 2, NaN] - D)
[NaN, NaN, NaN]
Show Answer & Explanation
Answer: B) [1, NaN, NaN]
Explanation: map passes (value, index, array) to parseInt(str, radix). It calls parseInt("1", 0) -> 1, parseInt("2", 1) -> NaN (radix 1 is invalid), parseInt("3", 2) -> NaN (3 is not valid in base 2).
87. reduce without initial value
console.log([1, 2, 3, 4].reduce((acc, cur) => acc + cur));
- A)
10 - B)
NaN - C)
TypeError - D)
undefined
Show Answer & Explanation
Answer: A) 10
Explanation: When no initialValue is provided to reduce, acc starts as the first element (1) and cur starts as the second (2), summing 1 + 2 + 3 + 4 = 10. (It throws only if the array is empty.)
88. Destructuring default values with null vs undefined
const [a = 1, b = 2] = [undefined, null];
console.log(a, b);
- A)
1and2 - B)
undefinedandnull - C)
1andnull - D)
undefinedand2
Show Answer & Explanation
Answer: C) 1 and null
Explanation: Destructuring default values only trigger when the value is strictly undefined. null is a defined value, so b becomes null.
89. Spread string into array
console.log([..."Lydia"]);
- A)
["Lydia"] - B)
["L", "y", "d", "i", "a"] - C)
[["L", "y", "d", "i", "a"]] - D)
TypeError
Show Answer & Explanation
Answer: B) ["L", "y", "d", "i", "a"]
Explanation: Strings are iterable, so spreading "Lydia" inside [...] iterates over each character and creates an array of single-character strings.
90. Array.from with length
console.log(Array.from({ length: 3 }, (_, i) => i * 2));
- A)
[undefined, undefined, undefined] - B)
[0, 2, 4] - C)
[2, 4, 6] - D)
[]
Show Answer & Explanation
Answer: B) [0, 2, 4]
Explanation: Array.from accepts an array-like object { length: 3 } and a mapping function (val, index) => index * 2, producing [0, 2, 4].
91. flat() default depth
console.log([1, [2, [3, [4]]]].flat());
- A)
[1, 2, 3, 4] - B)
[1, 2, [3, [4]]] - C)
[1, [2, [3, [4]]]] - D)
[1, 2, 3, [4]]
Show Answer & Explanation
Answer: B) [1, 2, [3, [4]]]
Explanation: Array.prototype.flat() defaults to depth 1, flattening only one level of nesting. Use .flat(Infinity) to flatten all levels.
92. includes vs indexOf with NaN
const arr = [1, NaN, 3];
console.log(arr.includes(NaN), arr.indexOf(NaN));
- A)
trueand1 - B)
falseand-1 - C)
trueand-1 - D)
falseand1
Show Answer & Explanation
Answer: C) true and -1
Explanation: includes() uses SameValueZero comparison and finds NaN (true). indexOf() uses strict equality ===, where NaN === NaN is false, so it returns -1.
Part 8: Functions, Generators, Symbols & Edge Cases (Q93–Q101)
93. function.length with default & rest parameters
function fn(a, b = 2, c, ...rest) {}
console.log(fn.length);
- A)
4 - B)
3 - C)
1 - D)
2
Show Answer & Explanation
Answer: C) 1
Explanation: Function.length counts parameters before the first parameter with a default value (and excludes rest parameters). Only a precedes b = 2, so fn.length is 1.
94. arguments object in arrow functions
const fn = () => arguments;
function outer() {
return (() => arguments[0])();
}
console.log(outer(42));
- A)
undefined - B)
42 - C)
ReferenceError - D)
TypeError
Show Answer & Explanation
Answer: B) 42
Explanation: Arrow functions do not have their own arguments object; instead, they lexically resolve arguments from their enclosing regular function (outer), where arguments[0] is 42.
95. Generator function execution
function* gen() {
yield 1;
yield 2;
return 3;
}
const g = gen();
console.log(g.next().value, g.next().value, g.next());
- A)
1,2,{ value: 3, done: false } - B)
1,2,{ value: 3, done: true } - C)
1,2,{ value: undefined, done: true } - D)
1,2,3
Show Answer & Explanation
Answer: B) 1, 2, { value: 3, done: true }
Explanation: Each .next() resumes until the next yield. When return 3 is reached, .next() returns { value: 3, done: true }.
96. Symbol uniqueness and Symbol.for
console.log(Symbol("id") === Symbol("id"), Symbol.for("id") === Symbol.for("id"));
- A)
trueandtrue - B)
falseandfalse - C)
falseandtrue - D)
trueandfalse
Show Answer & Explanation
Answer: C) false and true
Explanation: Symbol("id") always creates a unique symbol. Symbol.for("id") looks up or registers a symbol in the global symbol registry, returning the same symbol for the same key.
97. for...in vs for...of on an array
const list = ["a", "b"];
const res = [];
for (const i in list) res.push(i);
for (const v of list) res.push(v);
console.log(res);
- A)
["a", "b", 0, 1] - B)
["0", "1", "a", "b"] - C)
[0, 1, "a", "b"] - D)
["a", "b", "a", "b"]
Show Answer & Explanation
Answer: B) ["0", "1", "a", "b"]
Explanation: for...in iterates over enumerable property keys (which are string indices "0", "1"), while for...of iterates over iterable values ("a", "b").
98. Tagged template literal
function tag(strings, ...values) {
return [strings.length, values];
}
const name = "JS";
console.log(tag`Hello ${name}!`);
- A)
[1, ["JS"]] - B)
[2, ["JS"]] - C)
[3, ["JS"]] - D)
[2, "JS"]
Show Answer & Explanation
Answer: B) [2, ["JS"]]
Explanation: In tagged templates, the first argument is an array of string parts split around interpolations: ["Hello ", "!"] (length 2), followed by the interpolated values ["JS"].
99. try...catch...finally return override
function test() {
try {
return 1;
} catch {
return 2;
} finally {
return 3;
}
}
console.log(test());
- A)
1 - B)
2 - C)
3 - D)
undefined
Show Answer & Explanation
Answer: C) 3
Explanation: A return statement inside a finally block always overrides any pending return or throw from the try or catch blocks.
100. setTimeout with negative or 0 delay vs Promise
setTimeout(() => console.log("A"), 0);
setTimeout(() => console.log("B"), -10);
Promise.resolve().then(() => console.log("C"));
- A)
B A C - B)
C A B - C)
C B A - D)
A B C
Show Answer & Explanation
Answer: B) C A B
Explanation: Microtasks (C) always run before macrotasks. Negative timer delays are clamped to 0ms, so A and B are queued in registration order (A, then B).
101. with / Proxy trap get
const target = { msg: "hi" };
const proxy = new Proxy(target, {
get(obj, prop) {
return prop in obj ? obj[prop] : "default";
},
});
console.log(proxy.msg, proxy.other);
- A)
"hi"andundefined - B)
"hi"and"default" - C)
"default"and"default" - D)
ReferenceError
Show Answer & Explanation
Answer: B) "hi" and "default"
Explanation: The Proxy get trap intercepts property reads. msg exists on target ("hi"), while other does not, so the trap returns "default".