Complete Interview Questions & Answer Bank
Full collection of 50 JavaScript interview questions ranging from core fundamentals and coding challenges to advanced engine internals.
Q1: What are the primitive data types in JavaScript vs objects?
JavaScript has 7 primitive data types: string, number, bigint, boolean, undefined, symbol, and null. Primitives are immutable and passed by value. Objects (including arrays, functions, and plain objects) are mutable collections of key-value properties and are passed by reference.
Primitive types are immutable and stored directly by value.
Objects are mutable reference types stored by memory location.
What does typeof null return in JavaScript?
Q2: What is the difference between var, let, and const?
var is function-scoped (or globally scoped) and hoisted with an initial value of undefined. let and const are block-scoped and hoisted into a Temporal Dead Zone (TDZ). const creates a read-only variable reference that cannot be reassigned after declaration.
varis function-scoped;letandconstare block-scoped.letandconstexist in the Temporal Dead Zone prior to declaration.
What error occurs when accessing a let variable before its declaration line?
Q3: What is the difference between == and === in JavaScript?
== (loose equality) performs type coercion to convert operands to a common type before comparing. === (strict equality) checks for equality without type conversion; both the value and the type must match.
==converts operands to the same type before comparison.===compares both value and data type without coercion.
What is the result of the comparison: [] == false?
Q4: How does Hoisting work in JavaScript?
Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their containing scope during creation phase. Function declarations are hoisted with their complete definitions, var declarations are hoisted with undefined, while let and const remain uninitialized in the TDZ.
Function declarations are hoisted with their definitions fully accessible.
varis hoisted asundefined;let/constare placed in the TDZ.
What is printed when calling foo() declared as: var foo = function() { return 1; }; before assignment?
Q5: What is Scope and the Scope Chain?
Scope determines the accessibility of variables in code. JavaScript has Global Scope, Function Scope, and Block Scope. When a variable is referenced, JavaScript looks in the current scope; if not found, it traverses up the Scope Chain to outer enclosing scopes until it reaches the global scope.
Lexical scope means inner scopes can access outer scope variables.
The scope chain lookup travels outward up to global scope.
Where does lexical scope determine variable accessibility from?
Q6: What is a Closure in JavaScript?
A closure is the combination of a function bundled together with references to its surrounding lexical environment. Closures give inner functions access to an outer function's scope variables even after the outer function has finished executing.
Functions retain references to variables in their lexical environment.
Powers state encapsulation, module patterns, and memoization.
What will console.log print: for(var i=0; i<3; i++) { setTimeout(() => console.log(i), 100); }?
Q7 [Coding]: Implement a counter function using closures that supports increment, decrement, and getValue.
function createCounter(initialValue = 0) {
let count = initialValue;
return {
increment: () => ++count,
decrement: () => --count,
getValue: () => count
};
}
This encapsulates count inside a private closure, exposing only controlled modifier functions.
Enables private variables without native class private fields.
Exposes object methods that maintain access to closed-over state.
Can code outside createCounter access or modify the internal count variable directly?
Q8: How does the `this` keyword work in different execution contexts?
The value of this depends on how a function is called: standard method call (obj.fn()) sets this to obj; plain function call sets this to window/undefined (strict mode); constructors (new Fn()) bind this to the new instance; arrow functions bind this lexically from their outer scope.
Standard function
thisis bound dynamically at call time.Arrow function
thisis determined statically from lexical outer scope.
What is this inside an arrow function defined within an object method?
Q9: What is the difference between call(), apply(), and bind()?
call() invokes a function with a specified this context and arguments passed individually (fn.call(ctx, arg1, arg2)). apply() invokes the function with arguments passed as an array (fn.apply(ctx, [arg1, arg2])). bind() returns a new function with this bound permanently.
callaccepts arguments comma-separated;applyaccepts an array.bindreturns a bound copy of the function without immediate execution.
Which method executes a function immediately with an array of arguments?
Q10: How does Prototypal Inheritance work in JavaScript?
Objects in JavaScript have an internal [[Prototype]] link (exposed as __proto__). When accessing a property on an object, JavaScript looks at the object first, then traverses up the prototype chain until the property is found or null is reached.
Objects inherit properties and methods dynamically via prototype delegation.
Top of the prototype chain ends at
Object.prototype.__proto__ === null.
What method creates a new object using an existing object as its prototype?
Q11: How do ES6 Classes relate to Prototypal Inheritance?
ES6 Classes are syntactic sugar built on top of prototypal inheritance. Class methods are stored on the constructor's prototype property, and the extends keyword establishes prototype inheritance between prototype objects.
Classes provide cleaner syntax over function prototypes.
Under the hood, classes use prototypal delegation and function constructors.
Where are methods defined inside an ES6 class body attached?
Q12: How do Arrow Functions differ from Regular Functions?
Arrow functions: 1) Do not bind their own this or arguments object. 2) Cannot be used as constructor functions with new. 3) Do not have a prototype property. 4) Cannot be used as generator functions.
Arrow functions inherit lexical
thisandarguments.They cannot act as constructors or generators.
What error is thrown when invoking an arrow function with the new keyword?
Q13: What is the JavaScript Event Loop?
The Event Loop enables non-blocking asynchronous execution. JavaScript executes synchronous code on the single Call Stack. Asynchronous tasks offload to APIs and queue callbacks into the Microtask Queue (Promises) or Macrotask Queue (timers). The Event Loop empties the call stack, drains all microtasks, and then processes one macrotask.
Call stack processes synchronous tasks sequentially.
Microtasks (Promises) take execution priority over Macrotasks (setTimeout).
Which queue has higher execution priority: Microtask or Macrotask Queue?
Q14 [Coding]: Predict the execution output of this asynchronous code snippet.
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');
Output: 1, 4, 3, 2.
Reason: Synchronous logs (1, 4) run first. Promise.then enters the Microtask queue (3), executing before setTimeout in the Macrotask queue (2).
Synchronous code runs to completion first.
Microtasks (
Promise) run before Macrotasks (setTimeout).
In what order are the microtask and macrotask logged above?
Q15: What is a Promise and what are its three states?
A Promise represents the eventual completion or failure of an asynchronous operation. Its states are: 1) pending (initial state), 2) fulfilled (operation succeeded), 3) rejected (operation failed). State transitions are immutable once settled.
Promises encapsulate async outcomes in pending, fulfilled, or rejected states.
Transitions are permanent; settled states cannot change.
What occurs if resolve() and reject() are both called inside the same Promise executor?
Q16: How does async/await work under the hood?
async/await is syntactic sugar over Promises and Generators. An async function always returns a Promise. When await is encountered, function execution yields pause control back to the Event Loop until the awaited Promise settles.
asyncfunctions wrap return values in resolved Promises.awaitpauses async function execution without blocking the main event thread.
What does an async function return if it explicitly returns a plain primitive value 42?
Q17: What is the difference between Promise.all, Promise.allSettled, Promise.race, and Promise.any?
Promise.all(): Resolves when all resolve; rejects immediately if any reject.Promise.allSettled(): Resolves when all settle (fulfilled or rejected).Promise.race(): Settles as soon as any promise settles.Promise.any(): Resolves as soon as any promise fulfills; rejects if all reject.
Promise.allfails fast on initial rejection.Promise.allSettledguarantees tracking outcome states for every promise.
Which Promise combinator rejects ONLY if ALL input promises reject?
Q18 [Coding]: Implement a simple polyfill for Promise.all().
function myPromiseAll(promises) {
return new Promise((resolve, reject) => {
let results = [];
let completed = 0;
if (promises.length === 0) return resolve([]);
promises.forEach((p, index) => {
Promise.resolve(p)
.then(val => {
results[index] = val;
completed++;
if (completed === promises.length) resolve(results);
})
.catch(reject);
});
});
}
Tracks completed promise counts against total length.
Preserves array output index placement matching original input ordering.
Why is results[index] = val used instead of results.push(val) in Promise.all polyfills?
Q19: What is Event Bubbling and Event Capturing in the DOM?
DOM event propagation has 3 phases: 1) Capturing Phase (event travels down from document root to target), 2) Target Phase (event reaches target node), 3) Bubbling Phase (event bubbles up from target to document root). addEventListener defaults to handling events in the bubbling phase.
Capturing travels downward; Bubbling travels upward.
Passing
{ capture: true }attaches listeners to capturing phase.
Which method stops an event from propagating further up or down the DOM tree?
Q20: What is Event Delegation and why is it useful?
Event Delegation is a pattern where a single event listener is attached to a parent element to manage events for all its present and future child elements by leveraging event bubbling and checking event.target.
Reduces memory overhead by minimizing total event listener count.
Handles dynamically inserted child elements without requiring new listener attachments.
Which event property points to the actual element that triggered the event?
Q21 [Coding]: Write a debounce function implementation.
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
Debouncing delays function execution until a specified idle duration has elapsed since the last event invocation.
Resets timer on every new event trigger call.
Ideal for search auto-complete inputs and window resize handlers.
When does a debounced function execute after rapid continuous triggers?
Q22 [Coding]: Write a throttle function implementation.
function throttle(fn, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
Throttling enforces a maximum execution rate, ensuring the function fires at most once per defined time interval.
Executes function at regular, rate-limited time intervals.
Ideal for scroll position tracking and window resize listeners.
How does throttling differ from debouncing?
Q23: What is the difference between a Shallow Copy and a Deep Copy?
A shallow copy (Object.assign(), {...obj}) copies top-level properties, but nested objects/arrays retain memory references. A deep copy (structuredClone(), JSON.parse(JSON.stringify())) recursively duplicates all nested structures, creating completely independent object graphs.
Shallow copy leaves nested objects linked by reference.
Deep copy duplicates all nested layers independently.
Which modern native JavaScript global function performs deep copying safely?
Q24 [Coding]: Write a function to recursively flatten a deeply nested array.
function flattenArray(arr) {
return arr.reduce((acc, val) =>
Array.isArray(val)
? acc.concat(flattenArray(val))
: acc.concat(val),
[]);
}
// Example: flattenArray([1, [2, [3, 4]], 5]) -> [1, 2, 3, 4, 5]
Uses recursion and
Array.isArray()to unravel nested sub-arrays.Native equivalent:
arr.flat(Infinity).
What built-in Array prototype method flattens nested arrays to any depth directly?
Q25: What is the difference between ES Modules (ESM) and CommonJS (CJS)?
CommonJS (require/module.exports) is synchronous and evaluated dynamically at runtime. ES Modules (import/export) are asynchronous, statically analyzed at compile-time (enabling tree-shaking), and strict mode by default.
CJS loads modules dynamically at runtime using
require().ESM uses static
import/exportsyntax allowing build optimization and tree-shaking.
Why does ES Module syntax enable Tree-Shaking optimization in bundlers?
Q26: What is Function Currying?
Currying is a technique of transforming a function with multiple arguments into a sequence of functions that each take a single argument (f(a, b, c) into f(a)(b)(c)).
Transforms multi-argument functions into unary function chains.
Enables partial application and higher-order functional composition.
How would you call a curried function add(a)(b) to calculate 2 + 3?
Q27 [Coding]: Implement a generic curry() helper function.
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return function(...nextArgs) {
return curried.apply(this, args.concat(nextArgs));
};
};
}
Compares gathered
args.lengthagainst the expected function parameter count (fn.length).Recursively returns outer wrapper functions until all parameters are fulfilled.
What property of a Function object indicates its declared expected argument count?
Q28: What is the difference between Map, Set, WeakMap, and WeakSet?
Map: Key-value store accepting any data type key.Set: Collection of unique values.WeakMap/WeakSet: Hold garbage-collectable weak references strictly to objects/symbols. Their keys/elements are non-enumerable.
Mapsupports keys of any type;WeakMapkeys MUST be objects/symbols.WeakMapreferences do not prevent garbage collection if no other references exist.
Why are WeakMap keys non-enumerable?
Q29: What are Symbols in JavaScript and what are their primary use cases?
Symbol is a primitive type that returns guaranteed unique identifiers (Symbol('id') !== Symbol('id')). They are used to create private object property keys that avoid key collision issues across external modules.
Symbols generate guaranteed unique primitive property keys.
Used for well-known metaprogramming symbols (e.g.,
Symbol.iterator).
Do Symbol object keys appear in standard for...in loops or Object.keys()?
Q30: How do Generators and Iterators work in JavaScript?
An Iterator is an object with a next() method returning { value, done }. Generators (function*) are special functions that can pause execution using yield and resume when next() is called on their returned Generator object.
yieldpauses generator functions and returns execution values.Generators implement the iterable protocol automatically.
Which keyword pauses execution inside a Generator function?