Skip to content
Plurafy

JavaScript Quick Coding

JavaScript Quick Coding

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 undefineds

Why 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 var in the global scope are attached directly as properties to the global object (such as window in web browsers). Therefore, this.fruit1 successfully accesses that property and evaluates to "apple".

  • const fruit2 = "banana";

    Variables declared with let and const in 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 named fruit2, this.fruit2 evaluates to undefined.

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 0
first console log 1
first console log 2
first console log 3
first console log 4
inside timeout log 5
inside timeout log 5
inside timeout log 5
inside timeout log 5
inside timeout log 5

Let’s analyze the code and its output

  • var is function-scoped (or globally scoped if outside a function), meaning only one variable i is created for the entire loop.
  • The synchronous console.log('first console log ', i) runs immediately during each iteration, capturing i at that exact moment (0, 1, 2, 3, 4).
  • However, the setTimeout callbacks 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 variable i has finally incremented to 5 (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 let keyword

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 0
first console log 1
first console log 2
first console log 3
first console log 4
inside timeout log 0
inside timeout log 1
inside timeout log 2
inside timeout log 3
inside timeout log 4

How it works?

  • let is block-scoped.
  • Every time the for loop iterates, JavaScript creates a new, unique binding (a fresh variable i) specifically for that iteration’s block.
  • Even though setTimeout executes asynchronously after the loop has finished, each callback function retains a closure referencing its own distinct i value from that specific iteration.

What will the following code output?

var x = 10;
function foo() {
console.log(x);
var x = 20;
}
foo();
Answer
undefined

Explanation

  • JavaScript hoists variable declarations (using var) to the top of their enclosing function scope.
  • Inside foo(), the local variable x is hoisted, shadowing the global variable x = 10.
  • However, only the declaration is hoisted, not the assignment (= 20).
  • When console.log(x) runs, the local x exists in memory, but its value is still undefined because 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
1
4
3
2

Explanation

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 this based on how they are called. When called as obj.regularGreet(), this refers to obj.
  • Arrow functions do not have their own this. Instead, they inherit this lexically from their surrounding scope (in this case, the global scope or module scope where obj is defined), meaning this.name resolves to undefined.

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 with this explicitly bound to john, returning 'John'.
  • getName() extracts the method reference and executes it as a standalone function. In non-strict mode, this defaults to the global object (window / globalThis), which does not have a name property, returning undefined (or throws a TypeError in strict mode).
  • user.getName() assigns the exact same function reference to user. When invoked via user.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
D
E
A
F
H
G: B

Explanation

  • Calling generator() creates an async generator object without executing any code yet ('D' -> 'E').
  • Calling gen.next() starts execution inside the generator until the first yield/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 pending Promise from gen.next(), logging 'F'.
  • .then() attaches a microtask callback to step1, logging 'H'.
  • Once the current synchronous call stack empties, the microtask queue flushes: the generator resumes, yields 'B', resolves step1, and triggers .then() to log 'G: B'.

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
1
1
1

Explanation

  • initial holds a reference to the original object { count: 0 }.
  • store.increment() mutates the property count on that existing object in place. Because initial points to that same object in memory, initial.count becomes 1.
  • store.reset() reassigns the internal variable state to point to a new object ({ count: 0 }). However, initial still retains its reference to the original object.
  • The second store.increment() mutates the new object referenced by state.
  • Therefore, initial.count remains 1, while store.getState().count reads from the new object and returns 1.

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 decrements this.running and recursively calls next() to pick up queued jobs automatically.

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.

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
10
undefined

When 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.

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

4
1
3
6
8
7
5

Let’s understand the order of execution here.

  1. Synchronous Execution (Runs first):

    • console.log('4') prints 4.
    • setTimeout sends 5 to the macrotask queue.
    • async1() starts: console.log('1') prints 1.
    • async2() runs: console.log('3') prints 3. It hits await, pausing async1 and queuing its continuation as a microtask.
    • new Promise executor runs synchronously: console.log('6') prints 6. resolve() queues the .then() callback as a microtask.
    • console.log('8') prints 8.
    • Sync phase finishes, having printed: 4, 1, 3, 6, 8.
  2. Microtask Queue (Promises & await continuations):

    • First microtask registered: The rest of async1 (console.log('2')) prints 2.
    • Second microtask registered: The Promise .then() (console.log('7')) prints 7.
  3. Macrotask Queue:

    • Finally, the setTimeout callback (console.log('5')) prints 5.

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
null
20

What exactly happened here?

  • In JavaScript destructuring, default values (= 10 or = 20) are only triggered if the property is strictly undefined (or missing entirely).

  • Because a was explicitly assigned null, the default value was skipped, leaving a as null. However, b was undefined, which did trigger its default value, making b equal to 20.

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
PARENT

This is a classic trap regarding polymorphism during construction.

  • When new Child() runs, super() calls the Parent constructor. Inside Parent, this refers to the new Child instance. When Parent calls this.printName(), JavaScript looks up the prototype chain and invokes Child’s version of printName.

  • At that exact moment, this.name is 'parent', and Child’s method calls .toUpperCase(), printing PARENT.

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
false
true

When 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