JavaScript Interview Questions and Answers for Freshers

JavaScript Interview Questions and Answers – whosgeek

Kabir, a BCA graduate from Indore, is in his first frontend interview with a small product company in Pune. The first question is an easy one: "What is the difference between slice and splice?" He has read the answer many times, so he says it confidently: "slice does not change the array, splice does." The interviewer nods and asks a follow-up: "So what does splice return?" Kabir guesses "the updated array". The real answer is the array of removed items. Then he is shown four lines with setTimeout and a Promise and asked for the output, and he gets the order wrong. He knew every definition. So what was the interviewer actually checking, and how do you answer in a way that survives the follow-up?

This guide is a complete set of JavaScript interview questions for freshers and junior developers, from "What is JavaScript?" to the event loop, memory leaks and polyfills. For each question you get a short answer you can say out loud, a small tested example, and the follow-up trap that interviewers like to add. If you want a topic-by-topic revision sheet instead, read the JavaScript Part 2 revision guide. If you want predict-the-output puzzles, read the intermediate and advanced output questions. Every code output below was checked on Node.js v24.

How to Answer a JavaScript Interview Question

Most interviewers are not testing whether you memorised a definition. They want to know whether you understand the idea well enough to use it, and the quickest way to find out is a follow-up question. A strong answer has three parts, and it takes less than a minute to say:

PartWhat you sayExample for slice vs splice
1. One-line definitionWhat it is, in plain words"slice copies part of an array; splice changes the array in place."
2. Tiny exampleA one-line case, ideally with the output"[1,2,3].slice(0, 2) gives [1, 2] and the original is untouched."
3. The gotcha or the useThe detail that shows real understanding"splice returns the removed items, not the new array."

Part 3 is what separates candidates. It is also exactly what Kabir was missing. Throughout this guide, the blue boxes give you a ready answer in this three-part shape, and the text around them explains why it is true.

Part 1: JavaScript Basics

What Is JavaScript?

JavaScript is the programming language that makes web pages interactive. When you click "Add to Cart" and the cart count changes without the page reloading, when a form tells you the PIN code is invalid while you are still typing, or when a notification slides in, JavaScript is doing that work. It started in 1995 as a small language for the Netscape browser, and the history of JavaScript explains how it grew from there.

Today it runs far beyond the browser: on servers with Node.js, in mobile apps (React Native), desktop apps (Electron, which powers VS Code), games, serverless functions and cloud services. So the old interview answer "JavaScript is a client-side language" is now only half true. Say "it started on the client side and now runs on both sides".

Interviewers often expect you to list its main features. Here they are with one line of meaning each:

  • Dynamically typed: you don't declare types, and a variable can hold any type.
  • Object-based: data and behaviour are grouped into objects, and almost everything (arrays, functions, dates) is an object underneath.
  • Cross-platform: it runs on Windows, Linux, macOS, Android and iOS, anywhere there is a browser or Node.js.
  • Single-threaded: it runs one piece of your code at a time.
  • Synchronous by default: it runs line by line, but it can handle slow work asynchronously using the event loop.

Interview answer: "JavaScript is a dynamically typed, single-threaded language that makes web pages interactive. It began in browsers and now also runs on servers through Node.js. Even though it runs one task at a time, it handles slow work like network calls asynchronously using the event loop."

Why Is JavaScript Called a Scripting Language?

A scripting language is one that runs inside an existing program and automates work there, instead of building a full application from scratch. Classic pairs are the browser and JavaScript, Photoshop and its scripts, and Excel and VBA macros. The host program provides the window, the files or the spreadsheet, and the script tells it what to do.

That label is mostly historical. Modern JavaScript is a full programming language that runs entire backends, so in an interview it is fine to say: "It is called a scripting language because it was designed to run inside the browser, but today it is a general-purpose language."

What Is Dynamic Typing?

In a dynamically typed language, the type belongs to the value, not to the variable. You never write "this variable is a number", and the same variable can hold a number now and a string later:

let value = 10;
console.log(typeof value); // number

value = "Hello";
console.log(typeof value); // string

value = [1, 2, 3];
console.log(typeof value, Array.isArray(value)); // object true

value = { name: "JS" };
console.log(typeof value); // object

Notice that typeof says "object" for an array. That is a common follow-up, and the correct way to check for an array is Array.isArray(). In a statically typed language like Java, or in TypeScript, the variable has a fixed type and the compiler stops you from putting a string into a number variable.

Dynamic typing makes small programs quick to write. The cost is that type mistakes show up only when the code runs, for example a price read from a form arriving as the string "100" instead of the number 100. Chapter 4 on operators and type conversion covers those bugs in detail.

Is JavaScript Single-Threaded and Synchronous?

Yes. Think of a kirana store with one person at the billing counter. Customers stand in a queue, and the shopkeeper finishes one bill before starting the next. JavaScript runs your code the same way, on a single thread, one statement after another:

console.log("First");
console.log("Second");
console.log("Third");
// First
// Second
// Third

Each line waits for the previous one to finish. That raises the obvious follow-up: "If it does only one thing at a time, how does a web page stay responsive while it downloads data?" The answer is that slow work like timers and network requests is handed to the browser or to Node.js, and the result comes back later through the event loop. We cover that properly in Part 5.

What Is the Difference Between == and ===?

This is probably the most common JavaScript interview question of all. The double equals == converts both sides to the same type before comparing. The triple equals === compares without converting, so the value and the type must both match.

console.log(5 == "5");            // true  (the string is converted to a number)
console.log(5 === "5");           // false (number vs string)
console.log(null == undefined);   // true
console.log(null === undefined);  // false
console.log(0 == false);          // true
console.log("" == 0);             // true
console.log([] == false);         // true  (yes, really)

The last three lines are why most teams simply ban ==. The conversion rules are long, and they produce results that look wrong when you read the code later.

Interview answer: "=== checks value and type with no conversion. == converts types first, so 5 == "5" is true. I use === everywhere because loose equality gives surprises like "" == 0 being true."

What Is the Difference Between var, let and const?

Before ES6 (2015), var was the only way to declare a variable. It caused bugs in larger programs, so ES6 added let and const. The three differ in scope, in whether you can declare the same name twice, and in whether you can reassign them.

Featurevarletconst
ScopeFunctionBlock { }Block { }
HoistedYes, set to undefinedYes, but in the TDZYes, but in the TDZ
ReassignYesYesNo
Redeclare in same scopeYesNo (SyntaxError)No (SyntaxError)

The scope difference is the one that causes real bugs. A var declared inside an if block leaks out of that block, while let stays inside it:

if (true) {
  var town = "Delhi";
}
console.log(town); // Delhi  (var ignores the block)

if (true) {
  let city = "Delhi";
}
console.log(city); // ReferenceError: city is not defined

Redeclaring is the next difference. With var, a second declaration silently replaces the first, which is how two parts of a big file can overwrite each other's variable. With let, the file does not even start:

var customer = "Asha";
var customer = "Ravi";
console.log(customer); // Ravi (no warning at all)

// In a separate file:
let city = "Pune";
let city = "Jaipur";
// SyntaxError: Identifier 'city' has already been declared

The classic interview version uses a loop with setTimeout. With var there is only one i for the whole loop, so every callback sees its final value. With let, each loop round gets its own copy:

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

for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log("let", j), 0);
}
// let 0, let 1, let 2

Does const Make an Object Unchangeable?

No, and this is a favourite trick question. const stops you from pointing the variable at a different value. It does not stop you from changing what is inside an object or array:

const PI = 3.14;
PI = 10; // TypeError: Assignment to constant variable.

const user = { name: "Asha" };
user.name = "Ravi";  // allowed: the object itself is changed
console.log(user);   // { name: 'Ravi' }

The variable user still points to the same object, so const is satisfied. If you need an object that cannot be changed, use Object.freeze(), covered in Part 2.

What Is Hoisting?

Before JavaScript runs your code, it reads through it once and sets up memory for every declaration. Think of a class teacher whose attendance register already has every student's name before the first period starts. Because of this setup step, some names can be used before the line where they are declared. That behaviour is called hoisting.

console.log(city); // undefined (no error)
var city = "Pune";
console.log(city); // Pune

sayHello();        // Hello
function sayHello() {
  console.log("Hello");
}

A var is set up with the value undefined, and its real value arrives only when its line runs. A function declaration is set up with its full body, so you can call it from anywhere in its scope. People often say the declaration is "moved to the top". Nothing actually moves in your file; it is just that memory is prepared before execution starts.

The follow-up is usually a function expression. It is stored in a var, so at the time of the early call the variable holds undefined, and calling undefined fails:

greetLater(); // TypeError: greetLater is not a function
var greetLater = function () {
  console.log("Hi");
};

For the full picture, including classes and the order in which names are set up, see Chapter 10 on hoisting.

What Is the Temporal Dead Zone (TDZ)?

let and const are hoisted too, but they are not given any starting value. From the start of their block until their declaration line runs, the variable exists but cannot be touched. That period is the Temporal Dead Zone, and any access during it throws an error:

console.log(age); // ReferenceError: Cannot access 'age' before initialization
let age = 25;

Read that error message carefully. It says "before initialization", not "is not defined". JavaScript already knows about age; it simply refuses access until the line runs. Even typeof, which is normally safe on unknown names, throws inside the TDZ:

console.log(typeof notDeclaredAnywhere); // undefined (safe)

console.log(typeof price); // ReferenceError: Cannot access 'price' before initialization
let price = 100;

Interview answer: "All declarations are hoisted. var starts as undefined, function declarations start with their full body, and let and const stay uninitialised in the temporal dead zone, so using them early throws a ReferenceError."

What Is Scope?

Scope decides where a variable can be used. Think of access cards in an office: a few people can enter every room, while most can only enter their own department. JavaScript has three main levels:

  • Global scope: declared outside every function and block, visible everywhere.
  • Function scope: declared inside a function, visible only inside that function.
  • Block scope: declared with let or const inside { }, visible only inside that block.
let company = "TechCorp"; // global

function test() {
  let message = "Hello";  // function scope
  console.log(company);   // TechCorp (inner code can read outer variables)
}
test();
console.log(message); // ReferenceError: message is not defined

{
  let city = "Delhi";     // block scope
}
console.log(city);    // ReferenceError: city is not defined

Lookups only go outward. Code inside a function can read the global company, but code outside cannot read the function's message. That one-way search from inner to outer scope is called the scope chain, and it is the base for closures in Part 3.

Part 2: Objects, Prototypes and this

What Are the Different Ways to Create Objects?

There are five ways you should be able to name and show. All five are below in one runnable snippet:

// 1. Object constructor
const a = new Object();
a.city = "Pune";
console.log(a); // { city: 'Pune' }

// 2. Object.create() with a chosen prototype
const base = { greet() { return "Namaste, " + this.name; } };
const b = Object.create(base);
b.name = "Asha";
console.log(b.greet()); // Namaste, Asha

// 3. Object literal (the everyday choice)
const c = { name: "Ravi", age: 30 };

// 4. Constructor function (the pre-ES6 way)
function Person(name) {
  this.name = name;
  this.age = 21;
}
console.log(new Person("Meera")); // Person { name: 'Meera', age: 21 }

// 5. ES6 class
class Student {
  constructor(name) {
    this.name = name;
  }
}
console.log(new Student("Kabir")); // Student { name: 'Kabir' }

In real code you will use the object literal most of the time, and a class when you need many objects of the same shape with shared methods. A class is mostly a cleaner way to write a constructor function; underneath, both use prototypes.

One detail is worth knowing about Object.create(null). It creates an object with no prototype at all, so it does not even have toString. That makes it a clean dictionary with no inherited keys, but calling a normal object method on it fails:

const bare = Object.create(null);
console.log(typeof bare.toString); // undefined
bare.toString(); // TypeError: bare.toString is not a function

What Is the Prototype Chain?

Imagine a small shop. If a customer asks for something the shop doesn't have, the owner asks the warehouse. If the warehouse doesn't have it either, the warehouse asks the main supplier. The search stops when the item is found or when there is nobody left to ask.

JavaScript objects work the same way. Every object has a hidden link to another object, its prototype. When you read a property that the object doesn't have, JavaScript looks in the prototype, then in that object's prototype, and so on until it reaches null. This chain of links is the prototype chain.

const supplier = { rice: "₹60/kg" };
const warehouse = Object.create(supplier);
warehouse.dal = "₹120/kg";
const shop = Object.create(warehouse);
shop.sugar = "₹45/kg";

console.log(shop.sugar, shop.dal, shop.rice, shop.oil);
// ₹45/kg ₹120/kg ₹60/kg undefined

The shop owns only sugar. It finds dal one step up and rice two steps up. Nobody has oil, so the result is undefined rather than an error. This is also why a plain object can call methods it never defined:

const person = { name: "Asha" };
console.log(person.toString());                                 // [object Object]
console.log(person.hasOwnProperty("toString"));                 // false
console.log(Object.getPrototypeOf(person) === Object.prototype); // true
console.log(Object.getPrototypeOf(Object.prototype));           // null (end of the chain)

Interview answer: "Every object has a link to a prototype object. When a property isn't found on the object, JavaScript looks up that chain of prototypes until it finds it or reaches null. That's how a plain object gets toString, and it's how classes share methods."

What Is the this Keyword?

Think of the word "I". When Asha says "I am a developer", "I" means Asha; when Ravi says the same sentence, it means Ravi. this works similarly: inside a normal function, its value depends on how the function is called, not where it was written.

const person = {
  name: "Asha",
  greet() {
    console.log(this.name);
  },
};

person.greet();   // Asha  (called as person.greet, so this === person)

const looseGreet = person.greet;
looseGreet();     // undefined in Node.js (called on its own, so this is not person)

The second call is the bug interviewers are looking for. The same function lost its object just because it was called differently. This is exactly what happens when you pass a method as a callback, such as setTimeout(person.greet, 1000).

At the top level, this depends on the environment. In a classic browser script it is the window object. In a Node.js CommonJS file it is module.exports, an empty object {}. In an ES module it is undefined. The full guide to this, call, apply and bind walks through all the rules.

What Are Arrow Functions, and How Are They Different?

Arrow functions, added in ES6, are a shorter way to write functions. These three do the same job:

function add(a, b) {
  return a + b;
}
const add2 = (a, b) => {
  return a + b;
};
const add3 = (a, b) => a + b; // one expression: return is automatic

console.log(add(2, 3), add2(2, 3), add3(2, 3)); // 5 5 5

The difference that matters in interviews is not the syntax. Arrow functions do not get their own this; they use the this of the code around them. That makes them perfect for callbacks inside methods, and wrong as object methods:

const user = {
  name: "Asha",
  greet: () => {
    console.log(this.name);
  },
};
user.greet(); // undefined in Node.js

The arrow function takes this from the file's top level, not from user. In Node.js that is an empty object, so you get undefined. In a browser you usually see an empty line instead, because window.name exists and is an empty string. Either way, the name is not printed.

Arrow functions also have no arguments object and cannot be used with new:

const Make = () => {};
new Make(); // TypeError: Make is not a constructor

What Is the Difference Between call, apply and bind?

All three let you choose what this should be when a function runs. Say you have one greet function and want to use it with different objects:

const employee = { name: "Asha" };

function greet(message, punctuation) {
  console.log(message + " " + this.name + punctuation);
}

greet.call(employee, "Hello", "!");     // Hello Asha!   (runs now, arguments one by one)
greet.apply(employee, ["Hello", "!"]);  // Hello Asha!   (runs now, arguments as an array)

const greetAsha = greet.bind(employee); // does NOT run; returns a new function
greetAsha("Namaste", ".");              // Namaste Asha.
MethodRuns immediately?How arguments are passedTypical use
call()YesOne by oneBorrowing a method once
apply()YesAs one arrayWhen the arguments are already in an array
bind()No, returns a new functionOne by one (can be preset)Callbacks and event handlers that must keep their this

An easy way to remember the first two: apply takes an array. A classic use of apply was Math.max.apply(null, [3, 9, 2]), which returns 9. Today the spread syntax Math.max(...[3, 9, 2]) does the same job and reads better.

What Is Function Borrowing?

Function borrowing means using one object's method on a different object, without copying the method. You do it with call, apply or bind:

const person1 = {
  name: "Asha",
  display() {
    console.log(this.name);
  },
};
const person2 = { name: "Ravi" };

person1.display.call(person2); // Ravi

The method belongs to person1, but for this one call this is person2. You will see the same trick in older code that borrows array methods for array-like objects, for example Array.prototype.slice.call(arguments).

What Is the Difference Between a Shallow Copy and a Deep Copy?

A shallow copy duplicates only the top level of an object. Nested objects inside it are still shared, like two duplicate keys that open the same house. Spread syntax { ...obj } and Object.assign() both make shallow copies:

const originalUser = { name: "Asha", address: { city: "Delhi" } };
const copiedUser = { ...originalUser };

copiedUser.name = "Ravi";            // top level: independent
copiedUser.address.city = "Mumbai";  // nested: shared!

console.log(originalUser.name, originalUser.address.city); // Asha Mumbai

The name stayed safe, but the city changed in the original too, because both objects point to the same address object. A deep copy duplicates every level, so the copy is fully independent. The modern built-in way is structuredClone(), available in all current browsers and in Node.js 17 and later:

const original = { name: "Asha", address: { city: "Delhi" }, joined: new Date("2026-01-15") };
const deep = structuredClone(original);
deep.address.city = "Mumbai";
console.log(original.address.city, deep.joined instanceof Date); // Delhi true

const viaJson = JSON.parse(JSON.stringify(original));
console.log(typeof viaJson.joined); // string (the Date was lost)

structuredClone({ greet() {} });
// DataCloneError: greet() {} could not be cloned.

Older tutorials use the JSON.parse(JSON.stringify(obj)) trick for deep copies. It turns dates into strings and drops undefined values and functions, so prefer structuredClone. Neither can copy functions; for objects with methods, you write the copy yourself.

What Is the Difference Between Object.freeze() and Object.seal()?

Object.freeze() locks an object completely, like a printed birth certificate that nobody should edit. You cannot change, add or delete properties. Object.seal() is softer: you can still change existing properties, but you cannot add or delete any.

const user = { name: "Asha", address: { city: "Delhi" } };
Object.freeze(user);
user.name = "Ravi";  // ignored
user.age = 25;       // ignored
delete user.name;    // ignored
console.log(user.name, user.age); // Asha undefined

user.address.city = "Mumbai";     // nested object is NOT frozen
console.log(user.address.city);   // Mumbai

const sealed = { name: "Asha" };
Object.seal(sealed);
sealed.name = "Ravi"; // allowed
sealed.age = 25;      // ignored
delete sealed.name;   // ignored
console.log(sealed, Object.isSealed(sealed)); // { name: 'Ravi' } true
ActionObject.freeze()Object.seal()
Change existing propertiesNoYes
Add new propertiesNoNo
Delete propertiesNoNo
Affects nested objectsNo (shallow)No (shallow)

Two follow-ups catch people here. First, both are shallow, as the city line shows. Second, the failed changes are ignored silently only in normal (sloppy) mode. In strict mode, which ES modules and classes use automatically, they throw an error instead:

"use strict";
user.name = "Ravi";
// TypeError: Cannot assign to read only property 'name' of object '#<Object>'

Part 3: Functions, Closures and Performance Patterns

What Are Higher-Order Functions?

A higher-order function is a function that takes another function as an argument, returns a function, or does both. A manager who doesn't do every task personally but hands work to the right people is a good picture of it: the higher-order function decides when to call the function you gave it.

function greet(name) {
  return "Hello " + name;
}

function processUser(callback) {
  console.log(callback("Asha"));
}

processUser(greet); // Hello Asha

processUser accepts a function, so it is a higher-order function. You already use many of them: map, filter, reduce, setTimeout and addEventListener all take a function as an argument. Functions can be passed around like this because in JavaScript they are values, just like numbers and strings. That property is often called "functions are first-class citizens".

What Is a Closure?

A closure is a function that remembers the variables from the place where it was created, even after that outer function has finished running. Picture leaving the office with your notes in your bag: the office is closed, but you still have the notes.

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

const counter = outer();
counter(); // 1
counter(); // 2
counter(); // 3

const counter2 = outer();
counter2(); // 1 (a new call to outer creates a new, separate count)

outer() returned long ago, yet inner still reads and updates count. Each call to outer creates a fresh count, which is why counter2 starts again at 1. Nothing outside can reach count directly, so closures are JavaScript's natural way to keep data private.

You will meet closures in counters, event handlers, callbacks, the module pattern, memoization, debouncing and React hooks such as useState. Chapter 12 on closures and the event loop goes deeper with a banking example.

Interview answer: "A closure is a function bundled with the variables of the scope it was created in. The inner function keeps access to them even after the outer function returns. I'd use one to keep private state, like a counter or a cache, that nothing outside can change directly."

What Is a Lexical Environment?

"Lexical" means "based on where the code is written". Every time a function runs, JavaScript creates a lexical environment for it: a record of its own variables plus a reference to the environment it was written inside. That reference is what makes the scope chain and closures work.

let company = "Infosys";

function developer() {
  let name = "Ravi";
  function display() {
    console.log(name);    // Ravi    (from the parent function)
    console.log(company); // Infosys (from the global scope)
  }
  display();
}
developer();

The follow-up that proves you understand "lexical" is this one. A function looks up variables where it was written, not where it is called from:

const shopName = "Global Mart";

function showShop() {
  console.log(shopName);
}

function run() {
  const shopName = "Sharma Kirana";
  showShop(); // called from inside run...
}
run(); // Global Mart  (...but written at the top level)

What Is Currying?

Currying turns a function that takes several arguments into a chain of functions that each take one. Instead of multiply(5, 10) you call multiply(5)(10):

function multiply(a) {
  return function (b) {
    return a * b;
  };
}
console.log(multiply(5)(10)); // 50

const multiplyArrow = a => b => a * b; // same thing, arrow style
console.log(multiplyArrow(5)(10));     // 50

It is like ordering a pizza step by step: first the size, then the toppings, then the address. The useful part is that you can stop after the first step and keep a ready-made, specialised function. A GST calculator shows why that helps:

const addGST = rate => price => Math.round(price * (1 + rate / 100));

const addGST18 = addGST(18); // fix the rate once
console.log(addGST18(1000), addGST18(250)); // 1180 295
console.log(addGST(5)(200));                // 210

Currying works because of closures: the inner function remembers rate. If an interviewer asks "where would you use this?", the honest answer is configuration, such as preset tax rates, loggers with a fixed prefix, or API helpers with a fixed base URL.

What Is Memoization?

Memoization means remembering the result of a function for a given input, so the next call with the same input returns the saved answer instead of calculating again. A shopkeeper who has just checked the price of milk in the register doesn't look it up again when the next customer asks ten minutes later.

function memoize(fn) {
  const cache = new Map();
  return function (arg) {
    if (cache.has(arg)) return cache.get(arg);
    const result = fn(arg);
    cache.set(arg, result);
    return result;
  };
}

let calls = 0;
const slowSquare = n => { calls++; return n * n; };
const square = memoize(slowSquare);

console.log(square(5), square(5), square(0), square(0)); // 25 25 0 0
console.log("calculations:", calls);                     // calculations: 2

Four calls, but only two real calculations. Many tutorials write the cache check as if (cache[number]). That has a hidden bug: when the saved result is 0 or an empty string, the check is false, so the function recalculates every time. With that version, calling square(0) three times does three calculations. Use cache.has() on a Map, or the in operator on an object.

Memoization only makes sense for pure functions, the ones that always return the same output for the same input. Don't memoize something that reads the current time or a database. Also remember the cache grows forever unless you limit it, which can become a memory leak in a long-running server.

What Is Debouncing?

Debouncing waits until something has stopped happening for a set time, and only then runs the function once. The standard example is a search box. If you call the search API on every key press, typing "Hello" sends five requests for "H", "He", "Hel", "Hell" and "Hello". With debouncing, only the last one is sent:

function debounce(fn, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer); // cancel the previous plan
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

const searchProducts = debounce(query => console.log("API call for:", query), 300);

// Simulate typing one letter every 100 ms
["H", "He", "Hel", "Hell", "Hello"].forEach((text, i) => {
  setTimeout(() => searchProducts(text), i * 100);
});
// API call for: Hello

Each key press cancels the timer set by the previous one, so the function runs only after 300 ms of silence. Notice that timer survives between calls because of a closure. Use debouncing for search boxes, auto-complete, saving a draft and validating a field after the user stops typing.

What Is Throttling, and How Is It Different from Debouncing?

Throttling lets a function run at most once in a fixed time window, no matter how often it is triggered. Picture a security guard who lets in one person every five seconds, however big the crowd gets.

function throttle(fn, interval) {
  let lastRun = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastRun >= interval) {
      lastRun = now;
      fn.apply(this, args);
    }
  };
}

let events = 0, runs = 0;
const onScroll = throttle(() => runs++, 300);
const id = setInterval(() => { events++; onScroll(); }, 50); // fake scroll events
setTimeout(() => {
  clearInterval(id);
  console.log(`events: ${events}, handler runs: ${runs}`);
}, 1000);
// events: 15, handler runs: 3  (exact numbers vary slightly, timers are not precise)
DebouncingThrottling
Runs whenActivity stops for the delayAt most once per interval, during the activity
Good forSearch input, auto-save, resize endScroll, mouse move, resize while dragging
Main benefitFewer API callsSteady, limited update rate

A quick way to choose: if you only care about the final value, debounce. If you need regular updates while something is happening, such as a "back to top" button that appears as you scroll, throttle.

Part 4: Working with Data

What Is JSON?

JSON (JavaScript Object Notation) is a text format for sending data between systems. When a frontend talks to a backend API, the request and response bodies are almost always JSON. It looks like a JavaScript object, but it is plain text with stricter rules: keys must be in double quotes, strings must use double quotes, and there are no functions, comments or undefined.

{
  "name": "Asha",
  "age": 25,
  "city": "Jaipur"
}

It became the standard because it is light (less text than XML), easy for people to read, built into JavaScript, and supported by practically every language, including Java, Python, PHP, C# and Go. JavaScript converts in both directions with two methods:

const order = {
  id: 101,
  items: ["rice", "dal"],
  total: 499.5,
  paid: true,
  coupon: undefined,
  placedAt: new Date("2026-11-07T10:30:00Z"),
  print() {},
};

const text = JSON.stringify(order); // object → JSON text
console.log(text);
// {"id":101,"items":["rice","dal"],"total":499.5,"paid":true,"placedAt":"2026-11-07T10:30:00.000Z"}

const back = JSON.parse(text);      // JSON text → object
console.log(back.items[1], typeof back.placedAt); // dal string

JSON.parse("{name: 'Asha'}");       // SyntaxError (keys and strings need double quotes)

Look at what went missing: coupon (undefined) and print (a function) were dropped, and the date came back as a string, not a Date. Those three facts are the usual follow-up questions. Also wrap JSON.parse in try...catch whenever the text comes from outside, because bad input throws. For readable output while debugging, use JSON.stringify(obj, null, 2) to indent with two spaces.

What Are map(), filter() and reduce()?

These three array methods replace most of the for loops you would otherwise write. Each one takes a function and returns a new result without changing the original array.

console.log([1, 2, 3].map(num => num * 2));                  // [ 2, 4, 6 ]
console.log([12, 18, 20, 15, 30].filter(age => age >= 18));  // [ 18, 20, 30 ]
console.log([1, 2, 3, 4].reduce((sum, num) => sum + num, 0)); // 10
  • map() transforms every item and returns an array of the same length, like a teacher turning each student's marks into a grade.
  • filter() selects the items that pass a test, like a guard letting only adults into an event.
  • reduce() combines all items into one value, like adding up a month of UPI payments into one total.

They are most useful together. Here is a grocery cart total and a list of the costlier items:

const cart = [
  { name: "Rice 5kg", price: 320, qty: 1 },
  { name: "Toor dal 1kg", price: 150, qty: 2 },
  { name: "Ghee 1L", price: 640, qty: 1 },
];

const total = cart
  .map(item => item.price * item.qty)
  .reduce((sum, n) => sum + n, 0);
console.log(total); // 1260

console.log(cart.filter(item => item.price >= 300).map(item => item.name));
// [ 'Rice 5kg', 'Ghee 1L' ]

A common follow-up is: "What happens if you leave out the starting value in reduce?" On an empty array it crashes, so always pass one:

[].reduce((s, n) => s + n);    // TypeError: Reduce of empty array with no initial value
console.log([].reduce((s, n) => s + n, 0)); // 0

What Is the Difference Between slice() and splice()?

This is Kabir's question from the start, and the names are confusingly similar. slice() copies a part of an array and leaves the original alone. splice() changes the original array by removing, adding or replacing items, and it returns the items it removed.

let numbers = [1, 2, 3, 4, 5];

// slice(start, end) — end is not included
console.log(numbers.slice(0, 2), numbers); // [ 1, 2 ] [ 1, 2, 3, 4, 5 ]
console.log(numbers.slice(-2));            // [ 4, 5 ] (negative counts from the end)

// splice(start, deleteCount, ...itemsToAdd)
console.log(numbers.splice(1, 2), numbers);      // [ 2, 3 ] [ 1, 4, 5 ]       remove
console.log(numbers.splice(1, 0, "A"), numbers); // [] [ 1, 'A', 4, 5 ]        add
console.log(numbers.splice(1, 1, "B"), numbers); // [ 'A' ] [ 1, 'B', 4, 5 ]   replace
Featureslice()splice()
Original arrayUnchangedChanged
ReturnsA new array with the copied partAn array of the removed items
PurposeRead or copy a partAdd, remove or replace in place
Side effectsNoneYes

A cake is the easy way to remember it. With slice you cut a piece and take it, and the cake on the table looks the same. With splice you cut pieces out, maybe put new ones in, and the cake has changed for good. Because slice has no side effects, it is the safer default, especially with React state, where changing an array in place causes bugs. If you want splice-style editing without changing the original, ES2023 added toSpliced(): [1, 2, 3].toSpliced(1, 1) returns [1, 3] and leaves the original alone.

Interview answer: "slice returns a copy of part of the array and doesn't change it. splice edits the array in place, to remove, insert or replace, and it returns the removed items. I prefer slice, or toSpliced, when I must not change the original."

What Are the Spread and Rest Operators?

Both use the same three dots, ..., but they do opposite jobs. Spread expands an array or object into individual pieces. Rest collects several pieces into one array. Which one you have depends on where the dots appear.

// Spread: expand
const numbers = [1, 2, 3];
console.log([...numbers, 4, 5]); // [ 1, 2, 3, 4, 5 ]

const user = { name: "Asha" };
console.log({ ...user, age: 25 }); // { name: 'Asha', age: 25 }

const defaults = { theme: "light", language: "en" };
const saved = { language: "hi" };
console.log({ ...defaults, ...saved }); // { theme: 'light', language: 'hi' } (later wins)

// Rest: collect
function collect(...numbers) {
  console.log(numbers);
}
collect(1, 2, 3, 4); // [ 1, 2, 3, 4 ]

function billTotal(customer, ...prices) {
  return customer + ": ₹" + prices.reduce((s, p) => s + p, 0);
}
console.log(billTotal("Asha", 120, 80, 300)); // Asha: ₹500
SpreadRest
Expands valuesCollects values
Used where values are given: calls, array and object literalsUsed where values are received: function parameters, destructuring
Turns an array into separate valuesTurns separate values into an array

The merging line deserves attention: when two spread objects have the same key, the later one wins. That is the standard way to apply a user's saved settings on top of defaults. A rest parameter must also be the last parameter, which is why customer comes first.

What Is Destructuring?

Destructuring pulls values out of arrays and objects into separate variables in one line. Arrays are matched by position, and objects are matched by key name.

const colors = ["Red", "Blue"];
const [first, second] = colors;
console.log(first, second); // Red Blue

const user = { name: "Asha", age: 25 };
const { name, age: years, city = "Not given" } = user; // rename and default
console.log(name, years, city); // Asha 25 Not given

let a = 1, b = 2;
[a, b] = [b, a]; // swap without a temp variable
console.log(a, b); // 2 1

You will see destructuring everywhere in React (const [count, setCount] = useState(0)) and in Node.js (const { name, email } = req.body). Knowing the rename (age: years) and default (city = "Not given") forms is what interviewers usually check.

What Are Set and Map?

A Set stores unique values, so duplicates are dropped automatically. Think of a wedding guest list: if the same person registers five times, they should still appear once.

const numbers = new Set([1, 1, 2, 2, 3, 3]);
console.log(numbers, numbers.size, numbers.has(2)); // Set(3) { 1, 2, 3 } 3 true

const emails = ["asha@mail.in", "ravi@mail.in", "asha@mail.in"];
console.log([...new Set(emails)]); // [ 'asha@mail.in', 'ravi@mail.in' ]

That last line, [...new Set(arr)], is the standard one-line answer to "remove duplicates from an array". A Map stores key-value pairs like an object, but any value can be a key, including numbers and objects. Objects quietly turn keys into strings:

const users = new Map();
users.set(1, "Asha");
users.set(2, "Ravi");
console.log(users.get(1), users.size); // Asha 2

const obj = {};
obj[1] = "Asha";
obj[true] = "yes";
console.log(Object.keys(obj)); // [ '1', 'true' ] (keys became strings)

const cartOwner = { id: 7 };
const carts = new Map();
carts.set(cartOwner, ["rice", "dal"]); // an object as a key
console.log(carts.get(cartOwner));     // [ 'rice', 'dal' ]
ObjectMap
Key typesStrings and symbols onlyAny value
SizeObject.keys(obj).lengthmap.size
Inherited keysYes, from the prototypeNone
Best forFixed records like a user or an orderLookups that grow and shrink, such as caches

What Are WeakMap and WeakSet?

A WeakMap is like a Map with two rules: keys must be objects, and it holds them weakly. If nothing else in your program refers to a key object, the garbage collector can delete it, and its entry disappears from the WeakMap too. A WeakSet is the same idea for a Set of objects.

const visits = new WeakMap();
let visitor = { id: 7 };
visits.set(visitor, 3);
console.log(visits.get(visitor), visits.has(visitor)); // 3 true

visits.set("asha", 1); // TypeError: Invalid value used as weak map key

const seen = new WeakSet();
seen.add(visitor);
console.log(seen.has(visitor)); // true

visitor = null; // the object and its WeakMap entry can now be cleaned up

Because entries can vanish at any time, you cannot loop over a WeakMap or read its size. Use it to attach extra data to objects you don't own, such as DOM elements or request objects, without stopping those objects from being freed. That is why it helps avoid memory leaks.

Part 5: How JavaScript Runs Your Code

What Is an Execution Context?

Before a restaurant kitchen starts cooking, the chef gets the station ready: ingredients collected, tools laid out, orders read. Only then does cooking begin. JavaScript does the same thing. Before running any code, it creates an environment that holds the variables, the functions and the value of this. That environment is called an execution context.

There are two main kinds. The Global Execution Context is created once, when the file starts. A Function Execution Context is created every time a function is called, so ten calls mean ten separate contexts, each with its own local variables.

Each context, global or function, is built in the same two phases:

  1. Memory creation phase: JavaScript scans the code. Each var is stored as undefined, each function declaration is stored with its full body, and let/const are registered but left uninitialised. No code runs yet.
  2. Execution phase: the code runs line by line, variables receive their real values, and functions are called.
console.log(shopName);       // undefined (memory phase stored var as undefined)
console.log(typeof openShop); // function  (memory phase stored the whole function)

var shopName = "Sharma Kirana";
function openShop() {
  return "Open";
}

console.log(shopName);       // Sharma Kirana (execution phase assigned it)

This two-phase setup is the real reason hoisting exists. Chapter 8 on execution context walks through both phases step by step.

What Is the Call Stack?

The call stack is how JavaScript keeps track of which function is running and where to return when it finishes. It works like a stack of plates: you put a new plate on top, and you always take the top plate off first. This is called Last In, First Out (LIFO).

function first() {
  console.log("enter first");
  second();
  console.log("leave first");
}
function second() {
  console.log("enter second");
  third();
  console.log("leave second");
}
function third() {
  console.log("third says Hello");
}
first();
// enter first
// enter second
// third says Hello
// leave second
// leave first

Calling first pushes it on the stack. It calls second, which goes on top, and second calls third, which goes on top of that. third finishes first and is removed, then second continues, and first finishes last. The "leave" lines appear in reverse order for exactly that reason.

The stack has a size limit. A function that calls itself without ever stopping fills it up:

function countDown(n) {
  return countDown(n - 1); // no base case
}
countDown(5); // RangeError: Maximum call stack size exceeded

That error is the famous "stack overflow". When you see it, look for recursion without a working base case. Chapter 9 on the call stack shows how to read the stack trace.

What Is the Difference Between Synchronous and Asynchronous Code?

Synchronous code runs one statement after another, and each one waits for the previous one to finish. That is fine for quick work, but imagine a page that waits for a large file to download before doing anything else. Buttons would stop responding and the page would freeze.

Asynchronous code solves this. Slow work is started, handed off, and its result is handled later, while the rest of your code keeps running:

console.log("Start");
setTimeout(() => {
  console.log("Downloaded");
}, 300);
console.log("End");
// Start
// End
// Downloaded

The timer appears earlier in the code, but JavaScript doesn't wait for it. It prints "End" first and runs the callback when the timer is done. What makes that possible is the event loop.

What Is the Event Loop?

The event loop is the mechanism that lets single-threaded JavaScript handle many slow tasks without freezing. Almost every JavaScript interview reaches this topic sooner or later, because it ties together the call stack, timers and Promises. You need to know five parts:

  • Call stack: where your code actually runs, one function at a time.
  • Web APIs (or Node.js APIs): the browser's own features, such as timers, fetch, DOM events and geolocation. They do the waiting outside your JavaScript thread.
  • Callback queue (also called the task or macrotask queue): finished callbacks from timers and events wait here.
  • Microtask queue: Promise callbacks (.then, .catch, code after await) wait here.
  • Event loop: whenever the call stack is empty, it first runs all waiting microtasks, then takes the next callback from the callback queue.

Think of a restaurant manager who keeps checking whether the chef is free. When the chef finishes a dish, the manager hands over the next order, but urgent orders (microtasks) always go before regular ones. Here is the flow for a simple timer:

console.log("Start");
setTimeout(() => console.log("Timer Done"), 2000);
console.log("End");
  1. "Start" is printed immediately.
  2. setTimeout hands the timer to the Web API, and the 2-second wait happens there.
  3. "End" is printed immediately. The call stack is now empty.
  4. After 2 seconds, the callback is placed in the callback queue.
  5. The event loop sees the empty stack and moves the callback onto it, so "Timer Done" is printed.

The delay in setTimeout is therefore a minimum, not an exact time. If the stack is busy with a long loop, the callback simply waits longer.

What Is the Microtask Queue? (The Most Asked Output Question)

Promise callbacks go to the microtask queue, and the event loop empties that queue completely before it touches the callback queue. That is why a Promise beats a setTimeout of 0 milliseconds. This exact question is asked in many interviews:

console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
// A
// D
// C
// B
  1. A runs immediately because it is ordinary synchronous code.
  2. The setTimeout callback is handed off and later lands in the callback queue.
  3. The .then callback is placed in the microtask queue.
  4. D runs immediately. The synchronous code is now finished.
  5. The stack is empty, so the event loop runs all microtasks first, which prints C.
  6. Only then does it take B from the callback queue.

Kabir practises this one the evening after his interview. His first instinct is still A, B, C, D, "because the timer is zero". Then he writes the order of the queues on paper (synchronous code, then microtasks, then the callback queue) and gets it right. To check that the rule really stuck, he tries a version with async/await, where the code after await is also a microtask:

console.log("1");
setTimeout(() => console.log("2"), 0);
(async () => {
  console.log("3");  // runs synchronously, up to the first await
  await null;
  console.log("4");  // microtask
})();
console.log("5");
// 1
// 3
// 5
// 4
// 2

The surprise for most people is 3: an async function runs synchronously until its first await. If you can explain this output, you can explain the event loop. For more puzzles like it, see Chapter 12 and the tricky output questions.

Interview answer: "JavaScript runs all synchronous code first. Then the event loop empties the microtask queue, which holds Promise callbacks and code after await. Only then does it take one task from the callback queue, such as a setTimeout callback. So a resolved Promise always runs before a zero-delay timeout."

What Is Callback Hell?

Before Promises, async steps that depended on each other were written as callbacks inside callbacks. With three dependent steps, such as getting a user, then their orders, then a payment, the code drifts to the right with every step:

function getUser(id, callback) {
  setTimeout(() => callback({ id, name: "Asha" }), 50);
}
function getOrders(userId, callback) {
  setTimeout(() => callback([{ id: 9001, total: 499 }]), 50);
}
function getPayment(orderId, callback) {
  setTimeout(() => callback({ orderId, status: "PAID", via: "UPI" }), 50);
}

getUser(7, function (user) {
  getOrders(user.id, function (orders) {
    getPayment(orders[0].id, function (payment) {
      console.log(payment); // { orderId: 9001, status: 'PAID', via: 'UPI' }
    });
  });
});

That triangle shape is called callback hell or the "pyramid of doom". It is hard to read and hard to debug. Worse, error handling has to be repeated at every level, and one forgotten error check makes a failure disappear silently. Promises were added to fix this.

What Is a Promise?

A Promise is an object that stands for a result that isn't ready yet. Ordering food online is a good picture: you get an order ID immediately, and the food (or a cancellation message) arrives later. A Promise is always in one of three states:

  • Pending: the work is still running.
  • Fulfilled: it finished successfully and has a value.
  • Rejected: it failed and has a reason, ideally an Error object.
const orderPromise = new Promise((resolve, reject) => {
  const delivered = true;
  if (delivered) resolve("Order delivered");
  else reject(new Error("Order failed"));
});

console.log(orderPromise); // Promise { 'Order delivered' }

orderPromise
  .then(result => console.log(result))         // Order delivered
  .catch(error => console.log(error.message))
  .finally(() => console.log("Tracking closed")); // Tracking closed

Once a Promise is settled, it never changes state again. Use .then for success, .catch for failure, and .finally for clean-up that should run either way, such as hiding a loading spinner. Reject with new Error(...) rather than a plain string, so you get a stack trace when something fails.

What Is Promise Chaining?

Each .then() returns a new Promise, so dependent steps can be written as a flat chain instead of a pyramid. With Promise-returning versions of the same three functions:

function fetchUser(id) {
  return new Promise(resolve => setTimeout(() => resolve({ id, name: "Asha" }), 50));
}
function fetchOrders(userId) {
  return Promise.resolve([{ id: 9001, total: 499 }]);
}
function fetchPayment(orderId) {
  if (orderId !== 9001) return Promise.reject(new Error("Payment not found"));
  return Promise.resolve({ orderId, status: "PAID", via: "UPI" });
}

fetchUser(7)
  .then(user => fetchOrders(user.id))
  .then(orders => fetchPayment(orders[0].id))
  .then(payment => console.log(payment.status, "via", payment.via)) // PAID via UPI
  .catch(error => console.log("Failed:", error.message));

One .catch at the end handles a failure from any step. The rule that trips people up is that each .then must return the next Promise. If you forget the return inside a block-bodied callback, the next step receives undefined and runs too early.

What Is async/await?

async/await is a cleaner way to write the same Promise code. An async function always returns a Promise, and await pauses that function (not the whole program) until a Promise settles. The code reads top to bottom like synchronous code, and errors are handled with an ordinary try...catch:

async function showPayment(userId) {
  try {
    const user = await fetchUser(userId);
    const orders = await fetchOrders(user.id);
    const payment = await fetchPayment(orders[0].id);
    console.log(`${user.name} paid ₹${orders[0].total} via ${payment.via}`);
  } catch (error) {
    console.log("Failed:", error.message);
  }
}

await showPayment(7);   // Asha paid ₹499 via UPI   (top-level await works in ES modules)

try {
  await fetchPayment(1234);
} catch (e) {
  console.log("Failed:", e.message); // Failed: Payment not found
}

console.log(fetchUser(7)); // Promise { <pending> } (forgot await, so you get the Promise)

Its benefits are cleaner syntax, less nesting, easier debugging (stack traces point to real lines) and familiar error handling. It is the preferred style in modern JavaScript.

The common follow-up is: "What is wrong with awaiting independent calls one by one?" If the calls don't depend on each other, waiting for each in turn wastes time. Start them together with Promise.all:

const [user, orders] = await Promise.all([fetchUser(7), fetchOrders(7)]);
console.log(user.name, orders.length); // Asha 1

Chapter 13 on Promises and async/await covers Promise.allSettled, Promise.race and the async mistakes that show up in real projects.

Part 6: Browser and Memory Questions

What Is the Difference Between localStorage and sessionStorage?

Both let a website save small amounts of text in the browser, using the same methods. The difference is how long the data lives. localStorage stays until your code or the user clears it, even after the browser is closed. sessionStorage lasts only as long as that tab: it survives a page reload but is gone when the tab is closed, and each tab has its own copy.

// Run in the browser console (F12 → Console)
localStorage.setItem("user", "Asha");
localStorage.getItem("user");        // "Asha"

localStorage.setItem("count", 5);
localStorage.getItem("count");       // "5" (a string, not a number)

localStorage.setItem("cart", { items: 2 });
localStorage.getItem("cart");        // "[object Object]" (the object was lost)

localStorage.setItem("cart", JSON.stringify({ items: 2 }));
JSON.parse(localStorage.getItem("cart")).items; // 2

sessionStorage.setItem("step", "payment"); // gone when this tab closes
FeaturelocalStoragesessionStorage
LifetimeUntil clearedUntil the tab closes
Shared between tabs of the same siteYesNo, one copy per tab
Survives browser restartYesNo
Size limitUsually about 5 MB per siteUsually about 5 MB per site
StoresStrings onlyStrings only

Two points earn extra credit. First, both store only strings, so numbers come back as text and objects must go through JSON.stringify and JSON.parse. Second, any script on the page can read them, so never store passwords or login tokens there; one cross-site scripting bug would expose them. Chapter 2 on how browsers work covers storage and the other browser APIs.

What Is Event Delegation?

Event delegation means attaching one event listener to a parent element instead of one listener to every child. It works because most events bubble: a click on a button travels up through its parent, grandparent and so on, so the parent hears it too.

<!-- HTML -->
<ul id="product-list">
  <li><button data-id="101">Add Rice</button></li>
  <li><button data-id="102">Add Dal</button></li>
  <li><button data-id="103">Add Ghee</button></li>
</ul>
// One listener on the parent instead of three on the buttons
const list = document.querySelector("#product-list");

list.addEventListener("click", (event) => {
  const button = event.target.closest("button[data-id]");
  if (!button) return; // the click was not on a button
  console.log("Add to cart:", button.dataset.id); // e.g. Add to cart: 102
});

The benefits are fewer listeners (which matters with hundreds of rows) and automatic support for buttons added later, such as products loaded on scroll, because the listener lives on the parent that is already there. Using closest() rather than checking event.target directly handles clicks on an icon or <span> inside the button.

What Is Garbage Collection?

Garbage collection is how JavaScript frees memory automatically. In languages like C, you release memory yourself. In JavaScript, the engine periodically finds objects that your program can no longer reach and removes them, like an office cleaner who clears papers nobody is using at the end of the day.

The key word is reachable. An object stays in memory as long as something can still reach it, through a variable, another object, a closure or a listener:

let a = { name: "Asha" };
let b = a;          // a second reference to the same object
a = null;
console.log(b.name); // Asha (still reachable through b, so not collected)

b = null;            // now nothing refers to it; it can be collected

Without garbage collection, memory would keep growing until the app slowed down or the browser tab crashed. You don't call the collector yourself, and you can't control exactly when it runs.

What Is a Memory Leak, and What Causes One?

A memory leak is memory your program no longer needs but still keeps reachable, so the garbage collector cannot free it. It is like renting storage units you stopped using but never cancelled: the cost keeps growing quietly. These are the usual causes:

  • Event listeners that are never removed, especially on elements you remove from the page or in single-page apps. Pair every addEventListener with a removeEventListener when the component goes away.
  • Timers that are never cleared. A setInterval keeps its callback, and everything that callback uses, alive until you stop it.
  • Accidental globals. Assigning to an undeclared name creates a global variable that lives for the whole life of the page.
  • Caches and arrays that only grow, such as a memoization cache or a list of log messages with no limit.
// A timer you keep the ID for, so you can stop it
let ticks = 0;
const intervalId = setInterval(() => {
  ticks++;
  console.log("Running", ticks);
}, 100);
setTimeout(() => {
  clearInterval(intervalId);
  console.log("Stopped");
}, 350);
// Running 1
// Running 2
// Running 3
// Stopped

// An accidental global
function setName() {
  userName = "Asha"; // no let/const: creates a global
}
setName();
console.log(globalThis.userName); // Asha (it leaked out of the function)

Strict mode turns the accidental global into an error instead: assigning to an undeclared name throws ReferenceError: userName is not defined. ES modules and classes are always strict, which is one more reason to use them.

What Is a Polyfill?

A polyfill is code that adds a modern feature to an older browser that doesn't support it, using features the old browser already has. It is like fitting a lift in an old building: old and new residents end up with the same convenience. The pattern is always the same: check whether the feature exists, and add it only if it is missing.

if (!Array.prototype.includes) {
  Array.prototype.includes = function (value) {
    for (let i = 0; i < this.length; i++) {
      const item = this[i];
      if (item === value || (Number.isNaN(item) && Number.isNaN(value))) return true;
    }
    return false;
  };
}

console.log(["rice", "dal"].includes("dal")); // true
console.log([1, NaN].includes(NaN));          // true

Many tutorials write this polyfill as return this.indexOf(value) !== -1. That is a good interview follow-up, because it is subtly wrong. indexOf uses ===, and NaN === NaN is false, so [NaN].indexOf(NaN) returns -1 while the real [NaN].includes(NaN) returns true. A correct polyfill must match the real behaviour, including edge cases. In real projects you rarely write polyfills by hand; tools like Babel and core-js add them for the browsers you choose to support.

What Are JavaScript Modules?

As an app grows, one huge file becomes impossible to manage, just as a library would be useless without sections for science, history and mathematics. Modules let you split code into files, each with its own private scope, and share only what you choose with export and import:

// math.mjs
export function add(a, b) {
  return a + b;
}

// app.mjs
import { add } from "./math.mjs";
console.log(add(2, 3)); // 5

Modules improve readability, make code easier to maintain and test, and let teams work on separate files. Node.js also has an older module system, CommonJS (require and module.exports), and the differences between the two come up in backend interviews. They are explained in CommonJS vs ES Modules.

What Is the Module Pattern?

Before ES6 modules existed, developers created private variables using the module pattern: a function that runs immediately (an IIFE) and returns only the methods that should be public. It is a closure put to work:

const Counter = (function () {
  let count = 0; // private
  return {
    increment() { count++; },
    getCount() { return count; },
  };
})();

Counter.increment();
Counter.increment();
console.log(Counter.getCount(), Counter.count); // 2 undefined

Only the returned methods can see count, so nothing outside can set it to a wrong value. The pattern was popular for encapsulation and data privacy. You will still meet it in older code and in interviews, even though ES modules and private class fields (#count) now do the same job more directly.

Rapid-Fire JavaScript Interview Questions

These short ones often come at the end of a round. Each answer is one or two sentences, so say it confidently and move on.

Is JavaScript compiled or interpreted?

Both. Modern engines such as V8 (used in Chrome and Node.js) first run your code quickly through an interpreter, then compile the frequently used parts into fast machine code while the program runs. This is called Just-In-Time (JIT) compilation.

If JavaScript is single-threaded, how can it do asynchronous work?

Your JavaScript runs on one thread, but the browser or Node.js does the waiting for timers, network requests and file reads elsewhere. When that work finishes, the event loop puts the callback, Promise or await continuation back onto the single thread.

What is NaN?

NaN means "Not a Number", the result of a failed numeric operation such as Number("Hello"). Oddly, typeof NaN is "number", and NaN is not equal even to itself, so test for it with Number.isNaN().

What does typeof null return?

It returns "object". This is a bug from the very first version of JavaScript that can never be fixed without breaking old websites. To check for null, write value === null.

Are an empty array and an empty object truthy?

Yes, both [] and {} are truthy, so if ([]) runs its block. To check whether an array is empty, test arr.length === 0; for an object, use Object.keys(obj).length === 0.

Common Mistakes (and the Fix)

Mistake in an answer or in codeWhy it's wrongBetter answer or fix
"let and const are not hoisted."They are hoisted but stay uninitialised in the TDZ"They are hoisted, but using them before the declaration throws a ReferenceError."
"const makes an object read-only."It only stops reassignment of the variableUse Object.freeze(), and remember it is shallow
Treating { ...obj } as a full copyNested objects are still sharedUse structuredClone(obj) for a deep copy
"splice returns the new array."It returns the removed items and changes the originalUse slice or toSpliced when the original must stay the same
Expecting setTimeout(fn, 0) to run before a PromiseMicrotasks always run before the callback queueOrder: synchronous code, then microtasks, then timers
Writing an object method as an arrow functionArrows have no own this, so this.name is not the object'sUse method syntax: greet() { ... }
Memo cache check if (cache[n])Results like 0 or "" look missing, so they are recalculatedUse a Map with cache.has(n)

My Opinion

Learn the follow-up, not just the definition. A definition only gets you past the first question. For every topic in this guide, ask yourself what the obvious next question is ("what does it return?", "what happens with zero?", "is it shallow?") and make sure you can answer that too.

Run every snippet before the interview. Predict the output, then run it in the browser console or with Node.js. The gap between what you predicted and what you saw is exactly what you need to study. Reading about the event loop is much weaker practice than being wrong about it once.

For a fresher role, depth on the basics beats breadth. I would rather a candidate explain var/let/const, this, closures and the A-D-C-B question well than list ten advanced topics with one-line definitions. Polyfills, WeakMap and currying are worth knowing, but they come after the core.

Say "I'm not sure, but here's how I'd find out". Guessing confidently and being wrong, as Kabir did with splice, looks worse than reasoning out loud. "I think it returns the removed items; I'd confirm in the console" shows the habit teams actually want.

Connect each answer to real code. One sentence like "I'd debounce the search box so we don't hit the API on every key press" shows you have used the idea, not just read about it. That is usually what turns a correct answer into a convincing one.

Try It Yourself

Predict each output before you run it in the browser console (press F12 → Console) or with Node.js. Answers are below.

1. console.log(typeof null);

2. const arr = [1, 2, 3, 4];
   console.log(arr.splice(1, 2), arr);

3. console.log(x);
   var x = 5;

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

5. const a = { n: { v: 1 } };
   const b = { ...a };
   b.n.v = 2;
   console.log(a.n.v);

6. console.log([NaN].includes(NaN), [NaN].indexOf(NaN));

7. const f = a => b => a + b;
   console.log(f(2)(3));

8. console.log(null == undefined, null === undefined);
Show answers
1. "object"           → a historical bug that can't be fixed
2. [ 2, 3 ] [ 1, 4 ]  → splice returns the removed items and changes arr
3. undefined          → var is hoisted and starts as undefined
4. A D C B            → sync first, then microtasks, then the timer
5. 2                  → spread is a shallow copy; n is shared
6. true -1            → includes handles NaN, indexOf uses === and can't
7. 5                  → currying: f(2) returns b => 2 + b
8. true false         → == treats null and undefined as equal; === does not

Frequently Asked Questions

Which JavaScript topics matter most for a fresher interview?

Focus first on var/let/const, == vs ===, hoisting, scope and closures, this with arrow functions, array methods (map, filter, reduce, slice, splice), and the event loop with Promises and async/await. Then add one or two practical patterns such as debouncing. Most fresher rounds also include a small coding problem, so practise those alongside the theory.

Do I need to know ES6 features for interviews?

Yes. Arrow functions, let/const, template literals, destructuring, spread and rest, classes, modules and Promises are part of everyday JavaScript now, and interviewers assume you know them. Older patterns like the module pattern still come up, mostly to check that you understand closures.

Should I learn TypeScript before JavaScript interviews?

Not before, but soon after. Interview questions about the language itself are almost always about JavaScript behaviour, and TypeScript adds types on top without changing how the event loop, this or closures work. Once your JavaScript basics are solid, TypeScript is worth learning because many job listings ask for it.

How should I practise output-based questions?

Write the predicted output on paper first, then run the code. When you are wrong, write one sentence explaining why. The beginner logic questions and the tricky output questions on this blog are designed for exactly that kind of practice.

Key Takeaways

  • Answer in three parts: a one-line definition, a tiny example, and the gotcha or real use.
  • let and const are block-scoped and hoisted into the TDZ; var is function-scoped and starts as undefined. const does not freeze objects.
  • this depends on how a function is called; arrow functions borrow it from their surroundings, and call/apply/bind set it explicitly.
  • Closures let functions keep private state, and they power currying, memoization, debouncing and the module pattern.
  • slice copies, splice edits in place and returns the removed items; spread copies are shallow, while structuredClone copies deeply.
  • The event loop order is synchronous code, then all microtasks (Promises, await), then one callback-queue task (timers, events).
  • Memory leaks come from things that stay reachable: listeners, timers, accidental globals and caches that only grow.

Ready to test yourself? Work through the tricky JavaScript output questions next, and see how many you can explain, not just answer.

References

Related Articles

Post a Comment

0 Comments