JavaScript knowledge reference Essential JavaScript Concepts Explore all 134 knowledge cards from one complete menu. Each concept includes a quick tip, concise explanation, memory formula, example, and real-world uses for everyday reference, technical discussions, and interview preparation.
Question 01 1. What is JavaScript, and why is it important? Quick recall Concept Glance Card 30 sec
01 Easy tipJavaScript is a high-level programming language primarily used to create interactive web applications. 02 Concise explanation“JavaScript is a high-level programming language primarily used to create interactive web applications. It runs in browsers and in server-side environments such as Node.js, and supports functional, object-oriented, and event-driven programming.”
03 Memory formulaHTML = structure + CSS = appearance + JavaScript = behaviour04 Real-world usesinteractive interfaces API calls form handling full-stack applications Question 02 2. What are the different data types in JavaScript? Quick recall Concept Glance Card 30 sec
01 Easy tipJavaScript has seven primitive types: string, number, boolean, undefined, null, symbol, and bigint. let value = 10;
value = 'Hello';
typeof value; // 'string' 02 Concise explanation“JavaScript has seven primitive types: string, number, boolean, undefined, null, symbol, and bigint. Primitive values are immutable. Objects represent more complex structures; arrays and functions are specialised kinds of objects.”
03 Memory formula7 primitives + objects = JavaScript values04 Real-world usesvalidation safe comparisons API data debugging Question 03 3. What is the difference between var, let, and const? Quick recall Concept Glance Card 30 sec
01 Easy tipvar is function-scoped and can be redeclared and reassigned. let score = 10;
score = 20;
const user = { name: 'Alex' };
user.name = 'Sam'; // Allowed 02 Concise explanation“var is function-scoped and can be redeclared and reassigned. let and const are block-scoped; let permits reassignment, while const does not permit the binding to be reassigned.”
03 Memory formulaconst by default + let when reassigned + avoid var04 Real-world usessafe bindings block scope loop variables preventing accidental reassignment Question 04 4. What is hoisting? Quick recall Concept Glance Card 30 sec
01 Easy tipFunctions work early; var gives undefined; let and const give a ReferenceError. sayHello(); // Works
function sayHello() {
console.log('Hello');
}
console.log(total); // undefined
var total = 10;
console.log(price); // ReferenceError
let price = 20; 02 Concise explanation“Hoisting means JavaScript creates declarations before executing their scope. Function declarations are initialized immediately, var starts as undefined, and let and const remain inaccessible in the temporal dead zone until their declarations are reached.”
03 Memory formulaFunction ready → var undefined → let/const TDZ04 Real-world usesfunction declarations understanding undefined temporal dead zone errors function expressions Question 05 5. What is a closure? Quick recall Concept Glance Card 30 sec
01 Easy tipA closure remembers variables from where it was created, even after the outer function finishes. function createCounter() {
let count = 0;
return () => ++count;
}
const counter = createCounter();
counter(); // 1
counter(); // 2 02 Concise explanation“A closure is when an inner function keeps access to variables from its outer scope after the outer function has finished. Here, the counter remembers and updates count.”
03 Memory formulaFunction + remembered outer variables = closure04 Real-world usesprivate state counters event handlers callbacks function factories React hooks Question 06 6. What is the difference between == and ===? Quick recall Concept Glance Card 30 sec
01 Easy tipLoose equality (==) performs type coercion before comparison. 5 == '5'; // true
5 === '5'; // false
Object.is(NaN, NaN); // true 02 Concise explanation“Loose equality (==) performs type coercion before comparison. Strict equality (===) compares values without coercing their types, making its behaviour easier to predict.”
03 Memory formula== converts, === compares directly04 Real-world usespredictable conditions input validation avoiding coercion bugs Question 07 7. What is an arrow function? Quick recall Concept Glance Card 30 sec
01 Easy tipAn arrow function is concise syntax for a function expression. const add = (first, second) => first + second; 02 Concise explanation“An arrow function is concise syntax for a function expression. Unlike regular functions, arrow functions do not create their own this, arguments, or prototype; they inherit this from the surrounding lexical scope.”
03 Memory formulaShort function + lexical this = arrow function04 Real-world usescallbacks array methods preserving surrounding this Question 08 8. What does the this keyword mean? Quick recall Concept Glance Card 30 sec
01 Easy tipIn a regular function, the value of this generally depends on how the function is called. const user = {
name: 'Alex',
introduce() {
return this.name;
},
};
user.introduce(); // 'Alex' 02 Concise explanation“In a regular function, the value of this generally depends on how the function is called. A method call usually sets this to the object before the dot, while a standalone function receives undefined in strict mode.”
03 Memory formulaRegular this = call site; arrow this = outer scope04 Real-world usesobject methods classes event handlers function binding Question 09 9. What is event bubbling? Quick recall Concept Glance Card 30 sec
01 Easy tipEvent bubbling is the process in which an event starts at its target and propagates upward through its ancestors. 02 Concise explanation“Event bubbling is the process in which an event starts at its target and propagates upward through its ancestors. A click on a button can therefore trigger handlers on the button, its containing elements, and the document.”
03 Memory formulaTarget → parents = bubbling04 Real-world usesevent delegation shared parent handlers interactive component trees Question 10 10. What is event delegation? Quick recall Concept Glance Card 30 sec
01 Easy tipEvent delegation attaches one event listener to a parent rather than separate listeners to every child. document.querySelector('.list').addEventListener('click', (event) => {
const button = event.target.closest('.delete-button');
if (button) button.closest('li').remove();
}); 02 Concise explanation“Event delegation attaches one event listener to a parent rather than separate listeners to every child. Because events bubble, the parent can inspect event.target or use closest() to determine which child initiated the event.”
03 Memory formulaOne parent listener + bubbling = delegation04 Real-world usesdynamic lists tables menus reducing event listeners Question 11 11. What is a Promise? Quick recall Concept Glance Card 30 sec
01 Easy tipA Promise represents a result that will arrive in the future. async function loadUser() {
try {
const response = await fetch('/api/user');
return await response.json();
} catch (error) {
console.error(error);
}
} 02 Concise explanation“A Promise represents the eventual success or failure of an asynchronous operation. It starts pending, then becomes fulfilled or rejected. I normally handle Promises with async/await and try/catch.”
03 Memory formulaPending → fulfilled or rejected04 Real-world usesAPI requests database operations file operations other delayed work Question 12 12. What are async and await? Quick recall Concept Glance Card 30 sec
01 Easy tipasync and await provide readable syntax for Promise-based code. async function loadUsers() {
const response = await fetch('/api/users');
if (!response.ok) throw new Error('Request failed');
return response.json();
} 02 Concise explanation“async and await provide readable syntax for Promise-based code. An async function always returns a Promise, and await pauses only that async function until the supplied value settles; it does not block the JavaScript thread.”
03 Memory formulaasync returns a Promise; await pauses that function04 Real-world usesAPI calls database operations readable asynchronous code Question 13 13. What is the difference between null and undefined? Quick recall Concept Glance Card 30 sec
01 Easy tipundefined usually indicates that a value is missing or has not been assigned. let result; // undefined
let selectedUser = null; // intentionally empty 02 Concise explanation“undefined usually indicates that a value is missing or has not been assigned. null is normally assigned deliberately to represent the intentional absence of a value.”
03 Memory formulaundefined = missing; null = intentionally empty04 Real-world usesoptional values resetting state API contracts Question 14 14. What is the DOM? Quick recall Concept Glance Card 30 sec
01 Easy tipThe Document Object Model is a programming interface that represents an HTML document as a tree of objects. const heading = document.querySelector('h1');
heading.textContent = 'Welcome'; 02 Concise explanation“The Document Object Model is a programming interface that represents an HTML document as a tree of objects. JavaScript uses DOM APIs to read or change content, attributes, styles, and structure.”
03 Memory formulaHTML parsed into an object tree = DOM04 Real-world useschanging page content handling events creating elements form interaction Question 15 15. What is scope in JavaScript? Quick recall Concept Glance Card 30 sec
01 Easy tipScope determines where a binding can be accessed. if (true) {
const message = 'Hello';
}
console.log(message); // ReferenceError 02 Concise explanation“Scope determines where a binding can be accessed. JavaScript has global, module, function, and block scopes; let and const are block-scoped, while var is function-scoped.”
03 Memory formulaWhere code is written determines what it can access04 Real-world usesencapsulation preventing name conflicts controlling variable lifetime Question 16 16. What is a callback function? Quick recall Concept Glance Card 30 sec
01 Easy tipA callback is a function passed to another function so it can be invoked later or as part of an operation. function greet(name, callback) {
callback('Hello, ' + name);
}
greet('Alex', console.log); 02 Concise explanation“A callback is a function passed to another function so it can be invoked later or as part of an operation. Callbacks are common in event handlers, timers, array methods, and older asynchronous APIs.”
03 Memory formulaPass a function now; another function calls it04 Real-world usesevents array methods timers asynchronous APIs Question 17 17. What is callback hell? Quick recall Concept Glance Card 30 sec
01 Easy tipCallback hell describes deeply nested callbacks whose control flow and error handling are difficult to understand, test, and maintain. 02 Concise explanation“Callback hell describes deeply nested callbacks whose control flow and error handling are difficult to understand, test, and maintain. It commonly appears in multi-step asynchronous workflows.”
03 Memory formulaToo many nested callbacks = hard-to-follow control flow04 Real-world usesrecognising async code smells refactoring to Promises extracting named functions Question 18 18. What is JSON, and how is it used? Quick recall Concept Glance Card 30 sec
01 Easy tipJSON, or JavaScript Object Notation, is a text format for exchanging structured data. const user = JSON.parse('{"name":"Alex"}');
const text = JSON.stringify(user); 02 Concise explanation“JSON, or JavaScript Object Notation, is a text format for exchanging structured data. It resembles JavaScript object syntax but is language-independent and follows stricter rules.”
03 Memory formulaparse: text → value; stringify: value → text04 Real-world usesAPIs configuration storage data exchange Question 19 19. What is the difference between synchronous and asynchronous JavaScript? Quick recall Concept Glance Card 30 sec
01 Easy tipSynchronous code runs one operation at a time on the call stack, so a long task can block the main thread. 02 Concise explanation“Synchronous code runs one operation at a time on the call stack, so a long task can block the main thread. Asynchronous runtime APIs can start work such as a timer or network request and deliver its result later without synchronously waiting.”
03 Memory formulaSync waits; async schedules the result for later04 Real-world usesnetwork requests timers responsive interfaces file operations Question 20 20. What is a higher-order function? Quick recall Concept Glance Card 30 sec
01 Easy tipA higher-order function accepts another function, returns a function, or does both. const prices = [10, 20, 30];
const discounted = prices.map((price) => price * 0.9); 02 Concise explanation“A higher-order function accepts another function, returns a function, or does both. Common examples include map, filter, and reduce.”
03 Memory formulaA function that receives or returns a function04 Real-world usesmap and filter reusable behaviour middleware function composition Question 21 21. What is currying? Quick recall Concept Glance Card 30 sec
01 Easy tipCurrying transforms a function that accepts multiple arguments into a sequence of functions that each accept one argument. const multiply = (first) => (second) => first * second;
const double = multiply(2);
double(5); // 10 02 Concise explanation“Currying transforms a function that accepts multiple arguments into a sequence of functions that each accept one argument. It can create specialised functions and support function composition.”
03 Memory formulaf(a, b) becomes f(a)(b)04 Real-world usesspecialised functions partial configuration functional composition Question 22 22. What is debouncing? Quick recall Concept Glance Card 30 sec
01 Easy tipKeep resetting the timer; run only after the calls stop. function debounce(callback, delay) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
callback.apply(this, args);
}, delay);
};
} 02 Concise explanation“Debouncing delays a function until a specified amount of time has passed without another call. It is useful for search fields because it avoids making an API request after every keystroke.”
03 Memory formulaKeep resetting the timer; run after activity stops04 Real-world usessearch inputs autocomplete validation window resizing draft saving Question 23 23. What is throttling? Quick recall Concept Glance Card 30 sec
01 Easy tipThrottling limits a function to no more than one execution in a specified interval. 02 Concise explanation“Throttling limits a function to no more than one execution in a specified interval. It is useful for continuous, high-frequency events such as scrolling, pointer movement, or progress tracking.”
03 Memory formulaRun at most once per time interval04 Real-world usesscroll handlers pointer movement progress updates rate limiting Question 24 24. What is the difference between map() and forEach()? Quick recall Concept Glance Card 30 sec
01 Easy tipBoth methods iterate over an array, but map() returns a new array containing transformed values while forEach() returns undefined. const numbers = [1, 2, 3];
const doubled = numbers.map((number) => number * 2);
numbers.forEach((number) => console.log(number)); 02 Concise explanation“Both methods iterate over an array, but map() returns a new array containing transformed values while forEach() returns undefined.”
03 Memory formulamap transforms and returns; forEach performs side effects04 Real-world usesdata transformation rendering lists logging external updates Question 25 25. What is the difference between a library and a framework? Quick recall Concept Glance Card 30 sec
01 Easy tipLibraries and frameworks both provide reusable tools, but differ mainly in control and scope. 02 Concise explanation“Libraries and frameworks both provide reusable tools, but differ mainly in control and scope. With a library, application code generally chooses when to call it; a framework usually supplies more structure and calls application code at defined extension points.”
03 Memory formulaYou call a library; a framework calls your code04 Real-world usestechnology selection application architecture team conventions Question 26 What is a JavaScript engine? Quick recall Concept Glance Card 30 sec
01 Easy tipA JavaScript engine reads, compiles, and executes JavaScript. 02 Concise explanation“A JavaScript engine reads, compiles, and executes JavaScript. V8 powers Chrome and Node.js, SpiderMonkey powers Firefox, and JavaScriptCore powers Safari. Modern Microsoft Edge also uses V8; Chakra powered the older EdgeHTML-based browser.”
03 Memory formulaJavaScript source → engine → executable behaviour04 Real-world usesbrowser execution Node.js performance optimisation runtime debugging Question 27 What is the difference between client-side and server-side JavaScript? Quick recall Concept Glance Card 30 sec
01 Easy tipClient-side JavaScript runs in the browser and handles interface updates, validation, animation, and user interaction. 02 Concise explanation“Client-side JavaScript runs in the browser and handles interface updates, validation, animation, and user interaction. Server-side JavaScript runs in an environment such as Node.js and can process requests, access databases, authenticate users, and produce responses.”
03 Memory formulaBrowser = interface; server = data and requests04 Real-world usesfrontend interaction APIs authentication database access Question 28 What happens if a variable is assigned without a declaration? Quick recall Concept Glance Card 30 sec
01 Easy tipIn non-strict script code, assigning to an undeclared identifier may create a property on the global object. 'use strict';
count = 10; // ReferenceError 02 Concise explanation“In non-strict script code, assigning to an undeclared identifier may create a property on the global object. This is not equivalent to a proper variable declaration and can cause accidental shared state.”
03 Memory formulaUndeclared + strict mode = ReferenceError04 Real-world usespreventing accidental globals safe modules debugging scope errors Question 29 What is a variable? Quick recall Concept Glance Card 30 sec
01 Easy tipA variable is a named binding that refers to a JavaScript value. const name = 'Alex';
let score = 10; 02 Concise explanation“A variable is a named binding that refers to a JavaScript value. That value may be a primitive, object, array, function, or any other value.”
03 Memory formulaName → binding → value04 Real-world usesstoring state naming values passing data through a program Question 30 What are primitive data types? Quick recall Concept Glance Card 30 sec
01 Easy tipSimple, immutable values copied by value. let word = 'cat';
word[0] = 'b';
console.log(word); // 'cat'
let first = 10;
let second = first;
second = 20;
console.log(first); // 10 02 Concise explanation“Primitive data types are simple, immutable values such as strings, numbers, and booleans. JavaScript has seven primitive types, and they are copied and compared by value.”
03 Memory formula7 simple values + immutable + copied by value04 Real-world usesvalue comparisons safe copying type checks understanding immutability Question 31 What is the difference between primitive values and objects? Quick recall Concept Glance Card 30 sec
01 Easy tipPrimitive values are immutable and compared by value. 10 === 10; // true
{} === {}; // false
const user = { name: 'Alex' };
user.name = 'Sam'; // Object mutated 02 Concise explanation“Primitive values are immutable and compared by value. Objects are mutable by default and are normally compared by identity, meaning two separate objects with identical properties are not strictly equal.”
03 Memory formulaPrimitives compare by value; objects compare by identity04 Real-world usesequality checks immutable updates state management copying data Question 32 What are arrays, functions, and objects? Quick recall Concept Glance Card 30 sec
01 Easy tipArray = ordered values; function = reusable behaviour; object = related properties. const animals = ['dog', 'cat'];
function add(a, b) {
return a + b;
}
const person = {
name: 'Alex',
introduce() {
return 'Hello, I am ' + this.name;
},
}; 02 Concise explanation“An array stores an ordered collection, a function contains reusable behaviour, and an object groups related properties and methods.”
03 Memory formulaArray orders + function acts + object groups04 Real-world usescollections reusable logic structured records application models Question 33 What does the typeof operator do? Quick recall Concept Glance Card 30 sec
01 Easy tiptypeof returns a string describing the broad type of a value. typeof 42; // 'number'
typeof []; // 'object'
typeof null; // 'object'
typeof function () {}; // 'function'
Array.isArray([]); // true 02 Concise explanation“typeof returns a string describing the broad type of a value. It reports arrays and null as "object", while functions receive the special result "function".”
03 Memory formulatypeof gives a broad type label, not a complete type check04 Real-world usesruntime guards debugging values checking functions and undefined Question 34 What is type coercion? Quick recall Concept Glance Card 30 sec
01 Easy tipType coercion is conversion from one type to another. '5' + 2; // '52'
'5' - 2; // 3
Number('5'); // 5
Boolean(0); // false 02 Concise explanation“Type coercion is conversion from one type to another. JavaScript performs implicit coercion in some operations, while explicit conversion uses functions such as Number, String, and Boolean.”
03 Memory formulaImplicit = JavaScript converts; explicit = you convert04 Real-world usesform values comparisons arithmetic avoiding conversion bugs Question 35 What are unary, binary, and ternary operators? Quick recall Concept Glance Card 30 sec
01 Easy tipA unary operator works with one operand, such as typeof value or !isActive. const status = age >= 18 ? 'Adult' : 'Minor'; 02 Concise explanation“A unary operator works with one operand, such as typeof value or !isActive. A binary operator works with two operands, such as a + b. The conditional operator uses three expressions: a condition, a result when truthy, and a result when falsy.”
03 Memory formulaUnary = 1 operand; binary = 2; ternary = 3 expressions04 Real-world usesnegation arithmetic comparisons short conditional values Question 36 What is operator precedence? Quick recall Concept Glance Card 30 sec
01 Easy tipOperator precedence determines which operations are evaluated first. 2 + 3 * 4; // 14
(2 + 3) * 4; // 20 02 Concise explanation“Operator precedence determines which operations are evaluated first. Multiplication, for example, has higher precedence than addition. Parentheses override the normal order and often make intent clearer during review.”
03 Memory formulaPrecedence chooses order; parentheses make order explicit04 Real-world usesarithmetic compound conditions readable expressions Question 37 What is short-circuit evaluation? Quick recall Concept Glance Card 30 sec
01 Easy tipLogical operators stop evaluating once their result is known. isLoggedIn && showDashboard();
const name = providedName || 'Guest';
const count = suppliedCount ?? 0; 02 Concise explanation“Logical operators stop evaluating once their result is known. && stops at the first falsy operand, while || stops at the first truthy operand. Both return an operand rather than necessarily returning a boolean.”
03 Memory formula&& stops on falsy; || stops on truthy; ?? stops on non-nullish04 Real-world usesfallback values guarded calls optional configuration Question 38 What is the difference between spread and rest syntax? Quick recall Concept Glance Card 30 sec
01 Easy tipBoth use ..., but spread expands an iterable or object into another context, while rest collects remaining values into one array or object. const combined = [...first, 3, 4];
function total(...numbers) {
return numbers.reduce((sum, number) => sum + number, 0);
} 02 Concise explanation“Both use ..., but spread expands an iterable or object into another context, while rest collects remaining values into one array or object. The surrounding syntax determines which behaviour applies.”
03 Memory formulaSpread expands; rest collects04 Real-world usesimmutable copies merging arrays variadic functions destructuring Question 39 How do you add and remove array elements? Quick recall Concept Glance Card 30 sec
01 Easy tippush() and pop() operate at the end of an array; unshift() and shift() operate at the beginning. 02 Concise explanation“push() and pop() operate at the end of an array; unshift() and shift() operate at the beginning. All four mutate the original array. push() and unshift() return the new length, while pop() and shift() return the removed value.”
03 Memory formulapush/pop = end; unshift/shift = beginning04 Real-world usesstacks queues dynamic collections Question 40 What is the difference between find() and filter()? Quick recall Concept Glance Card 30 sec
01 Easy tipfind() stops at the first match and returns that element or undefined. const numbers = [2, 4, 6, 8];
numbers.find((number) => number > 4); // 6
numbers.filter((number) => number > 4); // [6, 8] 02 Concise explanation“find() stops at the first match and returns that element or undefined. filter() checks the collection and returns a new array containing every match.”
03 Memory formulafind = first match; filter = all matches04 Real-world usesrecord lookup search results permission filtering Question 41 What is the difference between slice() and splice()? Quick recall Concept Glance Card 30 sec
01 Easy tipslice(start, end) returns a shallow copy of a range without changing the original; its end index is excluded. const values = ['a', 'b', 'c'];
values.slice(1, 3); // ['b', 'c']
values.splice(1, 1, 'x'); // values is ['a', 'x', 'c'] 02 Concise explanation“slice(start, end) returns a shallow copy of a range without changing the original; its end index is excluded. splice(start, deleteCount, ...items) removes, replaces, or inserts elements and mutates the original array.”
03 Memory formulaslice copies; splice changes04 Real-world usesextracting ranges inserting items removing items immutable updates Question 42 How do sorting and reversing affect arrays? Quick recall Concept Glance Card 30 sec
01 Easy tipsort() and reverse() mutate the original array. const numbers = [10, 2, 30];
numbers.toSorted((first, second) => first - second); // [2, 10, 30] 02 Concise explanation“sort() and reverse() mutate the original array. Default sorting compares string representations, so numeric sorting needs a comparison function. Modern toSorted() and toReversed() return new arrays instead.”
03 Memory formulasort/reverse mutate; toSorted/toReversed copy04 Real-world usesrankings ordered displays state-safe transformations Question 43 What are array destructuring and array-like objects? Quick recall Concept Glance Card 30 sec
01 Easy tipArray destructuring assigns iterable values to bindings and can skip items, provide defaults, or swap variables. const [primary, secondary] = ['red', 'blue'];
[first, second] = [second, first];
const values = Array.from(arrayLike); 02 Concise explanation“Array destructuring assigns iterable values to bindings and can skip items, provide defaults, or swap variables. An array-like object instead has indexed properties and a length, but may not provide array methods.”
03 Memory formulaDestructure unpacks; Array.from converts array-like values04 Real-world usesswapping values function results DOM collections arguments conversion Question 44 What is a loop? Quick recall Concept Glance Card 30 sec
01 Easy tipRepeat code until a condition ends or a collection is finished. for (let index = 0; index < 3; index += 1) {
console.log(index);
} 02 Concise explanation“A loop repeatedly executes a block of code while a condition remains true or until a collection has been processed.”
03 Memory formulaStart + condition + update = controlled repetition04 Real-world usesprocessing collections retries searching values repeated calculations Question 45 Which loop should you choose? Quick recall Concept Glance Card 30 sec
01 Easy tipUse a classic for loop when you need index control or know the iteration pattern. 02 Concise explanation“Use a classic for loop when you need index control or know the iteration pattern. Use while when repetition depends on a condition, and do...while when the body must run at least once.”
03 Memory formulaIndex = for; condition = while; values = for...of04 Real-world usescollection processing retry loops index-based algorithms Question 46 What is the difference between break and continue? Quick recall Concept Glance Card 30 sec
01 Easy tipbreak exits the nearest loop or switch entirely. for (const number of numbers) {
if (number < 0) continue;
if (number === 100) break;
console.log(number);
} 02 Concise explanation“break exits the nearest loop or switch entirely. continue skips the remainder of the current loop iteration and proceeds with the next one.”
03 Memory formulabreak exits; continue skips04 Real-world usesearly loop termination ignoring invalid items search algorithms Question 47 What is the difference between for...of and for...in? Quick recall Concept Glance Card 30 sec
01 Easy tipfor...of iterates values from an iterable such as an array, string, Set, or Map. 02 Concise explanation“for...of iterates values from an iterable such as an array, string, Set, or Map. for...in iterates enumerable property keys, including inherited enumerable properties.”
03 Memory formulafor...of = values; for...in = property keys04 Real-world usesiterating arrays Sets and Maps inspecting object properties Question 48 How does forEach() compare with for...of? Quick recall Concept Glance Card 30 sec
01 Easy tipforEach() is concise for synchronous side effects on every array item, but it cannot be stopped with break or continue. for (const item of items) {
if (shouldStop(item)) break;
await processItem(item);
} 02 Concise explanation“forEach() is concise for synchronous side effects on every array item, but it cannot be stopped with break or continue. It also does not await an async callback as a sequence.”
03 Memory formulaforEach = callback; for...of = control and await04 Real-world usessimple side effects breakable loops sequential async work Question 49 What function forms are available? Quick recall Concept Glance Card 30 sec
01 Easy tipCommon forms include function declarations, function expressions, arrow functions, methods, async functions, generator functions, and constructor functions. 02 Concise explanation“Common forms include function declarations, function expressions, arrow functions, methods, async functions, generator functions, and constructor functions. These are related function values with different syntax or behaviour, not wholly separate data types.”
03 Memory formulaChoose function syntax for its behaviour, not just its length04 Real-world useshoisted declarations lexical this async workflows generators Question 50 What is the difference between named and anonymous functions? Quick recall Concept Glance Card 30 sec
01 Easy tipNamed has an identifier; anonymous does not. function add(a, b) {
return a + b;
}
const subtract = function (a, b) {
return a - b;
}; 02 Concise explanation“A named function has an explicit identifier. An anonymous function does not and is often used as a callback or assigned to a variable.”
03 Memory formulaNamed = explicit identity; anonymous = inline value04 Real-world usesclear stack traces recursion short callbacks function expressions Question 51 What is the purpose of anonymous functions? Quick recall Concept Glance Card 30 sec
01 Easy tipA short function used once, usually as a callback. const numbers = [1, 2, 3, 4];
const doubled = numbers.map((number) => number * 2);
button.addEventListener('click', () => {
console.log('Button clicked');
}); 02 Concise explanation“Anonymous functions are useful for short, one-time behaviour, especially callbacks passed to array methods, event listeners, timers, and Promises. A named function is usually better when the logic is complex or reusable.”
03 Memory formulaShort + one-time + inline callback = anonymous function04 Real-world usesarray methods event listeners Promise handlers timers Question 52 What is a function expression? Quick recall Concept Glance Card 30 sec
01 Easy tipCreate a function as a value and assign it. const add = function (a, b) {
return a + b;
};
add(2, 3); // 5 02 Concise explanation“A function expression defines a function as a value, usually by assigning it to a variable. Unlike a function declaration, it cannot be called through that variable before initialization.”
03 Memory formulaVariable = function value04 Real-world usescallbacks conditional functions closures module APIs Question 53 What is the difference between parameters, arguments, and defaults? Quick recall Concept Glance Card 30 sec
01 Easy tipParameters are the names in a function definition; arguments are the values supplied at a call site. function greet(name = 'Guest') {
return 'Hello, ' + name;
}
greet(); // 'Hello, Guest'
greet(undefined); // 'Hello, Guest'
greet(null); // 'Hello, null' 02 Concise explanation“Parameters are the names in a function definition; arguments are the values supplied at a call site. Default parameters apply when an argument is omitted or explicitly undefined, but not when it is null.”
03 Memory formulaParameters define inputs; arguments supply values; defaults fill undefined04 Real-world usesfunction APIs optional configuration clear contracts Question 54 What are first-class functions? Quick recall Concept Glance Card 30 sec
01 Easy tipJavaScript treats functions as first-class values. 02 Concise explanation“JavaScript treats functions as first-class values. They can be assigned to variables, stored in objects and arrays, passed as arguments, and returned from other functions.”
03 Memory formulaFunctions can be stored, passed, and returned like any value04 Real-world usescallbacks higher-order functions middleware function factories Question 55 Why use callback functions? Quick recall Concept Glance Card 30 sec
01 Easy tipKeep the process; swap the behaviour. function calculate(a, b, operation) {
return operation(a, b);
}
calculate(10, 5, (a, b) => a + b);
calculate(10, 5, (a, b) => a * b); 02 Concise explanation“Callbacks make code flexible by allowing different behaviour to be passed into the same reusable function.”
03 Memory formulaReusable process + supplied behaviour = callback04 Real-world usescustom operations event-driven code array methods asynchronous results Question 56 What is a pure function? Quick recall Concept Glance Card 30 sec
01 Easy tipSame input, same output, no outside changes. function add(a, b) {
return a + b;
}
add(2, 3); // Always 5 02 Concise explanation“A pure function always produces the same result for the same arguments and has no side effects, such as changing external state.”
03 Memory formulaPure = same input, same output, no outside change04 Real-world usespredictable code testing Redux reducers calculations Question 57 What is function composition? Quick recall Concept Glance Card 30 sec
01 Easy tipSmall functions joined together. const double = (number) => number * 2;
const addOne = (number) => number + 1;
const calculate = (number) => addOne(double(number));
calculate(5); // 11 02 Concise explanation“Function composition combines small functions so the result of one becomes the input of another.”
03 Memory formulaOutput of function A → input of function B04 Real-world usesreusable processing steps data pipelines functional programming Question 58 What is functional programming? Quick recall Concept Glance Card 30 sec
01 Easy tipFunctions, pure logic, and no direct mutation. const numbers = [1, 2, 3];
const doubled = numbers.map((number) => number * 2);
// numbers remains [1, 2, 3] 02 Concise explanation“Functional programming builds applications from small, reusable functions. It favours pure functions and immutable data instead of modifying existing state.”
03 Memory formulaPure functions + immutable data + composition04 Real-world usesReact Redux predictable data transformations testable business logic Question 59 What do call(), apply(), and bind() do? Quick recall Concept Glance Card 30 sec
01 Easy tipThese methods control this for regular functions. 02 Concise explanation“These methods control this for regular functions. call() invokes immediately with separate arguments, apply() invokes immediately with arguments in an array-like value, and bind() returns a new function to invoke later.”
03 Memory formulacall now; apply array now; bind later04 Real-world usessetting this method borrowing callback binding partial arguments Question 60 What are template literals? Quick recall Concept Glance Card 30 sec
01 Easy tipTemplate literals use backticks, support multiline text, and interpolate expressions with ${...}. const message = `Hello, ${name}`;
const lines = `First line
Second line`; 02 Concise explanation“Template literals use backticks, support multiline text, and interpolate expressions with ${...}. They are still strings unless used with a tag function.”
03 Memory formulaBackticks + ${expression} = interpolated string04 Real-world usesdynamic messages multiline text HTML fragments tagged templates Question 61 What does string immutability mean? Quick recall Concept Glance Card 30 sec
01 Easy tipA string value cannot have individual characters changed in place. let word = 'cat';
word[0] = 'b';
console.log(word); // 'cat'
word = `b${word.slice(1)}`; // 'bat' 02 Concise explanation“A string value cannot have individual characters changed in place. Methods such as toUpperCase, slice, replace, split, and trim return new values rather than modifying the original string.”
03 Memory formulaString methods return a new string; they do not edit the old one04 Real-world usessafe text transformation formatting search and replacement Question 62 What is the difference between HTML and the DOM? Quick recall Concept Glance Card 30 sec
01 Easy tipHTML is source markup describing a document. 02 Concise explanation“HTML is source markup describing a document. The DOM is the browser's in-memory object representation created from that markup.”
03 Memory formulaHTML = source; DOM = live in-memory tree04 Real-world usesbrowser rendering dynamic updates debugging generated markup Question 63 How do DOM selector methods differ? Quick recall Concept Glance Card 30 sec
01 Easy tipgetElementById() returns one element or null. 02 Concise explanation“getElementById() returns one element or null. getElementsByClassName() and getElementsByTagName() return live HTMLCollections that update as the DOM changes. querySelector() returns the first CSS-selector match, while querySelectorAll() returns a static NodeList.”
03 Memory formulaquerySelector = first; querySelectorAll = static list; getElementsBy* = live list04 Real-world usesfinding controls updating groups event registration Question 64 What is the difference between innerHTML and textContent? Quick recall Concept Glance Card 30 sec
01 Easy tipinnerHTML parses and writes HTML markup, whereas textContent inserts plain text. element.textContent = userSuppliedValue;
element.innerHTML = '<strong>Trusted markup</strong>'; 02 Concise explanation“innerHTML parses and writes HTML markup, whereas textContent inserts plain text. Use textContent for ordinary text and untrusted values.”
03 Memory formulainnerHTML parses markup; textContent stays plain and safe04 Real-world usessafe user text trusted markup preventing XSS Question 65 How do you create, clone, and remove DOM nodes? Quick recall Concept Glance Card 30 sec
01 Easy tipcreateElement() creates an element, while createTextNode() creates text. 02 Concise explanation“createElement() creates an element, while createTextNode() creates text. cloneNode(true) copies a node and its descendants, but listeners registered with addEventListener() are not copied.”
03 Memory formulacreateElement creates; cloneNode copies; remove deletes04 Real-world usesdynamic lists templates conditional interface elements Question 66 What do try, catch, finally, and throw do? Quick recall Concept Glance Card 30 sec
01 Easy tiptry contains work that may fail, catch handles a thrown exception, and finally runs afterwards whether the operation succeeded or failed. try {
await loadData();
} catch (error) {
console.error(error);
} finally {
hideLoadingIndicator();
} 02 Concise explanation“try contains work that may fail, catch handles a thrown exception, and finally runs afterwards whether the operation succeeded or failed. throw creates or propagates an exception.”
03 Memory formulatry work; catch failure; finally cleanup; throw signal04 Real-world usesAPI errors resource cleanup validation error boundaries Question 67 What is error propagation? Quick recall Concept Glance Card 30 sec
01 Easy tipAn unhandled thrown error moves up the call stack until a caller catches it. 02 Concise explanation“An unhandled thrown error moves up the call stack until a caller catches it. Promise rejections similarly travel through a Promise chain until handled by .catch() or by try...catch around an awaited operation.”
03 Memory formulaUnhandled errors travel upward until a boundary catches them04 Real-world usescentral error handling Promise chains adding context recovery boundaries Question 68 What are common error types and good handling practices? Quick recall Concept Glance Card 30 sec
01 Easy tipBuilt-in classes include Error, SyntaxError, ReferenceError, TypeError, RangeError, URIError, and AggregateError. 02 Concise explanation“Built-in classes include Error, SyntaxError, ReferenceError, TypeError, RangeError, URIError, and AggregateError. A logical error is different: execution succeeds but produces the wrong result.”
03 Memory formulaCatch where you can recover; otherwise preserve and propagate04 Real-world usesinput validation logging user-safe messages operational monitoring Question 69 What are classes and objects? Quick recall Concept Glance Card 30 sec
01 Easy tipClass = template; object = instance. class Car {
constructor(model, year) {
this.model = model;
this.year = year;
}
describe() {
return this.model + ' was made in ' + this.year;
}
}
const car = new Car('BMW X5', 2025); 02 Concise explanation“A class is a template containing shared properties and methods. An object created from that class is an instance. JavaScript classes use the language’s prototype system underneath.”
03 Memory formulaClass template → new instance object04 Real-world usesdomain models shared methods encapsulation inheritance Question 70 How do object access and iteration work? Quick recall Concept Glance Card 30 sec
01 Easy tipDot notation is concise for known identifier-like keys, while bracket notation supports dynamic keys and names such as "first-name". user.name;
user[propertyName];
for (const [key, value] of Object.entries(user)) {
console.log(key, value);
} 02 Concise explanation“Dot notation is concise for known identifier-like keys, while bracket notation supports dynamic keys and names such as "first-name". Use Object.keys, Object.values, or Object.entries to iterate own enumerable properties.”
03 Memory formulaDot = known key; brackets = dynamic key; entries = key-value pairs04 Real-world usesrecords configuration dynamic properties object transformations Question 71 What is the difference between a shallow and deep copy? Quick recall Concept Glance Card 30 sec
01 Easy tipSpread and Object.assign() create shallow copies: the outer object is new, but nested object references are shared. const shallow = { ...original };
const deep = structuredClone(original); 02 Concise explanation“Spread and Object.assign() create shallow copies: the outer object is new, but nested object references are shared. structuredClone() creates independent copies of many supported nested values and handles circular references.”
03 Memory formulaShallow copies the outside; deep copies supported nested values04 Real-world usesstate updates editing drafts isolating nested data Question 72 What is a Set? Quick recall Concept Glance Card 30 sec
01 Easy tipA Set stores unique values and provides add, has, delete, and size. const unique = [...new Set([1, 1, 2, 3])];
// [1, 2, 3] 02 Concise explanation“A Set stores unique values and provides add, has, delete, and size. It is iterable and preserves insertion order.”
03 Memory formulaSet = unique values04 Real-world usesremoving duplicates membership checks tracking selected IDs Question 73 What is the difference between a Map and an object? Quick recall Concept Glance Card 30 sec
01 Easy tipA Map accepts keys of any type, is directly iterable, preserves insertion order, and provides get, set, has, delete, and size. 02 Concise explanation“A Map accepts keys of any type, is directly iterable, preserves insertion order, and provides get, set, has, delete, and size. It communicates frequently changing key-value collection semantics clearly.”
03 Memory formulaMap = any key and collection API; object = named record04 Real-world usescaches metadata keyed by objects structured JSON data Question 74 Explain the JavaScript event loop. Quick recall Concept Glance Card 30 sec
01 Easy tipStack runs code; runtime waits; queues hold callbacks; event loop schedules them. console.log('Start');
setTimeout(() => console.log('Timer'), 0);
Promise.resolve().then(() => console.log('Promise'));
console.log('End');
// Start, End, Promise, Timer 02 Concise explanation“JavaScript runs one piece of code at a time on the call stack. The runtime handles asynchronous waiting, completed callbacks enter queues, and the event loop schedules them when the stack is empty. Promise microtasks run before the next normal task.”
03 Memory formulaCall stack → runtime → queues → event loop04 Real-world usespredicting execution order timers Promises avoiding blocking code Question 75 How do you implement and use a Promise? Quick recall Concept Glance Card 30 sec
01 Easy tipCreate with resolve/reject; consume with then/catch or await. function wait(delay) {
return new Promise((resolve) => {
setTimeout(resolve, delay);
});
}
async function run() {
try {
await wait(1000);
console.log('One second completed');
} catch (error) {
console.error(error);
}
} 02 Concise explanation“Create a Promise with an executor that receives resolve and reject. Consume it with then and catch, or with async and await. Do not wrap an API that already returns a Promise.”
03 Memory formulaCreate: resolve/reject → consume: then/catch or await04 Real-world useswrapping callback APIs timers API requests asynchronous workflows Question 76 How do you handle errors with async and await? Quick recall Concept Glance Card 30 sec
01 Easy tipTry the request; check response.ok; catch errors; finally clean up. async function loadUsers() {
try {
const response = await fetch('/api/users');
if (!response.ok) {
throw new Error('Request failed: ' + response.status);
}
return await response.json();
} catch (error) {
console.error('Unable to load users:', error);
throw error;
} finally {
hideLoadingIndicator();
}
} 02 Concise explanation“I handle async and await errors with try and catch. With fetch, I also check response.ok because HTTP error responses do not reject the Promise automatically. I use finally for cleanup and only catch errors where I can handle them meaningfully.”
03 Memory formulatry → check response.ok → catch → finally04 Real-world usesAPI requests user error messages logging loading-state cleanup Question 77 What is event handling? Quick recall Concept Glance Card 30 sec
01 Easy tipConnect an event to the callback that should respond. const button = document.getElementById('my-button');
function handleClick() {
console.log('Button clicked');
}
button.addEventListener('click', handleClick); 02 Concise explanation“Event handling means responding to browser actions. addEventListener connects an event such as click to a callback function.”
03 Memory formulaElement + event + callback = event handler04 Real-world usesclicks keyboard input form submission pointer interaction Question 78 What is an event object? Quick recall Concept Glance Card 30 sec
01 Easy tipThe browser passes an event object to a listener with information about what occurred. 02 Concise explanation“The browser passes an event object to a listener with information about what occurred. Important members include type, target, currentTarget, preventDefault(), and stopPropagation().”
03 Memory formulaEvent object = what happened + where + control methods04 Real-world usesclick handling keyboard input forms pointer interactions Question 79 What are capturing, target, and bubbling phases? Quick recall Concept Glance Card 30 sec
01 Easy tipDuring capturing, an event travels from outer ancestors toward its target. 02 Concise explanation“During capturing, an event travels from outer ancestors toward its target. It then reaches the target phase and, for bubbling events, travels back through ancestors. Most listeners use the bubbling phase by default.”
03 Memory formulaCapture goes down; target happens; bubble goes up04 Real-world usesdelegation global handlers debugging event order Question 80 What is the difference between preventDefault() and stopPropagation()? Quick recall Concept Glance Card 30 sec
01 Easy tippreventDefault() cancels a cancelable browser action, such as link navigation or form submission. 02 Concise explanation“preventDefault() cancels a cancelable browser action, such as link navigation or form submission. stopPropagation() prevents the event from continuing through the event path. One does not imply the other.”
03 Memory formulapreventDefault stops browser action; stopPropagation stops event travel04 Real-world usescustom form submission controlled navigation isolated event handling Question 81 What is the difference between target and currentTarget? Quick recall Concept Glance Card 30 sec
01 Easy tipevent.target is where the event originated. 02 Concise explanation“event.target is where the event originated. event.currentTarget is the element whose listener is currently running, so they often differ during delegation.”
03 Memory formulatarget started it; currentTarget owns the running listener04 Real-world usesevent delegation nested controls shared parent listeners Question 82 How do you remove an event listener? Quick recall Concept Glance Card 30 sec
01 Easy tipCall removeEventListener() with the same event type, function reference, and capture setting used during registration. const controller = new AbortController();
button.addEventListener('click', handleClick, {
signal: controller.signal,
});
controller.abort(); 02 Concise explanation“Call removeEventListener() with the same event type, function reference, and capture setting used during registration. Two identical-looking anonymous functions are different objects and cannot remove one another.”
03 Memory formulaSame type + same function + same capture setting = removable listener04 Real-world usescomponent cleanup preventing memory leaks temporary interactions AbortController Question 83 What is event capturing? Quick recall Concept Glance Card 30 sec
01 Easy tipCapturing travels down; bubbling travels up. form.addEventListener(
'click',
() => console.log('Form capture'),
{ capture: true }
); 02 Concise explanation“During capturing, an event travels from outer ancestors toward its target. Listeners use bubbling by default, but capturing can be enabled with the capture option.”
03 Memory formulaWindow → document → parent → target04 Real-world usesintercepting events early global interaction handling debugging event order Question 84 How do you stop event propagation? Quick recall Concept Glance Card 30 sec
01 Easy tipstopPropagation stops the event journey. button.addEventListener('click', (event) => {
event.stopPropagation();
console.log('Only the button handler');
}); 02 Concise explanation“stopPropagation prevents an event from continuing through the capturing or bubbling path. stopImmediatePropagation also prevents later handlers on the same element from running.”
03 Memory formulastopPropagation = stop travel; immediate = stop travel + same-element handlers04 Real-world usesisolated controls nested interactions modal boundaries Question 85 When should you use debounce? Quick recall Concept Glance Card 30 sec
01 Easy tipUse it for frequent events where only the final result matters. const search = debounce((query) => {
fetch('/api/search?q=' + encodeURIComponent(query));
}, 300);
input.addEventListener('input', (event) => {
search(event.target.value);
}); 02 Concise explanation“I use debounce when an expensive operation can be triggered repeatedly but should run only after the user pauses, such as waiting before sending a search request.”
03 Memory formulaMany rapid events → one final action04 Real-world usessearch suggestions form validation window resizing auto-saving Question 86 What is the difference between debounce and throttle? Quick recall Concept Glance Card 30 sec
01 Easy tipDebounce waits; throttle limits. 02 Concise explanation“Debounce is best when only the final event matters. Throttle is best when continuous updates are required but their frequency must be limited.”
03 Memory formulaDebounce = after activity; throttle = during activity at intervals04 Real-world usessearch input scroll tracking resize handling pointer updates Question 87 In what order will synchronous logs and a zero-delay timer run? Quick recall Concept Glance Card 30 sec
01 Easy tipSynchronous code first; timer callback later. console.log('First');
setTimeout(() => {
console.log('Second');
}, 0);
console.log('Third');
// First, Third, Second 02 Concise explanation“Synchronous logs run on the call stack first. A zero-delay timer callback is queued as a task and cannot run until the current stack is empty.”
03 Memory formulaFirst → Third → Second04 Real-world usespredicting timer order debugging scheduling understanding zero-delay timers Question 88 Where do Promise callbacks fit in the event loop? Quick recall Concept Glance Card 30 sec
01 Easy tipSynchronous code, then microtasks, then tasks. console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
// A, D, C, B 02 Concise explanation“Synchronous code executes first. Promise callbacks use the microtask queue, which is drained before task-queue callbacks such as setTimeout.”
03 Memory formulaSync → microtasks → tasks04 Real-world usesPromise ordering timer coordination avoiding scheduling races Question 89 What is prototypal inheritance? Quick recall Concept Glance Card 30 sec
01 Easy tipMissing property? JavaScript asks the prototype. const animal = {
speak() {
return 'Sound';
},
};
const dog = Object.create(animal);
dog.speak(); // 'Sound' 02 Concise explanation“JavaScript objects delegate property lookup through their prototype. If a property is not found directly, JavaScript searches along the prototype chain.”
03 Memory formulaObject → prototype → Object.prototype → null04 Real-world usesshared methods Object.create class internals property lookup Question 90 How does prototypal inheritance differ from class inheritance? Quick recall Concept Glance Card 30 sec
01 Easy tipJavaScript classes are built on prototypes. class Animal {
speak() {
return 'Sound';
}
}
class Dog extends Animal {}
new Dog().speak(); 02 Concise explanation“Traditional class inheritance describes classes inheriting from classes. JavaScript fundamentally uses objects and prototype chains; class and extends provide class-style syntax over that model.”
03 Memory formulaclass syntax → prototype chain underneath04 Real-world usesunderstanding extends method sharing debugging inheritance Question 91 Should you modify built-in prototypes? Quick recall Concept Glance Card 30 sec
01 Easy tipDo not change objects you do not own. function toTitleCase(value) {
return value.replace(/w/g, (letter) => letter.toUpperCase());
} 02 Concise explanation“I avoid modifying built-in prototypes because it creates global behaviour, can conflict with libraries or future language features, and makes code harder to understand. Standards-compliant guarded polyfills are the main exception.”
03 Memory formulaGlobal mutation = collision risk04 Real-world usesAPI design library safety standards-compliant polyfills Question 92 What does an async function return? Quick recall Concept Glance Card 30 sec
01 Easy tipAn async function always returns a Promise. async function getNumber() {
return 42;
}
getNumber().then(console.log); // 42
async function fail() {
throw new Error('Failed');
} 02 Concise explanation“An async function always returns a Promise. A normal returned value becomes a fulfilled Promise, while a thrown error becomes a rejected Promise.”
03 Memory formulareturn value → fulfilled Promise; throw → rejected Promise04 Real-world usesasynchronous APIs Promise chaining error propagation Question 93 What is the relationship between async/await and Promises? Quick recall Concept Glance Card 30 sec
01 Easy tipasync/await is cleaner Promise syntax. async function loadUser() {
const response = await fetch('/api/user');
return response.json();
} 02 Concise explanation“async and await are syntax built on Promises. await pauses only that async function until the Promise settles; it does not block JavaScript’s main thread.”
03 Memory formulaPromise behaviour + synchronous-looking syntax04 Real-world usesreadable workflows sequential async steps try/catch error handling Question 94 When are pure functions useful? Quick recall Concept Glance Card 30 sec
01 Easy tipPredictable means testable. function applyDiscount(price, percentage) {
return price * (1 - percentage / 100);
}
applyDiscount(100, 20); // 80 02 Concise explanation“Pure functions are useful for calculations, state transformations, selectors, and reducers because their output depends only on their input, making them easy to test and reason about.”
03 Memory formulaPredictable → testable → reusable04 Real-world usescalculations reducers selectors business rules Question 95 What is polyfilling? Quick recall Concept Glance Card 30 sec
01 Easy tipAdd an API that an older browser is missing. if (!Array.prototype.includes) {
// Install a standards-compatible implementation.
} 02 Concise explanation“A polyfill provides a JavaScript implementation of a modern runtime API when the target browser does not support it. Unsupported syntax requires transpilation instead.”
03 Memory formulaMissing API = polyfill; unsupported syntax = transpile04 Real-world useslegacy browser support Promise support feature detection Question 96 What are the drawbacks of polyfills? Quick recall Concept Glance Card 30 sec
01 Easy tipMore compatibility means more code. 02 Concise explanation“Polyfills improve compatibility but increase bundle size, parsing, execution cost, and maintenance. I target supported browsers and load only required polyfills.”
03 Memory formulaCompatibility + code weight + maintenance04 Real-world usesbrowser support planning bundle budgeting selective loading Question 97 Where are closures used? Quick recall Concept Glance Card 30 sec
01 Easy tipPrivate state and remembered configuration. function createMultiplier(multiplier) {
return (number) => number * multiplier;
}
const double = createMultiplier(2);
double(5); // 10 02 Concise explanation“Closures are used for private state, function factories, event handlers, callbacks, memoisation, module patterns, and React hooks because a function can remember its creation environment.”
03 Memory formulaFunction + remembered configuration04 Real-world usesprivate state function factories memoisation React hooks Question 98 What are the drawbacks of closures? Quick recall Concept Glance Card 30 sec
01 Easy tipRemembered references can remain in memory. function createHandler(largeData) {
return () => console.log(largeData.length);
} 02 Concise explanation“A closure can retain referenced values while the function remains reachable. Capturing large objects, DOM nodes, or listeners unnecessarily can increase memory use or contribute to leaks.”
03 Memory formulaLong-lived closure + large reference = memory risk04 Real-world usesmemory reviews listener cleanup timer cleanup profiling Question 99 What is the difference between cookies, localStorage, and sessionStorage? Quick recall Concept Glance Card 30 sec
01 Easy tipCookies travel; local stays; session disappears. localStorage.setItem('theme', 'dark');
sessionStorage.setItem('checkoutStep', '2'); 02 Concise explanation“Cookies are small and sent with matching HTTP requests. localStorage persists until cleared, while sessionStorage normally lasts only for the current tab. I avoid sensitive tokens in Web Storage because JavaScript and XSS can access them.”
03 Memory formulaCookies = requests; local = persistent; session = tab lifetime04 Real-world usessecure sessions user preferences temporary form progress feature settings Question 100 How would you optimise a new front-end application? Quick recall Concept Glance Card 30 sec
01 Easy tipShip less, load later, cache closer, measure continuously. 02 Concise explanation“I set a performance budget, measure bottlenecks, remove unused code, split and lazy-load non-critical features, optimise assets, use caching and a CDN, then monitor Core Web Vitals in production.”
03 Memory formulaMeasure -> reduce -> defer -> cache -> monitor04 Real-world usesperformance budgets Core Web Vitals bundle analysis real-user monitoring Question 101 Why bundle and compress JavaScript? Quick recall Concept Glance Card 30 sec
01 Easy tipBundling organises delivery; compression reduces transfer size. 02 Concise explanation“A production build prepares modules for efficient delivery. Minification reduces the source representation, while Brotli or Gzip encodes complete files more efficiently during network transfer.”
03 Memory formulaBuild modules -> minify code -> compress transfer04 Real-world usesproduction delivery smaller transfers module optimisation HTTP caching Question 102 What are minification and uglification? Quick recall Concept Glance Card 30 sec
01 Easy tipMinification shrinks code; mangling shortens names. function calculateTotal(price, tax) {
return price + tax;
}
// May become: function a(b,c){return b+c} 02 Concise explanation“Minification removes unnecessary source characters and may perform safe transformations. A minifier can also mangle local names to reduce size. Source maps are needed to debug transformed production output.”
03 Memory formulaRemove noise + shorten names + preserve behaviour04 Real-world usessmaller bundles faster parsing production builds source-map debugging Question 103 What are source maps? Quick recall Concept Glance Card 30 sec
01 Easy tipMap a production error back to the original source. bundle.min.js:1:2478
->
src/checkout/payment.ts:42 02 Concise explanation“A source map connects transformed, bundled, and minified production code to the original source so developer tools and monitoring systems can report meaningful files and locations.”
03 Memory formulaBundle location -> original file and line04 Real-world usesproduction debugging error monitoring TypeScript minified builds Question 104 What is code splitting? Quick recall Concept Glance Card 30 sec
01 Easy tipLoad only what the current page needs. const loadAdminPanel = () => import('./AdminPanel'); 02 Concise explanation“Code splitting divides a large bundle into smaller chunks loaded on demand, reducing initial download, parsing, and execution cost. Routes and large optional components are common split points.”
03 Memory formulaLarge bundle -> useful on-demand chunks04 Real-world usesroute loading admin features large editors optional components Question 105 What is tree shaking? Quick recall Concept Glance Card 30 sec
01 Easy tipShake out unused exports. 02 Concise explanation“Tree shaking removes exports that the application does not use. It works most reliably with static ES modules because bundlers can analyse import and export relationships at build time.”
03 Memory formulaStatic modules + unused exports -> removed code04 Real-world usessmaller bundles library consumption production builds dead-code removal Question 106 How would you optimise large images? Quick recall Concept Glance Card 30 sec
01 Easy tipRight size, right format, right time. 02 Concise explanation“I serve correctly sized responsive images, compress them, use AVIF or WebP where appropriate, deliver them through a CDN, reserve dimensions, and lazy-load below-the-fold images without delaying the LCP image.”
03 Memory formulaSize + format + responsive source + loading priority04 Real-world usesfaster LCP smaller transfers responsive layouts reduced layout shift Question 107 Why specify image width and height? Quick recall Concept Glance Card 30 sec
01 Easy tipReserve space before the image arrives. <img src="product.webp" width="800" height="600" alt="Product" /> 02 Concise explanation“Width and height let the browser calculate an image aspect ratio and reserve space before loading completes, reducing Cumulative Layout Shift.”
03 Memory formulaKnown aspect ratio -> reserved space -> lower CLS04 Real-world usespreventing layout shift stable galleries product cards article media Question 108 How would you manage code quality at scale? Quick recall Concept Glance Card 30 sec
01 Easy tipStandards, automation, tests, reviews, and monitoring. 02 Concise explanation“I automate TypeScript, linting, formatting, tests, accessibility, dependency checks, and builds in CI, supported by review standards, performance budgets, architecture boundaries, and production monitoring.”
03 Memory formulaLint -> type-check -> test -> build -> scan -> E2E -> deploy04 Real-world usesCI quality gates pull requests architecture enforcement production reliability Question 109 Which testing layers would you use? Quick recall Concept Glance Card 30 sec
01 Easy tipMany focused tests; fewer complete journey tests. 02 Concise explanation“I use unit tests for isolated logic, integration tests for collaborating components, and a smaller stable end-to-end suite for critical user journeys.”
03 Memory formulaUnit -> integration -> E2E; fast many -> realistic few04 Real-world usesbusiness logic component workflows API integration critical journeys Question 110 What is an XSS attack? Quick recall Concept Glance Card 30 sec
01 Easy tipUntrusted content executes as trusted JavaScript. 02 Concise explanation“Cross-site scripting occurs when attacker-controlled content is inserted into a page and executes in another user’s browser, allowing theft of accessible data, unwanted actions, or page modification.”
03 Memory formulaUntrusted input + unsafe output context = script execution04 Real-world usesthreat modelling security reviews safe rendering incident analysis Question 111 How do you prevent XSS? Quick recall Concept Glance Card 30 sec
01 Easy tipEscape output, sanitise HTML, restrict scripts. element.textContent = userComment;
// Sanitise before using an HTML-rendering API. 02 Concise explanation“I treat external content as untrusted, rely on context-aware escaping, sanitise HTML only when necessary, avoid unsafe DOM APIs, and enforce a strong Content Security Policy.”
03 Memory formulaSafe output + sanitisation + CSP + secure cookies04 Real-world usesuser content rich text DOM updates security headers Question 112 What is a CDN and how does it work? Quick recall Concept Glance Card 30 sec
01 Easy tipCache content closer to the user. 02 Concise explanation“A CDN is a geographically distributed network of edge servers. A nearby edge serves cached content when available and retrieves it from the origin on a cache miss.”
03 Memory formulaUser -> nearby edge -> cache hit or origin04 Real-world usesJavaScript and CSS images and fonts video cacheable HTML and APIs Question 113 What are the advantages of a CDN? Quick recall Concept Glance Card 30 sec
01 Easy tipFaster, scalable, and resilient. 02 Concise explanation“A CDN lowers latency, reduces origin load, absorbs traffic spikes, improves global availability, and can provide compression, caching, TLS, and DDoS protection.”
03 Memory formulaCloser delivery + shared cache + protected origin04 Real-world usesglobal applications traffic spikes static assets origin protection Question 114 What are the disadvantages of a CDN? Quick recall Concept Glance Card 30 sec
01 Easy tipMore speed, but more infrastructure and cache complexity. <script src="/assets/app.a84f21.js"></script> 02 Concise explanation“A CDN adds cost, configuration, cache invalidation, stale-content risk, vendor dependency, and another layer to debug. Incorrect caching can expose private responses.”
03 Memory formulaSpeed benefit + cache complexity + provider dependency04 Real-world usesrisk assessment cache design incident debugging vendor evaluation Question 115 Which CDN providers could you use? Quick recall Concept Glance Card 30 sec
01 Easy tipChoose for the existing platform and requirements. 02 Concise explanation“Options include CloudFront, Cloudflare, Azure Front Door, Google Cloud CDN, Fastly, Akamai, and Vercel’s edge network. I choose based on platform fit, cost, coverage, controls, and required edge features.”
03 Memory formulaPlatform fit + geography + cost + features04 Real-world usesprovider selection cloud integration global delivery edge security Question 116 What are micro-frontends? Quick recall Concept Glance Card 30 sec
01 Easy tipSplit one frontend into independently owned applications. 02 Concise explanation“Micro-frontends divide a large frontend into independently developed and deployable business areas. A shell usually composes them and provides shared navigation, authentication, and design-system integration.”
03 Memory formulaApplication shell + independently owned domain frontends04 Real-world usesmultiple product teams independent releases legacy migration domain ownership Question 117 When would you use micro-frontends? Quick recall Concept Glance Card 30 sec
01 Easy tipUse them for team independence, not simply application size. 02 Concise explanation“I consider micro-frontends when several autonomous teams need independent ownership and deployment and the current frontend has become an organisational bottleneck. I avoid them for a small team.”
03 Memory formulaIndependent teams + domain boundaries + release autonomy04 Real-world usesautonomous teams separate release schedules clear domains legacy decomposition Question 118 What are the benefits of micro-frontends? Quick recall Concept Glance Card 30 sec
01 Easy tipIndependent teams and independent releases. 02 Concise explanation“Micro-frontends can provide separate ownership, independent deployments, parallel development, domain-focused codebases, incremental migration, and carefully designed fault isolation.”
03 Memory formulaOwnership + release autonomy + gradual migration04 Real-world usesteam scaling release independence legacy replacement domain isolation Question 119 What are the disadvantages of micro-frontends? Quick recall Concept Glance Card 30 sec
01 Easy tipOrganisational freedom creates technical complexity. 02 Concise explanation“Micro-frontends add duplicate dependencies, larger downloads, shared-state and routing complexity, consistency challenges, coordinated testing, observability work, and more deployment infrastructure.”
03 Memory formulaTeam autonomy traded for distributed frontend complexity04 Real-world usesarchitecture trade-offs platform planning dependency governance operational readiness Question 120 What criteria would justify moving from a frontend monolith? Quick recall Concept Glance Card 30 sec
01 Easy tipIs the architecture blocking the organisation? 02 Concise explanation“I first improve module boundaries, ownership, and CI in the monolith. I move toward micro-frontends only when several teams need measurable deployment independence across clear domains and can operate the extra infrastructure.”
03 Memory formulaProve bottleneck -> improve monolith -> justify independent deployment04 Real-world usesarchitecture decisions team topology migration planning cost-benefit analysis Question 121 What is the temporal dead zone? Quick recall Concept Glance Card 30 sec
01 Easy tipThe binding exists, but cannot be used yet. console.log(value); // ReferenceError
const value = 42; 02 Concise explanation“The temporal dead zone is the period from entering a block until a let, const, or class declaration is initialized. Accessing the binding during that period throws a ReferenceError.”
03 Memory formulaBlock starts -> TDZ -> declaration initializes binding04 Real-world usesscope reasoning debugging ReferenceError safe declarations Question 122 What does strict mode change? Quick recall Concept Glance Card 30 sec
01 Easy tipStricter rules turn silent mistakes into errors. 'use strict';
undeclaredValue = 1; // ReferenceError 02 Concise explanation“Strict mode prevents accidental globals, changes some this behavior, rejects duplicate parameters and unsafe syntax, and makes certain silent failures throw errors. ES modules and class bodies are strict automatically.”
03 Memory formulaStrict mode = safer semantics + earlier errors04 Real-world usespreventing accidental globals migration debugging module behavior Question 123 Is JavaScript pass-by-value or pass-by-reference? Quick recall Concept Glance Card 30 sec
01 Easy tipEverything is passed by value, including object references. function update(user) {
user.name = 'Ada';
user = { name: 'Grace' };
}
const user = { name: 'Lin' };
update(user);
console.log(user.name); // Ada 02 Concise explanation“JavaScript passes arguments by value. For objects, the copied value is a reference to the same object, so property mutation is shared, but reassigning the parameter does not replace the caller’s variable.”
03 Memory formulaCopy value; object value happens to be a reference04 Real-world usesfunction API design mutation debugging state management Question 124 How does JavaScript garbage collection work? Quick recall Concept Glance Card 30 sec
01 Easy tipUnreachable values can be reclaimed. 02 Concise explanation“JavaScript engines trace values reachable from roots such as the global object and active call stacks. Values that are no longer reachable become eligible for garbage collection; collection timing is controlled by the engine.”
03 Memory formulaRoots -> reachable graph; unreachable -> collectible04 Real-world usesmemory profiling lifecycle design performance debugging Question 125 What commonly causes memory leaks in browser applications? Quick recall Concept Glance Card 30 sec
01 Easy tipLeaks come from references that outlive their useful work. 02 Concise explanation“Common causes include unremoved listeners, uncleared timers, retained DOM nodes, growing caches, subscriptions, global references, and closures that keep large objects reachable.”
03 Memory formulaFinished work + retained reference = leak risk04 Real-world usesSPA cleanup performance audits heap snapshot analysis Question 126 When should you use WeakMap or WeakSet? Quick recall Concept Glance Card 30 sec
01 Easy tipAttach data without keeping object keys alive. 02 Concise explanation“WeakMap and WeakSet hold object keys weakly, so they do not prevent those objects from being garbage-collected. They suit private metadata, memoization, and object tracking when enumeration is unnecessary.”
03 Memory formulaObject key + weak ownership = collectible metadata04 Real-world usesprivate metadata object memoization visited-object tracking Question 127 What is a Symbol and when is it useful? Quick recall Concept Glance Card 30 sec
01 Easy tipA Symbol is a unique primitive property key. const id = Symbol('id');
const record = { [id]: 123 };
record[id]; // 123 02 Concise explanation“A Symbol is a primitive whose values are unique. Symbols are useful for collision-resistant object keys and for language protocols such as Symbol.iterator, although they are not a security mechanism.”
03 Memory formulaSymbol = unique identity + property key04 Real-world usesprotocol hooks metadata keys avoiding property collisions Question 128 How do the Promise combinators differ? Quick recall Concept Glance Card 30 sec
01 Easy tipAll, allSettled, race, and any answer different coordination questions. 02 Concise explanation“Promise.all requires every input and fails fast; allSettled reports every outcome; race settles with the first outcome; any fulfills with the first success and rejects only if every input rejects.”
03 Memory formulaAll = all success; settled = all results; race = first; any = first success04 Real-world usesparallel requests fallback services timeouts batch reporting Question 129 Why does fetch not reject for HTTP errors? Quick recall Concept Glance Card 30 sec
01 Easy tipFetch rejects for request failure, not an error status. const response = await fetch('/api/user');
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const user = await response.json(); 02 Concise explanation“Fetch resolves when an HTTP response arrives, even for statuses such as 404 or 500. Code must inspect response.ok or response.status and throw or return an application-specific error when required.”
03 Memory formulaNetwork failure rejects; HTTP failure needs a status check04 Real-world usesAPI clients error boundaries retry policies Question 130 How do you cancel asynchronous browser work? Quick recall Concept Glance Card 30 sec
01 Easy tipPass an AbortSignal to APIs that support cancellation. const controller = new AbortController();
const request = fetch('/api/search', { signal: controller.signal });
controller.abort();
await request; // Rejects with an abort-related error 02 Concise explanation“Create an AbortController, pass its signal to supported APIs such as fetch, and call abort when the work is obsolete or times out. Handle the resulting abort separately from genuine failures.”
03 Memory formulaController -> signal -> abort -> cleanup04 Real-world usesrequest cancellation component cleanup timeouts race prevention Question 131 How do ES modules differ from CommonJS? Quick recall Concept Glance Card 30 sec
01 Easy tipES modules are statically structured; CommonJS loads with require. 02 Concise explanation“ES modules use import and export with statically analyzable, live bindings and asynchronous browser loading. CommonJS uses require and module.exports with runtime loading and is historically associated with Node.js.”
03 Memory formulaESM = static import/export; CommonJS = runtime require/exports04 Real-world usesNode.js packages bundling tree shaking migration planning Question 132 What is the difference between optional chaining and nullish coalescing? Quick recall Concept Glance Card 30 sec
01 Easy tipOne safely reads; the other supplies a default. const city = user.address?.city ?? 'Unknown';
const retries = config.retries ?? 3; // Keeps 0 02 Concise explanation“Optional chaining stops property access or a call when the left side is null or undefined. Nullish coalescing returns its right side only when the left side is null or undefined, preserving valid falsy values such as zero and an empty string.”
03 Memory formula?. = safe access; ?? = nullish default04 Real-world usesAPI data access configuration defaults optional callbacks Question 133 When should you use a Web Worker? Quick recall Concept Glance Card 30 sec
01 Easy tipMove CPU-heavy work off the browser main thread. 02 Concise explanation“A Web Worker runs JavaScript in a separate thread and helps keep the interface responsive during CPU-intensive work. Workers communicate through messages and cannot directly access the DOM.”
03 Memory formulaHeavy computation -> worker -> messages -> responsive UI04 Real-world usesdata processing parsing image computation background calculations Question 134 What is CORS and how does it work? Quick recall Concept Glance Card 30 sec
01 Easy tipThe server tells the browser which cross-origin reads are allowed. 02 Concise explanation“CORS is an HTTP-header protocol through which a server permits selected browser origins to read its responses. Some requests require a preflight OPTIONS request before the browser sends the actual request.”
03 Memory formulaOrigin policy + server headers + optional preflight04 Real-world usesAPI integration credentialed requests security debugging