JavaScript Logical Snippets

1. What will be the output?

console.log([] == []);

Answer:

false

Explanation:

Each [] creates a new array in memory.
Comparing objects checks reference, not value.

So:

  • left array: memory location A

  • right array: memory location B

A !== B → false


2. What will this print?

console.log([] == 0); console.log("0" == 0); console.log([0] == 0);

Answer:

true true true

Explanation:

Loose equality == does type coercion.

  • []""0

  • "0" → number 0

  • [0]"0"0

So all become 0.


3. What is the output? (Hoisting)

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

Answer:

undefined

Explanation:

var is hoisted to the top, but only declared, not assigned.

It becomes:

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

4. What will be the output?

let a = { num: 5 }; let b = a; b.num = 10; console.log(a.num);

Answer:

10

Explanation:

Objects are passed by reference, so both a and b point to the same memory.


5. Output? (Closures)

function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const fn = outer(); fn(); fn();

Answer:

1 2

Explanation:

fn remembers count even after outer() finishes.
This is closure.


6. Tricky: What will happen?

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

Answer:

ReferenceError

Explanation:

let is hoisted but kept in Temporal Dead Zone (TDZ) until initialization.
Accessing before assignment causes an error.


7. Promise question

console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); console.log("D");

Answer:

A D C B

Explanation:

JavaScript order:

  1. Synchronous

  2. Microtask queue (Promises)

  3. Macrotask queue (setTimeout)


8. Output? (this keyword)

const person = { name: "Pranjal", getName() { return this.name; } }; const fn = person.getName; console.log(fn());

Answer:

undefined

Explanation:

When you extract the method into a variable,
this loses context → defaults to undefined (in strict mode).


9. Output? (Object.freeze)

const obj = { a: 1 }; Object.freeze(obj); obj.a = 10; console.log(obj.a);

Answer:

1

Explanation:

freeze() makes object values immutable, so assignment is ignored.


10. Output? (Set behavior)

const set = new Set([1, 1, 2, 2, 3]); console.log(set.size);

Answer:

3

Explanation:

A Set stores unique values only.


🔥 SET 2 — Intermediate to Advanced Logical Questions (With Explanation)


1. What is the output? (Scope + var)

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

Answer:

3 3 3

Explanation:

var is function-scoped, not block-scoped.
After the loop, i = 3, so all callbacks print 3.


2. How to fix the above code to print 0,1,2?

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

Explanation:

let is block-scoped, so each iteration gets its own i.


3. Output? (Spread vs Rest)

function test(a, ...rest) { console.log(a, rest); } test(1, 2, 3, 4);

Answer:

1 [2, 3, 4]

4. Output? (Destructuring pitfalls)

const { length } = "hello"; console.log(length);

Answer:

5

Explanation:

Strings have a length property, so destructuring works.


5. Output? (Default parameters evaluation)

function add(a, b = a * 2) { return a + b; } console.log(add(5));

Answer:

15

Explanation:

b is evaluated after a is available → b = 10.


6. Output? (Object reference)

let a = { x: 1 }; let b = { x: 1 }; console.log(a == b); console.log(a === b);

Answer:

false false

Explanation:

Two objects never equal unless they reference same memory.


7. Output? (Prototype chain)

const obj = {}; console.log(obj.__proto__ === Object.prototype);

Answer:

true

Explanation:

All objects inherit from Object.prototype.


8. Output? (Array prototype)

console.log([].__proto__.__proto__ === Object.prototype);

Answer:

true

Explanation:

Array → Array.prototype → Object.prototype.


🔥 9. Tricky Promise + setTimeout

console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); console.log("D");

Answer:

A D C B

Explanation:

  • Sync first

  • Microtask (Promise) next

  • Macrotask (setTimeout) last


🔥 10. Promise + async

async function test() { return 10; } test().then(console.log);

Answer:

10

Explanation:

Async function always returns a promise, resolved with the return value.


🔥 11. Output? (this inside arrow function)

const user = { name: "Pranjal", getName: () => this.name }; console.log(user.getName());

Answer:

undefined

Explanation:

Arrow functions don’t bind this.
this refers to global object, not user.


🔥 12. Output? (IIFE + closure)

let count = 0; (function() { let count = 5; console.log(count); })(); console.log(count);

Answer:

5 0

Explanation:

IIFE has its own scope.


🔥 13. Output? (Mutation vs reassignment)

const obj = { a: 1 }; obj.a = 5; console.log(obj.a);

Answer:

5

Explanation:

const prevents reassigning the variable,
not mutating the object.


🔥 14. Output? (Map vs Object key)

const map = new Map(); map.set({}, "A"); map.set({}, "B"); console.log(map.size);

Answer:

2

Explanation:

Each {} is a different reference, so Map treats them as unique keys.


🔥 15. Output? (== vs === with null and undefined)

console.log(null == undefined); console.log(null === undefined);

Answer:

true false

Explanation:

null and undefined are only loosely equal to each other.


🔥 SET 3 — Advanced JavaScript Logical Questions (With Deep Explanation)


1. Output? (Shallow Copy vs Deep Copy)

const obj1 = { a: 1, b: { c: 2 } }; const obj2 = { ...obj1 }; obj2.b.c = 10; console.log(obj1.b.c);

Answer:

10

Explanation:

Spread operator { ...obj } makes a shallow copy,
so nested objects share the same reference.


2. Output? (Object keys as string)

const a = {}; const b = { key: "b" }; const c = { key: "c" }; a[b] = 100; a[c] = 200; console.log(a[b]);

Answer:

200

Explanation:

When using objects as keys in normal objects,
they get converted to:

"[object Object]"

So:

a[b]a["[object Object]"] a[c]a["[object Object]"]

Second assignment overwrites the first.


3. Output? (setTimeout inside Promise)

Promise.resolve().then(() => { console.log("A"); setTimeout(() => console.log("B"), 0); }); console.log("C");

Answer:

C A B

4. Output? (async / await + loops)

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

Answer:

1 2 3

Explanation:

let creates new block-scope variable each iteration.


🔥 5. Very common tricky one:

console.log("start"); setTimeout(() => console.log("timeout"), 0); Promise.resolve().then(() => console.log("promise")); console.log("end");

Answer:

start end promise timeout

🔥 6. Output? (Implicit return in arrow function)

const fn = () => { foo: 1 }; console.log(fn());

Answer:

undefined

Explanation:

Because { foo: 1 } looks like a block, not an object.
To return an object implicitly:

const fn = () => ({ foo: 1 });

🔥 7. Output? (typeof null)

console.log(typeof null);

Answer:

object

Explanation:

A historic JavaScript bug, kept for backward compatibility.


🔥 8. Output? (Function hoisting — tricky)

foo(); var foo = function() { console.log("A"); };

Answer:

TypeError: foo is not a function

Explanation:

var foo is hoisted, but value assignment is not:

var foo; // hoisted foo(); // foo is undefined → not a function foo = function() {}

🔥 9. Output? (class hoisting)

const obj = new User(); class User {}

Answer:

ReferenceError

Explanation:

Classes are hoisted but kept in Temporal Dead Zone, like let.


🔥 10. Output? (arguments object)

function test(...args) { console.log(args.length); console.log(arguments.length); } test(1, 2, 3, 4);

Answer:

4 4

Explanation:

Both args and arguments capture all passed values (except in arrow functions).


🔥 11. Output? (Strict mode this)

"use strict"; function test() { console.log(this); } test();

Answer:

undefined

Explanation:

In strict mode, this inside a normal function is undefined, not global.


🔥 12. Output? (Chained assignments)

let a = { n: 1 }; let b = a; a.x = a = { n: 2 }; console.log(a.x); console.log(b.x);

Answer:

undefined { n: 2 }

Explanation (Important):

a.x = a = { n: 2 } is evaluated like:

  1. Evaluate left object reference → points to old a

  2. Assign a = { n: 2 }

  3. Assign .x on the old object

So:

  • b points to old object → b.x = { n: 2 }

  • a.x is undefined because a now points to new object

Very common in interviews.


🔥 13. Output? (bind)

function say() { console.log(this.name); } const user = { name: "Pranjal" }; say.bind(user)();

Answer:

Pranjal

Explanation:

bind() permanently attaches this to the function.


🔥 14. Output? (Chaining Promises)

Promise.resolve(1) .then((x) => x + 1) .then((x) => x * 2) .then(console.log);

Answer:

4


🔥 15. Output? (delete operator)

const obj = { a: 1, b: 2 }; delete obj.a; console.log(obj);

Answer:

{ b: 2 }

Explanation:

delete removes properties from objects.



🔥 SET 4 — VERY HARD & TRICKY JAVASCRIPT QUESTIONS


1. Output? (Promise inside async)

async function test() { return Promise.resolve("A"); } test().then(console.log);

Answer:

A

Explanation:

If an async function returns a promise, JavaScript does not wrap it again.
It simply returns that promise.


2. Output? (Double await)

async function test() { let x = await Promise.resolve(10); let y = await x; console.log(y); } test();

Answer:

10

Explanation:

await on a non-promise returns the value directly.


3. Output? (Flattening after await)

async function test() { return 5; } console.log(test());

Answer:

Promise { <resolved>: 5 }

Explanation:

Async functions always return a Promise, never the value directly.


🔥 4. Output? (typeof NaN)

console.log(typeof NaN);

Answer:

number

Explanation:

NaN stands for Not a Number, but its type is "number".


🔥 5. Output? (Boolean conversion)

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

Answer:

true false

Explanation:

  • Non-empty string is always true

  • 0 converts to false


🔥 6. Output? (Falsy values)

console.log(Boolean([])); console.log(Boolean({})); console.log(Boolean(""));

Answer:

true true false

Explanation:

Only 6 values are falsy:
0, "", NaN, null, undefined, false


🔥 7. Output? (Operator precedence)

console.log(1 < 2 < 3); console.log(3 < 2 < 1);

Answer:

true true

Explanation:

1 < 2 < 3
→ true < 3
→ 1 < 3 → true

3 < 2 < 1
→ false < 1
→ 0 < 1 → true


🔥 8. Output? (Array holes)

const arr = [1, , 3]; console.log(arr.length); console.log(arr[1]);

Answer:

3 undefined

Explanation:

Missing elements are “holes", not undefined.
Length still counts them.


🔥 9. Output? (forEach skipping holes)

[1, , 3].forEach((x) => console.log(x));

Answer:

1 3

Explanation:

forEach skips holes.


🔥 10. Output? (map with hole)

console.log([1, , 3].map(x => x * 2));

Answer:

[2, <1 empty item>, 6]

Explanation:

map also preserves holes.


🔥 11. Output? (Object comparison)

console.log({} + {});

Answer:

"[object Object][object Object]"

Explanation:

Objects convert to string:

"[object Object]"

🔥 12. Output? (Adding arrays)

console.log([1,2] + [3,4]);

Answer:

"1,23,4"

Explanation:

Arrays convert to strings → "1,2" + "3,4"


🔥 13. Output? (Object keys ordering)

const obj = { 3: "A", 1: "B", 2: "C" }; console.log(Object.keys(obj));

Answer:

["1", "2", "3"]

Explanation:

Object keys are sorted numerically if they look like numbers.


🔥 14. Output? (class private fields)

class A { #x = 5; } console.log(new A().#x);

Answer:

SyntaxError

Explanation:

Private fields are not accessible outside class.


🔥 15. Output? (Chaining then with return undefined)

Promise.resolve(1) .then((x) => { x + 1; }) .then((x) => console.log(x));

Answer:

undefined

Explanation:

Missing return, so the first then returns undefined.


🔥 16. Output? (Promise resolve inside setTimeout)

setTimeout(() => { Promise.resolve().then(() => console.log("A")); }, 0); console.log("B");

Answer:

B A

Explanation:

  • Timeout callback → macrotask

  • Inside it, the Promise → microtask

After timeout executes, all its microtasks run.


🔥 17. Output? (Prototype override)

Array.prototype.push = function() { return "blocked"; }; console.log([1].push(2));

Answer:

"blocked"

Explanation:

Prototype methods can be overridden.


🔥 18. Output? (Weird typeof)

console.log(typeof (function() {})); console.log(typeof (class A {}));

Answer:

"function" "function"

Explanation:
Classes are special functions.


🔥 19. Output? (instanceof)

console.log([] instanceof Array); console.log([] instanceof Object);

Answer:

true true

Explanation:

Array inherits from Object.


🔥 20. Output? (Promise rejection)

Promise.reject("err").catch((e) => { return "fixed"; }).then(console.log);

Answer:

fixed

Explanation:

catch() returns a resolved promise unless it throws again.



Set 5 — Advanced JavaScript Logical Interview Questions


1️⃣ Output? (Event Loop Tricky)

console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); console.log("D");

Answer:

A D C B

📌 Explanation

  • Synchronous: A, D

  • Microtask queue: Promise → C

  • Macrotask queue: setTimeout → B


2️⃣ Output? (Closures)

function createFunctions() { let funcs = []; for (var i = 0; i < 3; i++) { funcs.push(() => console.log(i)); } return funcs; } const arr = createFunctions(); arr[0](); arr[1](); arr[2]();

Answer:

3 3 3

📌 Explanation

var is function scoped → all functions share same i.
After loop finishes, i = 3.


3️⃣ Fix previous code to print 0,1,2

for (let i = 0; i < 3; i++) { funcs.push(() => console.log(i)); }

📌 Because let is block scoped → each iteration creates its own binding.


4️⃣ Output? (Object keys conversion)

const a = {}; const b = { key: "b" }; const c = { key: "c" }; a[b] = 100; a[c] = 200; console.log(a[b]);

Answer: 200

📌 Explanation

Objects used as keys convert to string:

a[b]a["[object Object]"] a[c]a["[object Object]"]

Second assignment overwrites first.


5️⃣ Output? (this binding)

const user = { name: "Pranjal", getName() { return this.name; } }; const get = user.getName; console.log(get());

Answer: undefined

📌 Explanation

this depends on the caller.
Here, the caller is global, not user.

Fix:

const get = user.getName.bind(user);

6️⃣ Output? (Coercion + equality)

console.log(1 < 2 < 3); console.log(3 > 2 > 1);

Answer:

true false

📌 Explanation

  1. 1 < 2 → true
    true < 3 → 1 < 3 → true

  2. 3 > 2 → true
    true > 1 → 1 > 1 → false


7️⃣ Output? (Default params reference)

function foo(a, b = a) { console.log(a, b); } foo(5); foo(5, 10);

✅ Answer:

5 5 5 10

8️⃣ Output? (Set / Map)

const s = new Set([1, 2, 2, 3]); console.log(s.size);

Answer: 3


9️⃣ Output? (Promise chain)

Promise.resolve(1) .then(x => x + 1) .then(x => { throw new Error("Oops"); }) .then(() => console.log("Done")) .catch(err => console.log(err.message));

Answer:

Oops

🔟 Output? (Shallow copy trap)**

const obj = { a: 1, b: { c: 2 } }; const newObj = { ...obj }; obj.b.c = 99; console.log(newObj.b.c);

Answer: 99

📌 Explanation

Spread operator creates a shallow copy, not deep copy.



Set 6 — Advanced JavaScript Logical + Concept Questions


1️⃣ Output? (async/await + event loop)

async function test() { console.log("A"); await Promise.resolve(); console.log("B"); } console.log("C"); test(); console.log("D");

Answer:

C A D B

📌 Explanation

  • "C" → sync

  • "A" → sync inside async

  • await moves next part to microtask queue

  • "D" runs before microtask

  • "B" finally runs


2️⃣ Output? (async + setTimeout)

async function foo() { console.log(1); await new Promise(res => setTimeout(res, 1000)); console.log(2); } foo(); console.log(3);

Answer:

1 3 2

📌 Explanation

await pauses this function but not the whole program.


3️⃣ Output? (Generator)

function* gen() { yield 1; yield 2; return 3; } const it = gen(); console.log(it.next()); console.log(it.next()); console.log(it.next());

Answer:

{ value: 1, done: false } { value: 2, done: false } { value: 3, done: true }

4️⃣ Output? (Object.freeze shallow)

const obj = { a: 1, b: { c: 10 } }; Object.freeze(obj); obj.a = 9; obj.b.c = 99; console.log(obj);

Answer:

{ a: 1, b: { c: 99 } }

📌 Explanation

freeze → shallow
nested objects are still mutable.


5️⃣ Output? (setTimeout inside loop)

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

Answer:

4 4 4

📌 Explanation

var is function scoped → loop ends → i = 4
All callbacks reference the same i.

Fix with let or IIFE.


6️⃣ Output? (prototype chaining)

const a = { x: 1 }; const b = Object.create(a); const c = Object.create(b); console.log(c.x);

Answer: 1

📌 Explanation

c → b → a
a contains x, so c.x resolves to 1.


7️⃣ Output? (delete keyword)

const obj = { a: 10 }; console.log(delete obj.a); console.log(obj.a);

Answer:

true undefined

📌 Explanation

delete removes own properties.


8️⃣ Output? (callback vs promise timing)

setTimeout(() => console.log("timeout"), 0); Promise.resolve().then(() => console.log("promise")); console.log("end");

Answer:

end promise timeout

📌 Explanation

Microtask (promise) → runs before macrotask (setTimeout).


9️⃣ Output? (Deep destructuring)

const { a, b: { c: value } } = { a: 1, b: { c: 2 } }; console.log(a, value);

Answer:

1 2

🔟 Output? (Implicit return gotcha)**

const nums = [1,2,3]; const doubled = nums.map(num => { num * 2 }); console.log(doubled);

Answer: [undefined, undefined, undefined]

📌 Explanation

Using {} requires explicit return.

Fix:

nums.map(num => num * 2);



Set 7 — High-Level JS Logical + Concept Questions


1️⃣ Output? (Promise.all)

const p1 = Promise.resolve(1); const p2 = Promise.reject("Error"); const p3 = Promise.resolve(3); Promise.all([p1, p2, p3]) .then(res => console.log(res)) .catch(err => console.log(err));

Answer: "Error"

📌 Explanation

Promise.all() fails fast.
It stops at the first rejected promise.


2️⃣ Output? (Promise.race)

const fast = new Promise(res => setTimeout(res, 100, "Fast")); const slow = new Promise(res => setTimeout(res, 500, "Slow")); Promise.race([slow, fast]).then(console.log);

Answer: "Fast"


3️⃣ Output? (this inside class)

class User { name = "John"; getName() { return this.name; } } const u = new User(); const ref = u.getName; console.log(ref());

Answer: undefined

📌 Explanation

When the method is detached (ref), this becomes global.


4️⃣ Output? (Closures + loops)

function create() { let arr = []; for (let i = 0; i < 3; i++) { arr.push(function () { return i; }); } return arr; } const result = create(); console.log(result[0](), result[1](), result[2]());

Answer: 0 1 2

📌 Explanation

let → block-scoped → preserves value for each iteration.


5️⃣ Output? (Tricky object keys)

const obj = {}; obj[true] = "A"; obj[1] = "B"; obj["1"] = "C"; console.log(obj);

Answer:

{ "1": "C", "true": "A" }

📌 Explanation

  • 1 and "1" refer to same key

  • "C" overwrites "B"


6️⃣ Output? (Async recursion)

async function run() { console.log("A"); await run(); console.log("B"); } run();

Answer: Stack overflow (Maximum call stack size exceeded)

📌 Explanation

Infinite recursion — await does NOT stop call stack growth.


7️⃣ Output? (Symbol keys)

const sym = Symbol("x"); const obj = { [sym]: 10, x: 20 }; console.log(obj[sym], obj["x"]);

Answer: 10 20

📌 Explanation

Symbol keys don’t clash with string keys.


8️⃣ Output? (Promise chain)

Promise.resolve(5) .then(val => { console.log(val); return val * 2; }) .then() .then(val => console.log(val));

Answer:

5 10

📌 Explanation

A .then() with no callback just passes the value through.


9️⃣ Output? (Deep hoisting)

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

Answer: undefined

📌 Explanation

Hoisted as:

var a; console.log(a); // undefined a = 20;

🔟 Output? (Shadowing + TDZ)**

let x = 10; { console.log(x); let x = 20; }

Answer: ReferenceError

📌 Explanation

Block let x shadows outer x but is in temporal dead zone until declared.



Set 8 — Ultra-Advanced JavaScript Logical + Concept Questions


1️⃣ Output? (Microtask vs Macrotask Race)

setTimeout(() => console.log("T1"), 0); Promise.resolve() .then(() => console.log("P1")) .then(() => { setTimeout(() => console.log("T2"), 0); console.log("P2"); }); console.log("S");

Answer:

S P1 P2 T1 T2

📌 Why?

  • Sync: S

  • Microtask queue: P1P2

  • Macrotask queue: T1 (first), then T2


2️⃣ Output? (Async–Await Inside Loop)

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

Answer:

4 4 4

📌 Reason

var → function scoped → loop ends → i = 4.


3️⃣ Output? (async loop with await)

for (let i = 1; i <= 3; i++) { await new Promise(res => setTimeout(res, 100)); console.log(i); }

Answer:

1 2 3

📌 Reason

Each await blocks the loop iteration.


4️⃣ Output? (Chained awaits)

async function f() { return 1; } async function g() { console.log(await f()); console.log(await f()); } g();

Answer:

1 1

📌 Reason

Each await resolves independently.


5️⃣ Output? (Destructuring gotcha)

const data = { a: 1, b: 2 }; const { a: x, b: x } = data; console.log(x);

Answer: SyntaxError

📌 Reason

You can't declare two variables with same name in same destructuring object.


6️⃣ Output? (Prototype madness)

Function.prototype.x = 10; Object.prototype.y = 20; function test() {} const t = new test(); console.log(test.x); console.log(t.y); console.log(t.x);

Answer:

10 20 undefined

📌 Why?

  • test is a function → gets .x via Function.prototype

  • t is an object → gets .y via Object.prototype

  • But t.x doesn't exist → and prototype chain doesn’t reach Function.prototype.


7️⃣ Output? (Objects as functions)

function fun() { return { a: 1, b: function () { return this.a; } }; } const obj = fun(); const ref = obj.b; console.log(obj.b()); console.log(ref());

Answer:

1 undefined

📌 Reason

First call → this = obj
Second call → this = globala not defined → undefined.


8️⃣ Output? (Promise.resolve with then)

Promise.resolve(1) .then(2) .then(Promise.resolve(3)) .then(x => console.log(x));

Answer: 1

📌 Reason

.then() expects a function.
If you pass something else → it's ignored → value passes through unchanged.


9️⃣ Output? (Spread + mutation)

const a = { x: { y: 1 } }; const b = { ...a }; b.x.y = 999; console.log(a.x.y, b.x.y);

Answer: 999 999

📌 Reason

Shallow copy — nested objects shared.


🔟 Output? (Map key identity)**

const m = new Map(); m.set({}, "A"); m.set({}, "B"); console.log(m.size);

Answer: 2

📌 Reason

Each {} is a different reference → treated as unique key.


Set 9 — Expert-Level JavaScript Logical + Concept Questions


1️⃣ Output? (Promise.any)

Promise.any([ Promise.reject("A"), Promise.reject("B"), Promise.resolve("C"), ]).then(console.log) .catch(console.error);

Answer: "C"

📌 Explanation

Promise.any() returns the first fulfilled promise.
Rejections are ignored unless ALL fail.


2️⃣ Output? (Promise.allSettled)

Promise.allSettled([ Promise.resolve(1), Promise.reject(2), 3, ]).then(console.log);

Answer:

[ { status: "fulfilled", value: 1 }, { status: "rejected", reason: 2 }, { status: "fulfilled", value: 3 } ]

📌 Explanation

allSettled never rejects.
It reports the status of each promise.


3️⃣ Output? (async function returning promise)

async function test() { return Promise.resolve("Hello"); } test().then(console.log);

Answer: "Hello"

📌 Explanation

async automatically wraps return value in a resolved promise.


4️⃣ Output? (Generator + next values)

function* gen() { let x = yield 10; yield x + 5; } const it = gen(); console.log(it.next().value); console.log(it.next(20).value);

Answer:

10 25

📌 Explanation

1st next() returns first yield (10)
2nd next(20) → value assigned to x


5️⃣ Output? (WeakMap key behavior)

let obj = { a: 1 }; const wm = new WeakMap(); wm.set(obj, "data"); obj = null; console.log(wm);

Answer: WeakMap { <items cleared automatically> }

📌 Explanation

WeakMap keys must be objects.
When obj loses reference → GC removes it automatically.


6️⃣ Output? (setImmediate vs setTimeout vs Promise)

(Node.js-specific)

setTimeout(() => console.log("T"), 0); setImmediate(() => console.log("I")); Promise.resolve().then(() => console.log("P")); console.log("S");

Possible Answer (most common):

S P I T

📌 Explanation

  • Sync: S

  • Microtask: P

  • setImmediate runs before setTimeout(0)


7️⃣ Output? (Closure deep trick)

function outer() { var arr = []; for (var i = 0; i < 3; i++) { arr.push(() => i); } return arr; } const res = outer(); console.log(res[0](), res[1](), res[2]());

Answer: 3 3 3

📌 Explanation

var is shared → after loop ends, i = 3.


8️⃣ Output? (Object sealing)

const obj = { a: 1 }; Object.seal(obj); obj.a = 10; obj.b = 20; console.log(obj);

Answer: { a: 10 }

📌 Explanation

  • You can modify existing properties

  • Cannot add or delete properties


9️⃣ Output? (Function hoisting inside blocks)

{ function test() { console.log("A"); } } test();

Answer: "A" (in non-strict mode)

❌ Throws error in strict mode

📌 Explanation

Block-scoped function declarations are tricky:

  • Allowed in sloppy mode

  • Not allowed in strict mode


🔟 Output? (Promise chain + throw)**

Promise.resolve(1) .then(val => { throw val + 1; }) .catch(err => err * 2) .then(console.log);

Answer: 4

📌 Explanation

  • Throw → goes to catch

  • catch returns err * 2 → becomes new resolved value

  • printed = 4


Set 10 — Expert-Level JavaScript Logical + Concept Questions


1️⃣ Output? (Private class fields)

class User { #name = "Pranjal"; getName() { return this.#name; } } const u = new User(); console.log(u.getName()); console.log(u.#name);

Answer:

Pranjal SyntaxError

📌 Explanation

Private fields cannot be accessed outside the class.


2️⃣ Output? (Class inheritance + super)

class A { constructor() { this.x = 10; } } class B extends A { constructor() { super(); console.log(this.x); } } new B();

Answer: 10

📌 Explanation

super() initializes the parent class → this.x is set → then logged.


3️⃣ Output? (this in arrow function)

const obj = { a: 10, fn: () => console.log(this.a) }; obj.fn();

Answer: undefined

📌 Explanation

Arrow functions do not have their own this, they use the lexical scope.
In this case → global object → undefined.


4️⃣ Output? (Deep async + Promise chaining)

async function a() { console.log(1); return 2; } async function b() { console.log(3); return 4; } a().then(res => b().then(console.log));

Answer:

1 3 4

5️⃣ Output? (Destructuring + default values)

const obj = { a: 1 }; const { a = 10, b = 20 } = obj; console.log(a, b);

Answer:

1 20

📌 Explanation

a exists → default ignored
b missing → default 20 used


6️⃣ Output? (Nested destructuring + renaming)

const data = { a: { x: 10 }, b: 20 }; const { a: { x: y }, b } = data; console.log(y, b);

Answer:

10 20

7️⃣ Output? (Prototype + Object.create)

const parent = { x: 1 }; const child = Object.create(parent); child.y = 2; console.log(child.x, child.y); console.log(child.hasOwnProperty("x"));

Answer:

1 2 false

📌 Explanation

  • child.x → inherited from parent

  • hasOwnProperty → only own properties counted


8️⃣ Output? (Symbol + iteration)

const sym = Symbol("id"); const obj = { [sym]: 123, name: "Pranjal" }; for (let key in obj) console.log(key); console.log(Object.getOwnPropertySymbols(obj));

Answer:

name [Symbol(id)]

📌 Explanation

  • for..in ignores symbol keys

  • getOwnPropertySymbols lists them


9️⃣ Output? (Deep recursion + await)

async function recurse(n) { if (n <= 0) return 1; return n * await recurse(n - 1); } recurse(3).then(console.log);

Answer:

6

📌 Explanation

Factorial computed asynchronously using recursion.


🔟 Output? (Event loop + microtask vs macrotask)**

console.log("start"); setTimeout(() => console.log("timeout"), 0); Promise.resolve().then(() => console.log("promise")); console.log("end");

Answer:

start end promise timeout

Set 11 — Event & Event Loop Questions


1️⃣ Output? (Event loop + microtask vs macrotask)

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

Answer:

Start End Promise Timeout

Explanation:

  • Sync logs → Start, End

  • Promise → microtask → runs before macrotask

  • setTimeout → macrotask → runs last


2️⃣ Output? (Nested setTimeout + Promise)

setTimeout(() => console.log("T1"), 0); Promise.resolve().then(() => { console.log("P1"); setTimeout(() => console.log("T2"), 0); }); console.log("S");

Answer:

S P1 T1 T2

Explanation:

  • S → sync

  • P1 → microtask

  • T1 → macrotask

  • T2 → added to macrotask queue after P1 runs


3️⃣ Output? (Multiple microtasks)

Promise.resolve().then(() => console.log("P1")); Promise.resolve().then(() => console.log("P2")); console.log("S");

Answer:

S P1 P2

Explanation:
Microtasks run in order after the current stack is empty.


4️⃣ Output? (setTimeout 0 inside async)

async function foo() { console.log("A"); setTimeout(() => console.log("B"), 0); await Promise.resolve(); console.log("C"); } foo(); console.log("D");

Answer:

A D C B

Explanation:

  • A → sync inside async

  • D → next sync

  • await → microtask → C

  • setTimeout → macrotask → B


5️⃣ Output? (Event delegation)

<div id="parent"> <button id="child">Click</button> </div> <script> document.getElementById("parent").addEventListener("click", () => console.log("Parent")); document.getElementById("child").addEventListener("click", e => console.log("Child")); </script>

Question: Click on button → output?

Answer:

Child Parent

Explanation:
Event bubbles from child → parent.
Child runs first, then Parent.


6️⃣ Output? (Stop propagation)

document.getElementById("child").addEventListener("click", e => { console.log("Child"); e.stopPropagation(); }); document.getElementById("parent").addEventListener("click", () => console.log("Parent"));

Answer:

Child

Explanation:
stopPropagation() stops the event from bubbling.


7️⃣ Output? (Capture vs Bubble)

document.getElementById("parent").addEventListener("click", () => console.log("Parent Capture"), true); document.getElementById("child").addEventListener("click", () => console.log("Child Bubble"), false);

Answer: Click child

Parent Capture Child Bubble

Explanation:

  • Capture phase → Parent

  • Target/bubble → Child


8️⃣ Output? (setInterval + setTimeout + async)

setInterval(() => console.log("Interval"), 50); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("Sync");

Answer (approx order first iteration):

Sync Promise Timeout Interval

Explanation:

  • Sync → immediately

  • Promise → microtask

  • Timeout → macrotask → runs after microtasks

  • Interval → every 50ms


9️⃣ Output? (Event loop blocking)

setTimeout(() => console.log("T1"), 0); for (let i = 0; i < 1e9; i++) {} console.log("End");

Answer:

End T1

Explanation:

  • Long loop blocks the main thread

  • setTimeout cannot run until stack is free


🔟 Output? (Mouse event async simulation)

button.addEventListener("click", async e => { console.log("Click Start"); await Promise.resolve(); console.log("Click End"); });

Click the button → output?

Answer:

Click Start Click End

Explanation:

  • Async starts → logs "Click Start"

  • await → microtask → logs "Click End" after current execution context



Event Handling & Event Binding Questions — JavaScript


1️⃣ Output? (this in event handler)

<button id="btn">Click Me</button> <script> document.getElementById("btn").addEventListener("click", function () { console.log(this.id); }); </script>

Answer:

btn

Explanation:

  • In normal functions, this refers to the element that triggered the event.


2️⃣ Output? (Arrow function as event handler)

<button id="btn">Click Me</button> <script> document.getElementById("btn").addEventListener("click", () => { console.log(this.id); }); </script>

Answer:

undefined

Explanation:

  • Arrow functions do not have their own this; they use the lexical this from the scope where they were defined (here → window).


3️⃣ Output? (Multiple event listeners)

<div id="parent"> <button id="child">Click</button> </div> <script> document.getElementById("parent").addEventListener("click", () => console.log("Parent")); document.getElementById("child").addEventListener("click", () => console.log("Child")); </script>

Click button → output?

Answer:

Child Parent

Explanation:

  • Event bubbles from child → parent by default.


4️⃣ Stop propagation

<div id="parent"> <button id="child">Click</button> </div> <script> document.getElementById("child").addEventListener("click", e => { console.log("Child"); e.stopPropagation(); }); document.getElementById("parent").addEventListener("click", () => console.log("Parent")); </script>

Click child → output?

Answer:

Child

Explanation:

  • stopPropagation() prevents the event from bubbling.


5️⃣ Event delegation

<ul id="list"> <li>Item 1</li> <li>Item 2</li> </ul> <script> document.getElementById("list").addEventListener("click", e => { if (e.target.tagName === "LI") { console.log(e.target.textContent); } }); </script>

Click "Item 2" → output?

Answer:

Item 2

Explanation:

  • Event delegation → handle many child elements with one parent listener.


6️⃣ Vanilla JS vs React event binding

// Vanilla JS button.addEventListener("click", this.handleClick); // React <button onClick={this.handleClick}>Click</button>

Question: What’s the difference?

Answer:

  • Vanilla JS → uses native DOM events, this depends on function binding

  • React → synthetic event system, this must be bound (.bind(this) or arrow function)


7️⃣ Event capturing vs bubbling

parent.addEventListener("click", () => console.log("Parent"), true); child.addEventListener("click", () => console.log("Child"), false);

Click child → output?

Answer:

Parent Child

Explanation:

  • true → capture phase → Parent first

  • false → bubble phase → Child next


8️⃣ Removing event listener

function handleClick() { console.log("Clicked"); } button.addEventListener("click", handleClick); button.removeEventListener("click", handleClick);

Click button → output?

Answer: Nothing

Explanation:

  • To remove a listener, the function reference must be the same, not an anonymous function.


9️⃣ this in class event binding (React / JS)

class MyComponent { constructor() { this.name = "React"; this.handleClick = this.handleClick.bind(this); } handleClick() { console.log(this.name); } } const c = new MyComponent(); c.handleClick();

Answer:

React

Explanation:

  • .bind(this) ensures this points to the class instance.


🔟 Delegation + dynamic elements

<ul id="list"></ul> <script> document.getElementById("list").addEventListener("click", e => { if (e.target.tagName === "LI") console.log(e.target.textContent); }); const li = document.createElement("li"); li.textContent = "Dynamic Item"; document.getElementById("list").appendChild(li);

Click new "Dynamic Item" → output?

Answer:

Dynamic Item

Explanation:

  • Delegation allows handling future elements added dynamically.



Post a Comment

Previous Post Next Post