Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
All Practice Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools
JavaScript

Top 50 JavaScript Interview Questions

Curated questions covering closures, hoisting, promises, async/await, event loop, ES6+, prototypes, DOM, and advanced JavaScript concepts.

01

What is the difference between var, let, and const?

  • var - function-scoped, hoisted and initialized as undefined, can be re-declared.
  • let - block-scoped, hoisted but not initialized (TDZ), cannot be re-declared.
  • const - block-scoped, must be initialized, cannot be reassigned (but object properties can be mutated).
02

What is a closure in JavaScript?

A closure is a function that retains access to variables from its outer (enclosing) scope even after the outer function has returned. Used for data encapsulation, factory functions, and callbacks.

Example
function counter() {
  let count = 0;
  return () => ++count;
}
const inc = counter();
console.log(inc()); // 1
console.log(inc()); // 2
03

What is hoisting in JavaScript?

Hoisting moves declarations to the top of their scope during compilation. var declarations are hoisted and initialized as undefined. Function declarations are fully hoisted. let and const are hoisted but not initialized (Temporal Dead Zone).

04

What is the difference between == and ===?

== performs type coercion before comparison ("5" == 5 is true). === compares both value and type without coercion ("5" === 5 is false). Always prefer === to avoid unexpected type coercion bugs.

05

What is the event loop in JavaScript?

The event loop allows JavaScript (single-threaded) to handle async operations. The call stack executes synchronous code. Async callbacks go to the task queue (macrotasks) or microtask queue (Promises). The event loop moves tasks to the call stack when it is empty. Microtasks run before macrotasks.

06

What is the difference between Promise and async/await?

Both handle asynchronous operations. async/await is syntactic sugar over Promises, making async code look synchronous and easier to read. Error handling uses try/catch instead of .catch().

Example
// Promise
fetch(url).then(r => r.json()).then(data => console.log(data)).catch(console.error);

// async/await
async function getData() {
  try {
    const r = await fetch(url);
    const data = await r.json();
    console.log(data);
  } catch(e) { console.error(e); }
}
07

What is prototypal inheritance?

JavaScript objects have a prototype chain. When a property is not found on an object, JavaScript looks up the prototype chain. Objects inherit from Object.prototype by default. ES6 classes are syntactic sugar over prototypal inheritance.

08

What is the difference between call, apply, and bind?

  • call(thisArg, arg1, arg2) - invokes function immediately with given this and individual arguments.
  • apply(thisArg, [args]) - invokes function immediately with given this and arguments as array.
  • bind(thisArg, arg1) - returns a new function with this permanently bound. Does not invoke immediately.
Example
function greet(greeting) { return `${greeting}, ${this.name}`; }
const user = { name: "Alice" };
greet.call(user, "Hello");        // "Hello, Alice"
greet.apply(user, ["Hi"]);        // "Hi, Alice"
const sayHi = greet.bind(user);
sayHi("Hey");                     // "Hey, Alice"
09

What is event bubbling and event capturing?

Event bubbling - events propagate from the target element up to the root (default). Event capturing - events propagate from root down to the target. Use addEventListener(event, handler, true) for capturing. stopPropagation() stops propagation.

10

What is the difference between null and undefined?

undefined means a variable has been declared but not assigned a value. null is an intentional absence of value, explicitly assigned. typeof undefined is "undefined"; typeof null is "object" (a known JavaScript quirk).

11

What are arrow functions and how do they differ from regular functions?

  • Arrow functions do not have their own this - they inherit this from the enclosing scope.
  • Arrow functions cannot be used as constructors (no new).
  • Arrow functions do not have arguments object.
  • Arrow functions are always anonymous.
Example
const add = (a, b) => a + b;
const obj = {
  name: "Alice",
  greet: function() { return () => this.name; } // arrow inherits this
};
12

What is destructuring in JavaScript?

Destructuring extracts values from arrays or properties from objects into distinct variables.

Example
const [a, b, ...rest] = [1, 2, 3, 4];
const { name, age = 25 } = { name: "Alice" };
function greet({ name, role = "user" }) { return `${name} is ${role}`; }
13

What is the spread operator and rest parameters?

Spread (...) expands an iterable into individual elements. Rest (...) collects remaining arguments into an array.

Example
const arr = [1, 2, 3];
const copy = [...arr, 4]; // [1,2,3,4]

function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}
14

What is a Promise and what are its states?

A Promise represents an eventual value. States: pending (initial), fulfilled (resolved with value), rejected (failed with reason). Promises are immutable once settled. Use Promise.all(), Promise.race(), Promise.allSettled(), Promise.any() for multiple promises.

15

What is the difference between map, filter, and reduce?

  • map() - transforms each element, returns new array of same length.
  • filter() - returns new array with elements that pass a test.
  • reduce() - accumulates array into a single value.
Example
const nums = [1,2,3,4,5];
nums.map(x => x * 2);              // [2,4,6,8,10]
nums.filter(x => x % 2 === 0);     // [2,4]
nums.reduce((acc, x) => acc + x, 0); // 15
16

What is a WeakMap and WeakSet?

WeakMap and WeakSet hold weak references to objects - they do not prevent garbage collection. WeakMap keys must be objects. Neither is iterable. Useful for storing metadata about objects without memory leaks.

17

What is the difference between synchronous and asynchronous code?

Synchronous code executes line by line, blocking until each operation completes. Asynchronous code initiates an operation and continues executing other code while waiting for the result (via callbacks, Promises, or async/await).

18

What are generators in JavaScript?

Generators are functions that can pause and resume execution using yield. They return an iterator. Useful for lazy evaluation, infinite sequences, and async flow control.

Example
function* range(start, end) {
  for (let i = start; i <= end; i++) yield i;
}
const gen = range(1, 3);
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
19

What is the difference between localStorage and sessionStorage?

Both are Web Storage APIs. localStorage persists until explicitly cleared - survives browser restarts. sessionStorage is cleared when the browser tab is closed. Both store ~5MB of string data, are synchronous, and are never sent to the server.

20

What is a Symbol in JavaScript?

Symbol is a primitive type that creates unique identifiers. Every Symbol() call returns a unique value. Used as object property keys to avoid name collisions, especially in libraries and frameworks.

Example
const id = Symbol("id");
const user = { [id]: 42, name: "Alice" };
console.log(user[id]);          // 42
console.log(Object.keys(user)); // ["name"] - Symbol not enumerable
21

What is optional chaining (?.) and nullish coalescing (??)?

  • Optional chaining (?.) - safely accesses nested properties without throwing if an intermediate value is null/undefined.
  • Nullish coalescing (??) - returns right-hand side only when left side is null or undefined (unlike || which also triggers on 0 and "").
Example
const city = user?.address?.city;
const name = user.name ?? "Anonymous";
const count = data.count ?? 0; // 0 is valid - ?? will not replace it
22

What is the difference between deep copy and shallow copy?

Shallow copy copies only the top-level properties; nested objects are still referenced. Deep copy creates completely independent copies of all nested objects.

Example
// Shallow
const copy = { ...original };

// Deep (modern, recommended)
const deep = structuredClone(original);

// Deep (legacy - loses functions/undefined)
const deep2 = JSON.parse(JSON.stringify(original));
23

What is event delegation?

Event delegation attaches a single event listener to a parent element instead of multiple listeners on children. It uses event bubbling - the parent catches events from children. More efficient for dynamic lists.

Example
document.querySelector("#list").addEventListener("click", (e) => {
  if (e.target.matches("li")) console.log(e.target.textContent);
});
24

What is the difference between Object.freeze() and Object.seal()?

  • Object.freeze() - prevents adding, removing, or modifying properties. Object is fully immutable.
  • Object.seal() - prevents adding or removing properties, but existing properties can still be modified.
25

What is a Proxy in JavaScript?

Proxy wraps an object and intercepts fundamental operations (get, set, delete, etc.) via handler traps. Used for validation, logging, and reactive data systems (Vue 3 uses Proxy for reactivity).

Example
const handler = {
  get(target, key) {
    return key in target ? target[key] : `${key} not found`;
  },
  set(target, key, value) {
    if (typeof value !== "number") throw new TypeError("Numbers only");
    target[key] = value;
    return true;
  }
};
const obj = new Proxy({}, handler);
26

What is the difference between for...in and for...of?

  • for...in - iterates over enumerable property keys of an object (including inherited ones).
  • for...of - iterates over iterable values (arrays, strings, Maps, Sets). Does not work on plain objects.
Example
const arr = [10, 20, 30];
for (const i in arr) console.log(i); // "0", "1", "2" (keys)
for (const v of arr) console.log(v); // 10, 20, 30 (values)
27

What is memoization?

Memoization caches the results of expensive function calls and returns the cached result when the same inputs occur again. It trades memory for speed.

Example
function memoize(fn) {
  const cache = new Map();
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const result = fn.apply(this, args);
    cache.set(key, result);
    return result;
  };
}
28

What is the difference between Map and Object?

  • Map - keys can be any type; maintains insertion order; has size property; iterable directly.
  • Object - keys are strings or Symbols only; no guaranteed order for non-string keys.
  • Use Map when keys are non-strings, order matters, or you need frequent add/delete operations.
Example
const map = new Map();
map.set({ id: 1 }, "user");
map.set(42, "number key");
console.log(map.size); // 2
29

What is the difference between Set and Array?

Set stores unique values of any type - duplicates are automatically ignored. Arrays allow duplicates. Set has O(1) lookup with has(); Array has O(n) with includes(). Use Set for deduplication and fast membership checks.

Example
const set = new Set([1, 2, 2, 3, 3]);
console.log([...set]); // [1, 2, 3]

const unique = [...new Set(array)]; // fast deduplication
30

What is the difference between ES Modules and CommonJS?

  • CommonJS (require/module.exports) - synchronous; used in Node.js; loaded at runtime.
  • ES Modules (import/export) - asynchronous; static analysis; tree-shakeable; used in browsers and modern Node.js.
  • ES Modules are the standard. Use import/export in new projects.
Example
// ES Module
export const add = (a, b) => a + b;
import { add } from "./math.js";

// CommonJS
module.exports = { add };
const { add } = require("./math");
31

What is the difference between Promise.all, Promise.race, Promise.allSettled, and Promise.any?

  • Promise.all - resolves when ALL promises resolve; rejects immediately if any rejects.
  • Promise.race - resolves/rejects as soon as the FIRST promise settles.
  • Promise.allSettled - waits for ALL promises to settle; never rejects. Best for batch operations.
  • Promise.any - resolves as soon as ANY promise resolves; rejects only if ALL reject.
Example
const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]);
const results = await Promise.allSettled([p1, p2, p3]);
32

What is the Temporal Dead Zone (TDZ)?

The TDZ is the period between entering a scope and the point where a let or const variable is declared. Accessing the variable in this zone throws a ReferenceError. var does not have a TDZ.

Example
console.log(x); // ReferenceError: Cannot access before initialization
let x = 5;

console.log(y); // undefined (var has no TDZ)
var y = 5;
33

What is currying in JavaScript?

Currying transforms a function with multiple arguments into a sequence of functions each taking a single argument. Enables partial application and function composition.

Example
const multiply = (a) => (b) => a * b;
const double = multiply(2);
console.log(double(5));  // 10
console.log(double(10)); // 20
34

What is the difference between Object.keys(), Object.values(), and Object.entries()?

  • Object.keys(obj) - returns array of own enumerable property names.
  • Object.values(obj) - returns array of own enumerable property values.
  • Object.entries(obj) - returns array of [key, value] pairs. Useful for iteration and converting to Map.
Example
const user = { name: "Alice", age: 30 };
Object.keys(user);    // ["name", "age"]
Object.values(user);  // ["Alice", 30]
Object.entries(user); // [["name","Alice"], ["age",30]]
35

What is the difference between slice() and splice()?

  • slice(start, end) - returns a shallow copy of a portion of an array. Does NOT modify the original.
  • splice(start, deleteCount, ...items) - modifies the original array by removing/replacing/adding elements.
Example
const arr = [1, 2, 3, 4, 5];
arr.slice(1, 3);         // [2, 3] - original unchanged
arr.splice(1, 2, 9, 9); // arr becomes [1,9,9,4,5]
36

What is the Reflect API?

Reflect is a built-in object that provides methods for interceptable JavaScript operations - the same operations that Proxy traps intercept. It makes it easier to call default behavior inside Proxy handlers.

Example
const handler = {
  set(target, key, value, receiver) {
    console.log(`Setting ${key} = ${value}`);
    return Reflect.set(target, key, value, receiver);
  }
};
const obj = new Proxy({}, handler);
37

What is the difference between throw and Promise.reject()?

Inside an async function, throw and return Promise.reject() are equivalent - both cause the returned Promise to reject. Outside async functions, throw is synchronous and must be caught with try/catch synchronously.

Example
async function fetchData() {
  throw new Error("Failed"); // same as Promise.reject(new Error("Failed"))
}
try {
  await fetchData();
} catch (e) {
  console.error(e.message); // "Failed"
}
38

What is Array.from() and when do you use it?

Array.from() converts any iterable or array-like object to an array. It accepts an optional mapping function as the second argument.

Example
Array.from({ length: 5 }, (_, i) => i + 1); // [1,2,3,4,5]
Array.from("hello");  // ["h","e","l","l","o"]
Array.from(new Set([1,2,2,3])); // [1,2,3]
39

What is the difference between Object.assign() and the spread operator for objects?

  • Both perform a shallow merge of objects.
  • Object.assign(target, ...sources) - mutates the target object and returns it.
  • Spread ({ ...obj1, ...obj2 }) - creates a new object without mutation. Preferred in modern code.
Example
const merged = Object.assign({}, defaults, overrides); // mutates {}
const merged2 = { ...defaults, ...overrides }; // new object
40

What is the difference between a microtask and a macrotask?

  • Macrotasks (task queue) - setTimeout, setInterval, setImmediate, I/O callbacks. One macrotask runs per event loop iteration.
  • Microtasks (microtask queue) - Promise callbacks (.then/.catch/.finally), queueMicrotask(), MutationObserver. ALL microtasks run before the next macrotask.
Example
console.log("1");
setTimeout(() => console.log("2"), 0); // macrotask
Promise.resolve().then(() => console.log("3")); // microtask
console.log("4");
// Output: 1, 4, 3, 2
41

What is the difference between innerHTML, textContent, and innerText?

  • innerHTML - gets/sets HTML markup including tags. Risk of XSS if used with user input.
  • textContent - gets/sets raw text content including hidden elements. No HTML parsing. Faster.
  • innerText - gets/sets visible text only (respects CSS visibility). Triggers reflow.
Example
el.textContent = userInput; // safe - no XSS risk
el.innerHTML = userInput;   // DANGEROUS with untrusted input
42

What is the difference between setTimeout(fn, 0) and Promise.resolve().then(fn)?

Both schedule code to run asynchronously, but at different priority levels. Promise.resolve().then(fn) schedules a microtask which runs before the next macrotask. setTimeout(fn, 0) schedules a macrotask which runs after all microtasks are cleared.

43

What is the AbortController API?

AbortController allows you to cancel async operations like fetch requests. Create an AbortController, pass its signal to fetch, and call abort() to cancel.

Example
const controller = new AbortController();
const { signal } = controller;

fetch("/api/data", { signal })
  .then(r => r.json())
  .catch(e => {
    if (e.name === "AbortError") console.log("Request cancelled");
  });

controller.abort(); // cancel the request
44

What is the difference between Object.create() and class/constructor functions?

  • Object.create(proto) - creates a new object with the specified prototype. Direct prototype chain control.
  • Constructor functions (new Fn()) - creates an object with Fn.prototype as its prototype.
  • ES6 class - syntactic sugar over constructor functions. Cleaner syntax, same prototype mechanism.
Example
// Object.create
const animal = { speak() { return "..."; } };
const dog = Object.create(animal);

// Class
class Dog extends Animal { speak() { return "Woof"; } }
45

What is the difference between Array.isArray() and instanceof Array?

Array.isArray() is the reliable way to check if a value is an array. instanceof Array can fail across different iframes/realms because each frame has its own Array constructor. Array.isArray() works correctly in all contexts.

Example
Array.isArray([1,2,3]);       // true - always reliable
[1,2,3] instanceof Array;     // true - but fails cross-realm
46

What is the difference between structuredClone() and JSON.parse(JSON.stringify())?

  • JSON.parse(JSON.stringify()) - loses undefined, functions, Date objects (converted to strings), Map, Set, circular references throw.
  • structuredClone() - handles Date, Map, Set, ArrayBuffer, circular references. Does not clone functions.
  • Use structuredClone() for modern deep cloning.
Example
const date = new Date();
JSON.parse(JSON.stringify({ date })).date; // string, not Date
structuredClone({ date }).date;            // proper Date object
47

What is the difference between function declaration and function expression?

  • Function declaration - hoisted completely; can be called before it appears in code.
  • Function expression - not hoisted (only the variable is hoisted as undefined for var).
  • Named function expressions have the name available inside the function for recursion.
Example
// Declaration - hoisted
sayHello(); // works
function sayHello() { return "Hello"; }

// Expression - not hoisted
greet(); // TypeError: greet is not a function
var greet = function() { return "Hi"; };
48

What is the difference between Object.defineProperty() and direct assignment?

Direct assignment creates a property that is writable, enumerable, and configurable by default. Object.defineProperty() gives full control over these descriptors.

Example
Object.defineProperty(obj, "id", {
  value: 42,
  writable: false,    // cannot reassign
  enumerable: false,  // hidden from for...in and Object.keys()
  configurable: false // cannot delete or redefine
});
49

What is the difference between debounce and throttle?

Both limit how often a function executes, but differently.

  • debounce — delays execution until after a specified time has passed since the last call. Use for search input, resize handlers.
  • throttle — ensures a function executes at most once per specified time interval. Use for scroll events, API rate limiting.
Example
// Debounce: fires 300ms after user stops typing
const debounced = debounce((val) => search(val), 300);

// Throttle: fires at most once every 300ms while scrolling
const throttled = throttle(() => updatePosition(), 300);
50

What is the difference between composition and inheritance in JavaScript?

  • Inheritance (is-a) — a class extends another, inheriting its methods. Can lead to tight coupling and fragile base class problems.
  • Composition (has-a) — objects are built by combining smaller, focused functions or objects. More flexible and testable.
  • Prefer composition over inheritance for most cases in JavaScript.
Example
// Inheritance
class Animal { speak() {} }
class Dog extends Animal { fetch() {} }

// Composition
const canSpeak = (state) => ({ speak: () => console.log(state.sound) });
const canFetch = (state) => ({ fetch: () => console.log("fetching") });
const createDog = (sound) => {
  const state = { sound };
  return { ...canSpeak(state), ...canFetch(state) };
};

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.