JavaScript Quick Coding
JavaScript Quick Coding
1. Block Scoping
Section titled “1. Block Scoping”Can you guess the output of the following log?
var fruit1 = "apple";const fruit2 = "banana";
console.log(`I want to eat ${this.fruit1}s and ${this.fruit2}s`);Answer
I want to eat apples and undefinedsWhy this.fruit1 prints "apple" and this.fruit2 prints undefined?
In JavaScript, how a variable is declared determines whether it becomes a property of the global object (which this refers to in the global scope).
-
var fruit1 = "apple";Variables declared with
varin the global scope are attached directly as properties to the global object (such aswindowin web browsers). Therefore,this.fruit1successfully accesses that property and evaluates to"apple". -
const fruit2 = "banana";Variables declared with
letandconstin the global scope are not added as properties to the global object. Instead, they live in a separate, block-level Script scope. Because the global object has no property namedfruit2,this.fruit2evaluates toundefined.
Lets try one more
for (var i = 0; i < 5; i++) { console.log('first console log ', i); setTimeout(function () { console.log('inside timeout log', i); }, 0);}Can you guess the output of above code?
Answer
first console log 0first console log 1first console log 2first console log 3first console log 4inside timeout log 5inside timeout log 5inside timeout log 5inside timeout log 5inside timeout log 5Let’s analyze the code and its output
varis function-scoped (or globally scoped if outside a function), meaning only one variableiis created for the entire loop.- The synchronous
console.log('first console log ', i)runs immediately during each iteration, capturingiat that exact moment(0, 1, 2, 3, 4). - However, the
setTimeoutcallbacks are pushed to the event queue and only execute after the entire loop has completed. By the time the timeouts run, the loop has finished, and the single shared variableihas finally incremented to5(the condition that terminated the loop). As a result, all five timeout callbacks look up and print the final value:5.
We can fix this using
letkeyword
for (let i = 0; i < 5; i++) { console.log('first console log ', i); setTimeout(function () { console.log('inside timeout log', i); }, 0);}Output:
first console log 0first console log 1first console log 2first console log 3first console log 4inside timeout log 0inside timeout log 1inside timeout log 2inside timeout log 3inside timeout log 4How it works?
letis block-scoped.- Every time the
forloop iterates, JavaScript creates a new, unique binding (a fresh variablei) specifically for that iteration’s block. - Even though
setTimeoutexecutes asynchronously after the loop has finished, each callback function retains a closure referencing its own distinctivalue from that specific iteration.
2. Hoisting and Variable Shadowing
Section titled “2. Hoisting and Variable Shadowing”What will the following code output?
var x = 10;
function foo() { console.log(x); var x = 20;}
foo();Answer
undefinedExplanation
- JavaScript hoists variable declarations (using
var) to the top of their enclosing function scope. - Inside
foo(), the local variablexis hoisted, shadowing the global variablex = 10. - However, only the declaration is hoisted, not the assignment (
= 20). - When
console.log(x)runs, the localxexists in memory, but its value is stillundefinedbecause the assignment hasn’t happened yet.
3. Microtasks vs. Macrotasks (The Event Loop)
Section titled “3. Microtasks vs. Macrotasks (The Event Loop)”What is the exact order of the console logs here?
console.log('1');
setTimeout(function () { console.log('2');}, 0);
Promise.resolve().then(function () { console.log('3');});
console.log('4');Answer
1432Explanation
JavaScript handles asynchronous code using different queues with varying priorities:
- Synchronous code runs first:
'1'and ’4'are logged immediately. - Microtasks (like
Promise.then()callbacks) have higher priority than macrotasks. Once the call stack is clear, the microtask queue runs, logging'3'. - Macrotasks (like
setTimeout) have lower priority. The timeout callback is placed in the callback queue and executes last, logging'2'.
4. Arrow Functions vs. Regular Functions (this binding)
Section titled “4. Arrow Functions vs. Regular Functions (this binding)”What will this code output?
const obj = { name: 'Alice', regularGreet: function() { console.log('Hello, ' + this.name); }, arrowGreet: () => { console.log('Hello, ' + this.name); }};
obj.regularGreet();obj.arrowGreet();Answer
Hello, Alice Hello, undefined (or window name in non-strict browser mode)
Explanation
- Regular functions dynamically bind
thisbased on how they are called. When called asobj.regularGreet(),thisrefers toobj. - Arrow functions do not have their own
this. Instead, they inheritthislexically from their surrounding scope (in this case, the global scope or module scope whereobjis defined), meaningthis.nameresolves toundefined.
5. Prototypal Inheritance & Explicit Binding
Section titled “5. Prototypal Inheritance & Explicit Binding”What will the following code output?
function Person(name) { this.name = name;}
Person.prototype.getName = function () { return this.name;};
const john = new Person('John');const getName = john.getName;
const user = { name: 'Jane', getName: john.getName};
console.log(john.getName());console.log(getName());console.log(user.getName());Answer
John undefined Jane
Explanation
john.getName()executes withthisexplicitly bound tojohn, returning'John'.getName()extracts the method reference and executes it as a standalone function. In non-strict mode,thisdefaults to the global object (window/globalThis), which does not have anameproperty, returningundefined(or throws aTypeErrorin strict mode).user.getName()assigns the exact same function reference touser. When invoked viauser.getName(), JavaScript sets this to the object preceding the dot (user), returning'Jane'.
6. Async Microtask Pipelines & Generator Execution
Section titled “6. Async Microtask Pipelines & Generator Execution”What is the execution order of the console logs in this snippet?
async function* generator() { console.log('A'); yield await Promise.resolve('B'); console.log('C');}
async function run() { console.log('D'); const gen = generator(); console.log('E');
const step1 = gen.next(); console.log('F');
step1.then(res => console.log('G:', res.value)); console.log('H');}
run();Answer
DEAFHG: BExplanation
- Calling
generator()creates an async generator object without executing any code yet ('D' -> 'E'). - Calling
gen.next()starts execution inside the generator until the firstyield/await('A'). - The expression
await Promise.resolve('B')pauses the generator and schedules a microtask to resume it once the promise resolves. - Control immediately returns to
run(), returning a pendingPromisefromgen.next(), logging'F'. .then()attaches a microtask callback tostep1, logging'H'.- Once the current synchronous call stack empties, the microtask queue flushes: the generator resumes, yields
'B', resolvesstep1, and triggers.then()to log'G: B'.
7. Object Mutability & Closure References
Section titled “7. Object Mutability & Closure References”What gets logged when fn() is invoked?
function createStore() { let state = { count: 0 };
return { getState: () => state, increment: () => { state.count++; }, reset: () => { state = { count: 0 }; } };}
const store = createStore();const initial = store.getState();
store.increment();console.log(initial.count);
store.reset();store.increment();console.log(initial.count);console.log(store.getState().count);Answer
111Explanation
initialholds a reference to the original object{ count: 0 }.store.increment()mutates the property count on that existing object in place. Becauseinitialpoints to that same object in memory,initial.countbecomes1.store.reset()reassigns the internal variablestateto point to a new object ({ count: 0 }). However,initialstill retains its reference to the original object.- The second
store.increment()mutates the new object referenced by state. - Therefore,
initial.countremains1, while store.getState().count reads from the new object and returns1.
8. Custom Task Scheduler with Concurrency Limits
Section titled “8. Custom Task Scheduler with Concurrency Limits”Implement a TaskQueue class in JavaScript that runs asynchronous tasks with a maximum concurrency limit N.
class TaskQueue { constructor(concurrency) { this.concurrency = concurrency; this.running = 0; this.queue = []; }
add(task) { return new Promise((resolve, reject) => { this.queue.push(async () => { try { const result = await task(); resolve(result); } catch (error) { reject(error); } }); this.next(); }); }
next() { while (this.running < this.concurrency && this.queue.length > 0) { const task = this.queue.shift(); this.running++; task().finally(() => { this.running--; this.next(); }); } }}Key Architecture Concepts Handled:
- Promise Wrapper: Wraps pushed tasks inside a new Promise so callers can await
queue.add(task)individually. - Non-blocking Loop: Iterates through pending tasks as long as
running < concurrency. - Resource Cleanup: The
.finally()handler decrementsthis.runningand recursively callsnext()to pick up queued jobs automatically.
9. The Trap of arguments and Context
Section titled “9. The Trap of arguments and Context”What does the following code log to the console, and why?
const length = 4;
function callback() { console.log(this.length);}
const object = { length: 5, method(fn) { arguments[0](); }};
object.method(callback, 1, 2);Answer
3
Calling arguments[0]() implicitly sets this to the arguments array-like
object itself. Since three arguments were passed (callback, 1, 2),
arguments.length evaluates to 3.
10. Prototype Setters & Instance State
Section titled “10. Prototype Setters & Instance State”What will the two console.log statements output at the end of this script?
const parent = { get value() { return this._value; }, set value(v) { this._value = v * 2; }};
const child = Object.create(parent);child.value = 5;
console.log(child.value);console.log(parent.value);Answer
10undefinedWhen a setter is defined on a prototype (parent), invoking it via an instance (child.value = 5) binds this inside the setter to the instance (child), not the prototype. This creates child._value = 10, leaving parent._value untouched and thus undefined.
11. The Event Loop Order
Section titled “11. The Event Loop Order”What is the exact order of numbers printed to the console when this script runs?
async function async1() { console.log('1'); await async2(); console.log('2');}
async function async2() { console.log('3');}
console.log('4');
setTimeout(() => { console.log('5');}, 0);
async1();
new Promise((resolve) => { console.log('6'); resolve();}).then(() => { console.log('7');});
console.log('8');Answer
The actual order will be
4136875Let’s understand the order of execution here.
-
Synchronous Execution (Runs first):
console.log('4')prints4.setTimeoutsends5to the macrotask queue.async1()starts:console.log('1')prints1.async2()runs:console.log('3')prints3. It hitsawait, pausingasync1and queuing its continuation as a microtask.new Promiseexecutor runs synchronously:console.log('6')prints6.resolve()queues the.then()callback as a microtask.console.log('8')prints8.- Sync phase finishes, having printed:
4, 1, 3, 6, 8.
-
Microtask Queue (Promises & await continuations):
- First microtask registered: The rest of
async1(console.log('2')) prints2. - Second microtask registered: The Promise
.then()(console.log('7')) prints7.
- First microtask registered: The rest of
-
Macrotask Queue:
- Finally, the
setTimeoutcallback (console.log('5')) prints5.
- Finally, the
12. The Destructuring Default Trap
Section titled “12. The Destructuring Default Trap”What does the following code log to the console?
const { a = 10, b = 20 } = { a: null, b: undefined };
console.log(a);console.log(b);Answer
null20What exactly happened here?
-
In JavaScript destructuring, default values (
= 10 or = 20) are only triggered if the property is strictlyundefined(or missing entirely). -
Because
awas explicitly assignednull, the default value was skipped, leavingaasnull. However,bwasundefined, which did trigger its default value, makingbequal to20.
13. Polymorphism During Construction
Section titled “13. Polymorphism During Construction”What does the following script print to the console when new Child() is executed?
class Parent { constructor() { this.name = 'parent'; this.printName(); } printName() { console.log(this.name); }}
class Child extends Parent { constructor() { super(); this.name = 'child'; } printName() { console.log(this.name.toUpperCase()); }}
new Child();Answer
PARENTThis is a classic trap regarding polymorphism during construction.
-
When
new Child()runs,super()calls theParentconstructor. InsideParent, this refers to the newChildinstance. WhenParentcallsthis.printName(), JavaScript looks up the prototype chain and invokesChild’s version ofprintName. -
At that exact moment,
this.nameis'parent', andChild’s method calls.toUpperCase(), printingPARENT.
14. The Proxy Interception
Section titled “14. The Proxy Interception”What will the two console.log statements output?
const target = { a: 1, c: 3 };
const proxy = new Proxy(target, { has(target, prop) { if (prop === 'a') return false; return prop in target; }});
console.log('a' in proxy);console.log('c' in proxy);Answer
falsetrueWhen checking 'a' in proxy, the trap intercepted it, matched prop === 'a', and explicitly returned false. When checking 'c' in proxy, it fell through to prop in target, which correctly evaluated to true