25 JavaScript Interview Questions

Click any question to expand the detailed answer. These cover the most commonly tested JavaScript concepts in technical interviews for frontend, full stack, and software engineering roles.

A closure is a function that retains access to variables from its outer (enclosing) scope even after that outer function has finished executing. The inner function "closes over" the variables from its surrounding lexical environment.

function makeCounter() {
  let count = 0; // count lives in makeCounter's scope

  return function increment() {
    count++;       // inner function closes over count
    return count;
  };
}

const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
// count is private โ€” nobody outside can touch it directly

Why closures matter in interviews: They power data privacy (module pattern), factory functions, memoization, and event handler callbacks. Every time you write a function that uses a variable from an outer scope, you are using a closure.

Hoisting is JavaScript's behavior of moving declarations to the top of their scope during the compilation phase, before code executes. Only the declaration is hoisted โ€” not the initialization.

// var declarations are hoisted (initialized as undefined)
console.log(x); // undefined โ€” not a ReferenceError
var x = 5;
console.log(x); // 5

// let and const are hoisted but NOT initialized (Temporal Dead Zone)
console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 10;

// Function declarations are fully hoisted (body included)
greet(); // "Hello!" โ€” works before the declaration
function greet() { console.log("Hello!"); }

// Function expressions are NOT hoisted
sayBye(); // TypeError: sayBye is not a function
var sayBye = function() { console.log("Bye!"); };

In interviews, focus on the distinction: var hoists and initializes to undefined, let/const hoist but are in the Temporal Dead Zone, and function declarations are fully hoisted.

== is the loose equality operator โ€” it performs type coercion before comparing. === is the strict equality operator โ€” it compares both value and type with no coercion.

// == coerces types
0 == false       // true  (false coerces to 0)
"5" == 5         // true  (string "5" coerces to number)
null == undefined // true  (special case in spec)
[] == false      // true  ([] โ†’ "" โ†’ 0, false โ†’ 0)

// === no coercion
0 === false      // false (number vs boolean)
"5" === 5        // false (string vs number)
null === undefined // false (different types)

// Objects/arrays are compared by reference, not value
{} === {}        // false (different objects in memory)
[] === []        // false

Best practice: Always use === in production code. The only common exception is x == null which checks for both null and undefined at once.

JavaScript is single-threaded โ€” it can only execute one thing at a time. The event loop is the mechanism that allows JS to perform non-blocking I/O by offloading operations to the browser (or Node.js) and processing their callbacks when the main thread is idle.

Key components:

  • Call Stack: Executes synchronous code, one frame at a time (LIFO).
  • Web APIs / Node APIs: Handle async work (timers, fetch, DOM events) outside the main thread.
  • Task Queue (Macro-task): Holds callbacks from setTimeout, setInterval, I/O events.
  • Microtask Queue: Holds Promise callbacks (.then, .catch, async/await) and queueMicrotask. Runs before the next macro-task.
console.log("1");

setTimeout(() => console.log("2"), 0);

Promise.resolve().then(() => console.log("3"));

console.log("4");

// Output: 1, 4, 3, 2
// 1 & 4 โ†’ sync (call stack)
// 3 โ†’ microtask queue (Promises run before setTimeout)
// 2 โ†’ macro-task queue (setTimeout)

The event loop's job: when the call stack is empty, drain all microtasks, then pick one macro-task and repeat.

A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. It has three states: pending, fulfilled, or rejected.

// Callbacks โ€” leads to "callback hell"
getData(function(data) {
  processData(data, function(result) {
    saveResult(result, function(saved) {
      // deeply nested, hard to read/debug
    });
  });
});

// Promises โ€” chainable, flat
getData()
  .then(data => processData(data))
  .then(result => saveResult(result))
  .then(saved => console.log("Done!", saved))
  .catch(err => console.error("Error:", err));

// Creating a promise
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
delay(1000).then(() => console.log("1 second later"));

Callbacks vs Promises:

  • Callbacks can lead to "callback hell" โ€” deep nesting that is hard to read.
  • Promises are chainable and have a unified .catch() for error handling.
  • Promise.all() runs multiple async operations in parallel and waits for all to finish.
  • Promise.race() resolves/rejects as soon as the first promise settles.

async/await is syntactic sugar over Promises. An async function always returns a Promise. Inside it, await pauses execution until the Promise settles โ€” without blocking the main thread.

// Promise chain version
function fetchUser(id) {
  return fetch(`/api/users/${id}`)
    .then(res => res.json())
    .then(user => user.name);
}

// async/await version โ€” same behavior, cleaner syntax
async function fetchUser(id) {
  const res = await fetch(`/api/users/${id}`);
  const user = await res.json();
  return user.name; // function returns Promise
}

// Error handling
async function loadData() {
  try {
    const data = await fetchUser(1);
    console.log(data);
  } catch (err) {
    console.error("Failed:", err.message);
  }
}

// Parallel execution with async/await
async function loadAll() {
  const [user, posts] = await Promise.all([
    fetchUser(1),
    fetchPosts(1)
  ]);
}

Key point: await can only be used inside an async function. Under the hood, every await is a .then() โ€” the JS engine transforms the async function into a state machine of Promise callbacks.

this refers to the object that is currently executing the function. Its value is determined by how a function is called, not where it is defined โ€” except for arrow functions.

// 1. Global context
console.log(this); // window (browser) or {} (Node.js strict)

// 2. Object method
const obj = {
  name: "Ramayai",
  greet() { return `Hi, I'm ${this.name}`; }
};
console.log(obj.greet()); // "Hi, I'm Ramayai"

// 3. Regular function (loses context when detached)
const fn = obj.greet;
console.log(fn()); // "Hi, I'm undefined" โ€” this is now global

// 4. Arrow function โ€” inherits this from enclosing scope
const obj2 = {
  name: "Tech",
  greet: () => `Hi, I'm ${this.name}` // this = outer scope (window)
};
console.log(obj2.greet()); // "Hi, I'm undefined" (no own this)

// 5. Constructor (new)
function Person(name) { this.name = name; }
const p = new Person("Sai");
console.log(p.name); // "Sai" โ€” this = new object

// 6. Explicit binding
function sayName() { return this.name; }
sayName.call({ name: "Kiran" }); // "Kiran"

Arrow functions do not have their own this. They lexically inherit this from the surrounding code โ€” which makes them great for callbacks inside class methods.

In JavaScript, every object has an internal link to another object called its prototype. When you access a property on an object, JS looks up the prototype chain until it finds the property or reaches null.

// Every object's prototype is Object.prototype by default
const animal = {
  speak() { return `${this.name} makes a sound.`; }
};

const dog = Object.create(animal); // dog's prototype = animal
dog.name = "Rex";

console.log(dog.speak()); // "Rex makes a sound."
// speak() found on prototype, not on dog itself

// The prototype chain:
// dog โ†’ animal โ†’ Object.prototype โ†’ null

// ES6 class syntax (syntactic sugar over prototypes)
class Animal {
  constructor(name) { this.name = name; }
  speak() { return `${this.name} makes a sound.`; }
}

class Dog extends Animal {
  speak() { return `${this.name} barks.`; }
}

const d = new Dog("Rex");
console.log(d.speak()); // "Rex barks."
console.log(d instanceof Animal); // true

Unlike classical inheritance (copying properties), prototypal inheritance is based on delegation โ€” objects delegate property lookups up the chain. class syntax in ES6 is just cleaner syntax on top of the same prototype mechanism.

Both represent the absence of a value, but they signal different things:

  • undefined: A variable has been declared but not yet assigned a value. It is the default value JS gives to uninitialized variables, missing function arguments, and object properties that don't exist.
  • null: An intentional assignment of "no value." It is explicitly set by a developer to indicate "empty" or "cleared."
let a;
console.log(a); // undefined โ€” declared, not assigned

function greet(name) {
  console.log(name); // undefined if called as greet()
}

const obj = { x: 1 };
console.log(obj.y); // undefined โ€” property doesn't exist

// null is intentional
let user = null; // developer says "no user yet"

// typeof
typeof undefined // "undefined"
typeof null      // "object" โ€” this is a famous JS bug (legacy)

// Equality
null == undefined  // true  (loose equality)
null === undefined // false (strict equality)

Rule of thumb: Use null when you want to explicitly communicate "no value." Treat undefined as JS's way of saying "this wasn't set."

Event delegation is the pattern of attaching a single event listener to a parent element instead of attaching individual listeners to each child. It works because DOM events bubble up from the target element through its ancestors.

// BAD โ€” attaching to every item (memory-intensive)
document.querySelectorAll('.product').forEach(item => {
  item.addEventListener('click', handleClick);
});

// GOOD โ€” event delegation (one listener on the parent)
document.querySelector('#product-list').addEventListener('click', function(e) {
  const item = e.target.closest('.product');
  if (item) {
    const id = item.dataset.id;
    console.log("Clicked product:", id);
  }
});

// Works even for items added dynamically AFTER the listener is set up!

Why it matters:

  • Better performance โ€” one listener instead of hundreds.
  • Works for dynamically added elements (e.g., items loaded from an API).
  • Easier cleanup โ€” remove one listener instead of many.

e.target is the element that was actually clicked. e.currentTarget is the element the listener is attached to.

  • var: Function-scoped (or global). Hoisted and initialized to undefined. Can be re-declared. Avoid in modern JS.
  • let: Block-scoped. Hoisted but in the Temporal Dead Zone. Can be reassigned, not re-declared in the same scope.
  • const: Block-scoped. Must be initialized at declaration. Cannot be reassigned. Objects/arrays declared with const are still mutable (their contents can change, just not the binding).
// var โ€” function scope
function test() {
  if (true) { var x = 1; }
  console.log(x); // 1 โ€” var leaks out of the if block
}

// let โ€” block scope
function test2() {
  if (true) { let y = 1; }
  console.log(y); // ReferenceError โ€” y is block-scoped
}

// const โ€” not reassignable
const PI = 3.14;
PI = 3; // TypeError

const arr = [1, 2, 3];
arr.push(4); // OK โ€” mutating contents is allowed
arr = []; // TypeError โ€” cannot reassign the binding

Best practice: Default to const. Use let when you know the value will change. Never use var.

Both use the ... syntax but serve opposite purposes.

Spread operator โ€” expands an iterable (array, object) into individual elements. Used in calls, array/object literals.

// Spread in arrays
const a = [1, 2, 3];
const b = [...a, 4, 5]; // [1, 2, 3, 4, 5]

// Spread in function calls
Math.max(...a); // same as Math.max(1, 2, 3)

// Spread in objects (shallow copy / merge)
const base = { x: 1, y: 2 };
const extended = { ...base, z: 3 }; // { x:1, y:2, z:3 }
const override = { ...base, y: 99 }; // { x:1, y:99 }

Rest parameters โ€” collects the remaining arguments into an array. Used in function definitions.

function sum(...numbers) {
  return numbers.reduce((acc, n) => acc + n, 0);
}
sum(1, 2, 3, 4); // 10 โ€” numbers = [1, 2, 3, 4]

// Rest must be last parameter
function first(a, b, ...rest) {
  console.log(a, b, rest); // 1, 2, [3, 4, 5]
}
first(1, 2, 3, 4, 5);

Destructuring is a shorthand syntax to unpack values from arrays or properties from objects into distinct variables.

// Array destructuring
const [first, second, ...rest] = [10, 20, 30, 40];
// first = 10, second = 20, rest = [30, 40]

// Skip elements
const [, , third] = [1, 2, 3]; // third = 3

// Object destructuring
const user = { name: "Sai", age: 25, city: "Hyderabad" };
const { name, age } = user;
// name = "Sai", age = 25

// Rename while destructuring
const { name: userName, city: location } = user;
// userName = "Sai", location = "Hyderabad"

// Default values
const { role = "guest" } = user; // role = "guest" (not in user)

// Function parameter destructuring
function greet({ name, city = "Unknown" }) {
  return `${name} from ${city}`;
}
greet(user); // "Sai from Hyderabad"

Destructuring is everywhere in modern React โ€” const [count, setCount] = useState(0) is array destructuring, and function Component({ title, onClick }) is object destructuring in props.

These are the three core higher-order array methods in JavaScript. All three do not mutate the original array.

const products = [
  { name: "Laptop", price: 999, inStock: true },
  { name: "Mouse", price: 29, inStock: false },
  { name: "Keyboard", price: 79, inStock: true },
];

// map โ€” transform each element, return new array of same length
const names = products.map(p => p.name);
// ["Laptop", "Mouse", "Keyboard"]

// filter โ€” keep elements matching condition
const available = products.filter(p => p.inStock);
// [{ name: "Laptop" ... }, { name: "Keyboard" ... }]

// reduce โ€” accumulate to a single value
const totalValue = products.reduce((sum, p) => sum + p.price, 0);
// 1107

// Chaining
const availableTotal = products
  .filter(p => p.inStock)        // keep in-stock only
  .map(p => p.price)             // extract prices
  .reduce((sum, price) => sum + price, 0); // sum them
// 1078

Mental model: map = transform, filter = select, reduce = combine. Master these three and you can express most data transformations without loops.

A pure function satisfies two rules:

  • Deterministic: Given the same inputs, always returns the same output.
  • No side effects: It doesn't modify anything outside its own scope (no global mutation, no API calls, no DOM changes, no logging).
// Pure function
function add(a, b) { return a + b; }
add(2, 3); // always 5, nothing else changes

// Impure โ€” depends on external state
let tax = 0.1;
function priceWithTax(price) { return price * (1 + tax); }
// If tax changes, same input gives different output

// Impure โ€” side effect
let total = 0;
function addToTotal(n) { total += n; } // mutates external variable

// Pure equivalent
function addToTotal(currentTotal, n) { return currentTotal + n; }

Pure functions are the foundation of React's component model (same props โ†’ same output), Redux reducers, and functional programming. They are easy to test, cache, and parallelize.

Both limit how often a function is called in response to rapid events (like scroll, resize, keypress). They solve different problems.

Debouncing: Delays the function until the user has stopped triggering the event for a set delay. The timer resets on every call. Good for search inputs โ€” wait until the user stops typing.

function debounce(fn, delay) {
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

const handleSearch = debounce((query) => {
  fetch(`/api/search?q=${query}`);
}, 300);

// User types "r", "re", "rea", "reac", "react"
// API call only fires 300ms after "react" (last keystroke)

Throttling: Fires the function at most once per interval, ignoring extra calls in between. Good for scroll events โ€” fire max once every 100ms.

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

const handleScroll = throttle(() => updateNavbar(), 100);
window.addEventListener('scroll', handleScroll);

Synchronous code executes line by line. Each line must complete before the next one starts. If a task is slow (e.g., a big computation), it blocks everything.

Asynchronous code allows the engine to start a task and move on โ€” the result is handled later via a callback, Promise, or await. This is how JavaScript handles I/O without freezing the browser.

// Synchronous โ€” blocks
console.log("start");
const data = readFileSyncBlocking("big.csv"); // blocks for 2 seconds
console.log("done"); // only runs after the file is read

// Asynchronous โ€” non-blocking
console.log("start");
fetch("/api/data")             // starts the request, doesn't block
  .then(res => res.json())
  .then(data => console.log("got data", data));
console.log("this runs BEFORE data arrives");

// Output:
// "start"
// "this runs BEFORE data arrives"
// "got data ..." (when the request finishes)

JavaScript's single-threaded nature makes async essential โ€” blocking operations would freeze the UI. The event loop enables async by offloading work to browser APIs and bringing callbacks back when the stack is free.

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts web pages from making requests to a different domain, protocol, or port than the one that served the page โ€” the Same-Origin Policy.

When your React app at http://localhost:3000 calls an API at http://localhost:5000, the browser checks if the server allows it. The server signals this via response headers.

// Server (Node/Express) โ€” allow CORS
const cors = require('cors');
app.use(cors({
  origin: 'http://localhost:3000', // allow only this origin
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  credentials: true,              // allow cookies
}));

// Key CORS response headers:
// Access-Control-Allow-Origin: http://localhost:3000
// Access-Control-Allow-Methods: GET, POST
// Access-Control-Allow-Headers: Content-Type, Authorization

// Preflight โ€” browser sends OPTIONS request first for non-simple requests
// (POST with JSON, requests with custom headers)
// Server must respond to OPTIONS with the CORS headers

CORS errors only happen in browsers โ€” server-to-server requests are not affected. In production, configure your server to allow requests from your deployed frontend domain.

WeakMap and WeakSet hold weak references to their keys/values. This means if the referenced object has no other references, the garbage collector can remove it โ€” preventing memory leaks.

  • WeakMap: Keys must be objects (not primitives). Not iterable โ€” you cannot loop over entries or check its size.
  • WeakSet: Can only hold objects. Not iterable.
  • Regular Map/Set: Hold strong references โ€” they keep objects alive as long as the collection exists.
// WeakMap โ€” common use: associating private data with objects
const privateData = new WeakMap();

class User {
  constructor(name) {
    privateData.set(this, { name });
  }
  getName() {
    return privateData.get(this).name;
  }
}

const u = new User("Sai");
console.log(u.getName()); // "Sai"
// When u is garbage-collected, the WeakMap entry is automatically freed

// Map would hold the reference and prevent GC
// WeakMap lets the GC do its job

When to use them: When you need to attach metadata to objects without preventing garbage collection. Common in caching, memoization, and tracking DOM nodes.

Memoization is an optimization technique that caches the results of expensive function calls and returns the cached result when the same inputs are seen again โ€” trading memory for speed.

// Manual memoization
function memoize(fn) {
  const cache = new Map();
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache.has(key)) {
      console.log("Cache hit!");
      return cache.get(key);
    }
    const result = fn(...args);
    cache.set(key, result);
    return result;
  };
}

function slowFibonacci(n) {
  if (n <= 1) return n;
  return slowFibonacci(n - 1) + slowFibonacci(n - 2);
}

const fastFib = memoize(slowFibonacci); // not recursive, but illustrates caching
fastFib(40); // computes
fastFib(40); // instant โ€” cache hit!

// In React โ€” useMemo caches computed values
const expensiveResult = useMemo(() => heavyComputation(data), [data]);

// useCallback caches functions
const handleClick = useCallback(() => doSomething(id), [id]);

Memoization works best for pure functions (same input โ†’ same output, no side effects). If the function has side effects, caching breaks expected behavior.

JavaScript uses automatic garbage collection โ€” the engine reclaims memory occupied by objects that are no longer reachable from the root (global scope).

Algorithm: Mark-and-Sweep. The GC starts from "roots" (global variables, call stack), marks everything reachable, then sweeps (frees) everything not marked.

// Memory is freed when there are no more references
function createUser() {
  const user = { name: "Sai" }; // allocated on heap
  return user;
}

let u = createUser();
u = null; // no more references to the object โ†’ eligible for GC

// Memory leak examples:
// 1. Global variables that grow forever
window.leak = [];
setInterval(() => window.leak.push(new Array(10000)), 100);

// 2. Detached DOM nodes
let btn = document.getElementById('myBtn');
document.body.removeChild(btn);
// btn variable still holds reference โ†’ node not GC'd
btn = null; // now GC can collect it

// 3. Closure holding large data
function setup() {
  const bigData = new Array(1000000).fill("x");
  return function() { return bigData.length; }; // bigData never freed
}

JavaScript developers don't manually free memory, but understanding reachability helps avoid common leaks โ€” especially in SPAs where components mount/unmount frequently.

All three let you explicitly set this for a function. The difference is when and how they invoke it.

function greet(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}

const user = { name: "Sai" };

// call โ€” invoke immediately, pass args individually
greet.call(user, "Hello", "!"); // "Hello, Sai!"

// apply โ€” invoke immediately, pass args as array
greet.apply(user, ["Hi", "?"]); // "Hi, Sai?"

// bind โ€” does NOT invoke, returns a new function with this bound
const greetSai = greet.bind(user, "Hey"); // args partially applied
greetSai(".");     // "Hey, Sai."
greetSai("!");     // "Hey, Sai!"

// Memory aid:
// call  = comma-separated args
// apply = array args
// bind  = doesn't call, returns new function

bind is especially useful for React class components (this.handleClick = this.handleClick.bind(this)), and for partial application โ€” pre-filling some arguments of a function.

A generator function (declared with function*) returns an iterator. Execution is paused each time yield is encountered and resumes when .next() is called. Generators can produce values lazily โ€” on demand.

function* counter(start = 0) {
  while (true) {
    yield start++;
  }
}

const gen = counter(1);
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
// Infinite sequence โ€” but only computes on demand!

// Finite generator
function* range(start, end) {
  for (let i = start; i <= end; i++) {
    yield i;
  }
}

for (const n of range(1, 5)) {
  console.log(n); // 1, 2, 3, 4, 5
}

// Async generators โ€” for streaming data
async function* streamData() {
  const chunks = await fetchChunks();
  for (const chunk of chunks) yield chunk;
}

Generators are the foundation for async/await (Babel compiles async functions to generator-based state machines). They are also useful for infinite sequences, lazy evaluation, and custom iterators.

The module pattern uses closures to create private state and expose only a public API. It was the go-to pattern before ES Modules (import/export) were introduced.

// Classic IIFE module pattern
const CartModule = (function() {
  // private โ€” not accessible outside
  let items = [];

  function addItem(item) { items.push(item); }
  function getTotal() { return items.reduce((s, i) => s + i.price, 0); }

  // public API โ€” only what we expose
  return {
    add: addItem,
    total: getTotal,
    count: () => items.length,
  };
})();

CartModule.add({ name: "Headphones", price: 49 });
console.log(CartModule.total()); // 49
console.log(CartModule.items);   // undefined โ€” private!

// Modern ES Modules (ESM) โ€” native module system
// cart.js
let items = [];
export function addItem(item) { items.push(item); }
export function getTotal() { return items.reduce((s, i) => s + i.price, 0); }

// main.js
import { addItem, getTotal } from './cart.js';

ES Modules are now the standard. Each file is automatically a module with its own scope. Use export to expose, import to consume.

The Temporal Dead Zone (TDZ) is the period between entering a block scope and the point where a let or const variable's declaration is evaluated. Accessing the variable during this period throws a ReferenceError.

// TDZ illustration
{
  // TDZ for x starts here โ†“
  console.log(x); // ReferenceError: Cannot access 'x' before initialization
  //                   โ†‘ still in TDZ
  let x = 10;     // TDZ ends here โ€” x is now initialized
  //                   โ†“
  console.log(x); // 10 โ€” safe to use
}

// var does NOT have a TDZ (it's initialized to undefined)
{
  console.log(y); // undefined โ€” no error
  var y = 10;
  console.log(y); // 10
}

// TDZ in classes
class A {
  constructor() {
    console.log(this.b); // undefined โ€” class fields init in TDZ order
  }
  b = 42; // field is in TDZ during super() call
}

The TDZ is why let and const feel safer than var โ€” they fail loudly (ReferenceError) instead of silently producing undefined. In interviews, connect the TDZ back to hoisting: let/const ARE hoisted, but they are not initialized, which creates the TDZ.

Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

Ready to ace your JavaScript interview?
Ramayai teaches the full picture โ€” from closures to cloud.

Join the Best AI Programs โ€” three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses โ†’