Top 100 Javascript Interview Questions

Top 100 JavaScript Interview Questions and Answers (2025) – Ace Your Next Tech Interview!

 

JavaScript is the backbone of modern web development, powering interactive websites, dynamic applications, and cutting-edge technologies.

Whether you’re a beginner preparing for your first job interview or an experienced developer brushing up on advanced JavaScript concepts, this comprehensive guide covers the most frequently asked JavaScript interview questions in 2025.

In this post, you’ll find:
✅ Basic to Advanced JavaScript Questions
✅ Code Examples & Detailed Explanations
✅ ES6+, Async Programming, Closures, and More!

Master these JavaScript interview questions and boost your chances of landing your dream job at top tech companies like Google, Amazon, Meta, and more! 🚀


1. What are the different data types in JavaScript?

JavaScript has 8 primitive data types and 1 non-primitive (object) type.

Primitive Types:

  • String: Represents text. Example: "Hello"
  • Number: Represents integers & floating-point numbers. Example: 42, 3.14
  • Boolean: Represents true or false. Example: true, false
  • BigInt: For very large numbers. Example: BigInt(12345678901234567890)
  • Undefined: A variable declared but not assigned a value. Example: let x;
  • Null: Represents an empty or unknown value. Example: let y = null;
  • Symbol: Represents unique identifiers. Example: let sym = Symbol("id");
  • Undefined: A variable declared but not assigned a value.

Non-Primitive Type:

  • Object: A collection of key-value pairs. Example:
    let person = { name: "John", age: 30 };
    

2. Explain the difference between let, const, and var.

KeywordScopeReassignmentHoisting
varFunction-scopedAllowedHoisted (initialized as undefined)
letBlock-scopedAllowedHoisted (but not initialized)
constBlock-scopedNot allowedHoisted (but not initialized)

Example:

var a = 10;
let b = 20;
const c = 30;

function test() {
  if (true) {
    var x = 100; // function-scoped
    let y = 200; // block-scoped
    const z = 300; // block-scoped
  }
  console.log(x); // ✅ Works
  // console.log(y); // ❌ Error (y is block-scoped)
  // console.log(z); // ❌ Error (z is block-scoped)
}
test();

3. What is the difference between == and === in JavaScript?

  • == (loose equality) compares values after type conversion.
  • === (strict equality) compares both value and type.

Example:

console.log(5 == "5");  // true  (type coercion happens)
console.log(5 === "5"); // false (different types)
console.log(null == undefined);  // true
console.log(null === undefined); // false

4. What is a closure in JavaScript? Provide an example.

A closure is a function that retains access to its outer function’s variables even after the outer function has executed.

Example:

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

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

Even though outer() has finished executing, inner() still has access to count.


5. How does the JavaScript event loop work?

The event loop handles asynchronous operations by managing the call stack and task queue.

Working:

  1. Synchronous code runs first (Call Stack).
  2. Asynchronous code (like setTimeout, API calls) is sent to the Web APIs.
  3. Once completed, it moves to the Callback Queue.
  4. The event loop moves callbacks into the Call Stack only when it’s empty.

Example:

console.log("Start");

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

console.log("End");

// Output:
// Start
// End
// Timeout (executed last due to event loop)

6. What is the difference between null and undefined?

  • null: Explicitly assigned to a variable to indicate “no value”.
  • undefined: Automatically assigned to variables that have not been initialized.

Example:

let a; // undefined
let b = null;

console.log(a); // undefined
console.log(b); // null
console.log(typeof a); // "undefined"
console.log(typeof b); // "object" (JavaScript quirk)

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

Arrow functions are a shorter syntax for writing functions and do not bind their own this.

Example:

const regularFunc = function() {
  console.log(this); // Depends on how it’s called
};

const arrowFunc = () => {
  console.log(this); // Lexical `this` (inherits from parent scope)
};

regularFunc();
arrowFunc();

Arrow functions:

  • Cannot be used as constructors.
  • Do not have their own this (inherits from surrounding scope).
  • Do not have a arguments object.

8. Explain this keyword in JavaScript and how it behaves in different contexts.

this refers to the object that calls the function.

Scenarios:

  1. Global Scope (this is window in browsers):
    console.log(this); // window (in browser)
    
  2. Inside a function (this depends on strict mode):
    function show() {
      console.log(this);
    }
    show(); // window (or undefined in strict mode)
    
  3. Inside an object (this refers to the object):
    const obj = {
      name: "John",
      show() {
        console.log(this.name);
      }
    };
    obj.show(); // John
    
  4. Arrow functions (this is inherited from parent scope):
    const obj = {
      name: "John",
      show: () => console.log(this.name) // `this` is NOT obj, it's global
    };
    obj.show(); // undefined
    

9. What is the difference between synchronous and asynchronous programming?

  • Synchronous: Code executes line by line, blocking further execution until it’s finished.
  • Asynchronous: Code does not block, allowing execution to continue while waiting.

Example:

console.log("Start");

setTimeout(() => console.log("Async operation"), 2000);

console.log("End");

// Output:
// Start
// End
// (After 2 sec) Async operation

10. What are promises in JavaScript? How do they work?

A promise is an object that represents the eventual completion or failure of an asynchronous operation.

States of a Promise:

  1. Pending – Initial state.
  2. Resolved (Fulfilled) – Operation was successful.
  3. Rejected – Operation failed.

Example:

let myPromise = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Success!"), 2000);
});

myPromise.then(result => console.log(result))
         .catch(error => console.log(error));

// Output after 2 sec: Success!

 


11. What is the difference between function declaration and function expression?

TypeHoistingSyntaxExample
Function DeclarationHoistedfunction func() {}✅ Accessible before definition
Function ExpressionNot hoistedconst func = function() {}❌ Not accessible before definition

Example:

sayHello(); // ✅ Works (hoisted)
function sayHello() {
  console.log("Hello!");
}

sayHi(); // ❌ Error (not hoisted)
const sayHi = function() {
  console.log("Hi!");
};

12. What is an Immediately Invoked Function Expression (IIFE)?

An IIFE is a function that executes immediately after being defined.

Example:

(function() {
  console.log("IIFE executed!");
})(); 
// Output: IIFE executed!

Why use IIFE?

  • Avoid polluting the global scope.
  • Create private variables.

13. What is the difference between shallow and deep copy in JavaScript?

TypeCopies Nested Objects?Example
Shallow Copy❌ NoObject.assign({}, obj) or spread operator
Deep Copy✅ YesJSON.parse(JSON.stringify(obj)) or structuredClone(obj)

Example:

let obj = { a: 1, b: { c: 2 } };
let shallow = { ...obj };
shallow.b.c = 42; // Modifies original object!

let deep = JSON.parse(JSON.stringify(obj));
deep.b.c = 99; // Original object remains unchanged!

14. What are template literals in JavaScript?

Template literals use backticks `, allowing multi-line strings and embedded expressions.

Example:

const name = "John";
console.log(`Hello, ${name}!`); // Hello, John!

const multiLine = `Line 1
Line 2`;
console.log(multiLine);

15. What is destructuring in JavaScript?

Destructuring allows extracting values from arrays or objects.

Example:

// Array Destructuring
const arr = [1, 2, 3];
const [first, second] = arr; // first = 1, second = 2

// Object Destructuring
const person = { name: "Alice", age: 25 };
const { name, age } = person;
console.log(name, age); // Alice 25

16. What is the difference between map(), filter(), and reduce()?

MethodPurposeExample
map()Transforms each element[1, 2, 3].map(x => x * 2)[2, 4, 6]
filter()Filters elements[1, 2, 3].filter(x => x > 1)[2, 3]
reduce()Aggregates values[1, 2, 3].reduce((sum, x) => sum + x, 0)6

Example:

const numbers = [1, 2, 3, 4];

// Double each number
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]

// Filter even numbers
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]

// Sum all numbers
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 10

17. What is the difference between forEach() and map()?

MethodReturns a new array?Can modify original array?Use Case
forEach()❌ No✅ YesSide effects (e.g., logging)
map()✅ Yes❌ NoTransforming data

Example:

const arr = [1, 2, 3];

// Using forEach
arr.forEach((num, index, array) => {
  array[index] = num * 2; // Modifies original array
});
console.log(arr); // [2, 4, 6]

// Using map
const doubled = arr.map(num => num * 2);
console.log(doubled); // [4, 8, 12] (Original array remains unchanged)

18. What is the spread operator (...) in JavaScript?

The spread operator expands an iterable (array, object, etc.).

Example:

// Copy an array
const arr1 = [1, 2, 3];
const arr2 = [...arr1];
console.log(arr2); // [1, 2, 3]

// Merge objects
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3 };
const merged = { ...obj1, ...obj2 };
console.log(merged); // { a: 1, b: 2, c: 3 }

19. What is the rest operator (...) in JavaScript?

The rest operator collects multiple elements into an array.

Example:

function sum(...numbers) {
  return numbers.reduce((acc, num) => acc + num, 0);
}

console.log(sum(1, 2, 3, 4)); // 10
  • ...spread expands values.
  • ...rest gathers values.

20. What is object destructuring and how does it work?

Object destructuring allows extracting properties from objects.

Example:

const user = { name: "Alice", age: 30, city: "NY" };

// Destructuring with renaming
const { name: userName, age } = user;
console.log(userName, age); // Alice 30

// Default values
const { country = "USA" } = user;
console.log(country); // USA

 


21. What is the difference between function parameters and arguments?

  • Parameters are placeholders defined in the function declaration.
  • Arguments are actual values passed when calling the function.

Example:

function greet(name) { // 'name' is a parameter
  console.log(`Hello, ${name}!`);
}
greet("Alice"); // "Alice" is an argument

22. What are default parameters in JavaScript?

Default parameters allow you to set a fallback value if no argument is provided.

Example:

function greet(name = "Guest") {
  console.log(`Hello, ${name}!`);
}
greet(); // Hello, Guest!
greet("Alice"); // Hello, Alice!

23. What is the difference between call(), apply(), and bind()?

MethodExecutes Immediately?Pass ArgumentsReturns New Function?
call()✅ YesComma-separated❌ No
apply()✅ YesArray❌ No
bind()❌ NoComma-separated✅ Yes

Example:

const person = { name: "Alice" };

function greet(age) {
  console.log(`Hello, my name is ${this.name} and I'm ${age} years old.`);
}

greet.call(person, 25);  // Using call
greet.apply(person, [25]);  // Using apply

const boundGreet = greet.bind(person, 25); // Using bind
boundGreet(); // Executes later

24. What is event delegation in JavaScript?

Event delegation allows a parent element to handle events for its child elements.

Example:

document.getElementById("parent").addEventListener("click", function(event) {
  if (event.target.tagName === "BUTTON") {
    console.log("Button clicked:", event.target.textContent);
  }
});

Why use event delegation?

  • Improves performance for dynamically added elements.
  • Reduces memory usage.

25. What is the difference between localStorage, sessionStorage, and cookies?

Storage TypeExpirySize LimitAccessible by Server?
localStorageNever expires~5MB❌ No
sessionStorageExpires on tab close~5MB❌ No
CookiesCustom expiry~4KB✅ Yes

Example:

// localStorage
localStorage.setItem("user", "Alice");
console.log(localStorage.getItem("user")); // Alice

// sessionStorage
sessionStorage.setItem("sessionKey", "12345");
console.log(sessionStorage.getItem("sessionKey")); // 12345

// Cookies
document.cookie = "username=Alice; expires=Fri, 31 Dec 2025 12:00:00 UTC";

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

PropertyIncludes HTML Tags?Reads Hidden Elements?
innerHTML✅ Yes✅ Yes
innerText❌ No❌ No
textContent❌ No✅ Yes

Example:

const div = document.getElementById("myDiv");
console.log(div.innerHTML);  // Returns "<b>Bold</b> text"
console.log(div.innerText);  // Returns "Bold text" (ignores hidden elements)
console.log(div.textContent); // Returns "Bold text" (includes hidden elements)

27. What is the difference between setTimeout() and setInterval()?

FunctionPurposeExecution
setTimeoutDelays executionRuns once after delay
setIntervalRepeats executionRuns repeatedly at intervals

Example:

// setTimeout: Executes once after 2 seconds
setTimeout(() => console.log("Hello after 2 seconds"), 2000);

// setInterval: Executes every 2 seconds
const intervalId = setInterval(() => console.log("Repeating..."), 2000);

// Stop setInterval after 6 seconds
setTimeout(() => clearInterval(intervalId), 6000);

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

MethodModifies Original Array?Returns New Array?Use Case
slice()❌ No✅ YesExtracts elements
splice()✅ Yes❌ NoAdds/removes elements

Example:

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

// slice(start, end) - Extracts elements
console.log(arr.slice(1, 3)); // [2, 3]

// splice(start, deleteCount, items...) - Modifies array
arr.splice(1, 2, 99, 100);
console.log(arr); // [1, 99, 100, 4, 5]

29. What is the typeof operator in JavaScript?

typeof returns the data type of a variable.

Example:

console.log(typeof "Hello"); // string
console.log(typeof 42); // number
console.log(typeof true); // boolean
console.log(typeof {}); // object
console.log(typeof null); // object (JavaScript quirk)
console.log(typeof undefined); // undefined
console.log(typeof function() {}); // function

30. What is a higher-order function in JavaScript?

A higher-order function is a function that takes another function as an argument or returns a function.

Example:

function higherOrder(func) {
  return function(name) {
    console.log("Hello, " + name);
    func();
  };
}

function greet() {
  console.log("Welcome!");
}

const newFunc = higherOrder(greet);
newFunc("Alice");

// Output:
// Hello, Alice
// Welcome!

Common higher-order functions:

  • map(), filter(), reduce()
  • setTimeout(), setInterval()
  • Custom function wrappers

 


31. What is currying in JavaScript?

Currying transforms a function with multiple arguments into a series of functions that take one argument each.

Example:

function curry(a) {
  return function(b) {
    return function(c) {
      return a + b + c;
    };
  };
}

console.log(curry(1)(2)(3)); // 6

Benefits of Currying:

  • Reusability
  • Function composition
  • Avoids passing the same argument multiple times

32. What is the difference between == and === in JavaScript?

OperatorType ConversionExample
==✅ Yes (Loose equality)"5" == 5true
===❌ No (Strict equality)"5" === 5false

Example:

console.log(5 == "5"); // true (type conversion)
console.log(5 === "5"); // false (strict comparison)

Best practice: Always use === to avoid unexpected type coercion.


33. What are arrow functions in JavaScript?

Arrow functions provide a concise syntax for writing functions.

Example:

// Regular function
function add(a, b) {
  return a + b;
}

// Arrow function
const addArrow = (a, b) => a + b;

console.log(addArrow(2, 3)); // 5

Key Differences:

  • No this binding (inherits from the surrounding scope)
  • Cannot be used as constructors
  • Implicit return for single expressions

34. What is this in JavaScript?

this refers to the execution context of a function.

Example:

const person = {
  name: "Alice",
  greet() {
    console.log(`Hello, ${this.name}`);
  }
};
person.greet(); // Hello, Alice

Key Rules:

  • Global scope: this refers to the global object (window in browsers, global in Node.js).
  • Inside an object method: this refers to the object.
  • Arrow functions: this is inherited from the surrounding scope.

35. What is the purpose of new in JavaScript?

new is used to create an instance of an object from a constructor function.

Example:

function Person(name) {
  this.name = name;
}

const p1 = new Person("Alice");
console.log(p1.name); // Alice

What happens when using new?

  1. Creates a new empty object.
  2. Sets this to the new object.
  3. Returns the object.

36. What is prototypal inheritance in JavaScript?

Objects in JavaScript inherit properties from a prototype.

Example:

const person = {
  greet() {
    console.log("Hello!");
  }
};

const student = Object.create(person);
student.greet(); // Hello!

Key Points:

  • Every object has a prototype.
  • The prototype chain allows property inheritance.

37. What is the difference between Object.create() and class inheritance?

MethodInheritance TypeExample
Object.create()Prototype-basedObject.create(proto)
classES6 class-basedclass Child extends Parent {}

Example:

// Object.create()
const animal = { speak() { console.log("Animal sound"); } };
const dog = Object.create(animal);
dog.speak(); // Animal sound

// Class Inheritance
class Animal {
  speak() { console.log("Animal sound"); }
}
class Dog extends Animal {}
const pet = new Dog();
pet.speak(); // Animal sound

38. What is call, apply, and bind used for?

call(), apply(), and bind() change the this context of a function.

Example:

const person = { name: "Alice" };
function greet(age) {
  console.log(`Hello, my name is ${this.name} and I'm ${age} years old.`);
}

greet.call(person, 25);  // Hello, my name is Alice and I'm 25 years old.
greet.apply(person, [25]);  // Same as call, but uses an array
const boundGreet = greet.bind(person, 25);
boundGreet(); // Binds `this` permanently

39. What is the difference between synchronous and asynchronous JavaScript?

TypeExecutionExample
SynchronousRuns line by lineconsole.log("First"); console.log("Second");
AsynchronousRuns in the backgroundsetTimeout(() => console.log("Later"), 1000);

Example:

console.log("Start");

setTimeout(() => {
  console.log("Async task");
}, 1000);

console.log("End");

// Output:
// Start
// End
// Async task (after 1 second)

Asynchronous code prevents blocking and improves performance.


40. What is a promise in JavaScript?

A promise represents a value that may be available now, later, or never.

Example:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Data received"), 2000);
});

myPromise.then(data => console.log(data)); // Data received (after 2 sec)

Promise states:

  • Pending → Initial state
  • Fulfilled → Success (resolve())
  • Rejected → Error (reject())

 


41. What are async and await in JavaScript?

async and await simplify working with promises by making asynchronous code look synchronous.

Example:

async function fetchData() {
  return "Data received";
}

fetchData().then(console.log); // Data received

Using await with a promise:

async function getData() {
  let response = await new Promise(resolve => setTimeout(() => resolve("Fetched Data"), 2000));
  console.log(response);
}

getData(); // Prints "Fetched Data" after 2 seconds

Key Benefits:

  • Cleaner syntax than .then()
  • Avoids callback hell
  • Easier error handling with try...catch

42. What is the difference between microtasks and macrotasks?

JavaScript handles asynchronous tasks in two queues:

  • Microtasks (Higher Priority) → Promises, MutationObserver
  • Macrotasks (Lower Priority) → setTimeout(), setInterval(), setImmediate()

Example:

console.log("Start");

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

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

console.log("End");

// Output:
// Start
// End
// Microtask
// Macrotask

Key takeaway: Microtasks execute before macrotasks in the event loop.


43. What is debouncing in JavaScript?

Debouncing ensures a function runs only after a delay following the last event trigger.

Example:

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

const onResize = debounce(() => console.log("Resized!"), 500);

window.addEventListener("resize", onResize);

Use case: Optimizing input fields, window resizing, and search bars.


44. What is throttling in JavaScript?

Throttling ensures a function runs at most once in a specified time interval.

Example:

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

const onScroll = throttle(() => console.log("Scrolled!"), 1000);

window.addEventListener("scroll", onScroll);

Use case: Optimizing scroll, resize, and mousemove events.


45. What is the difference between deep copy and shallow copy?

Copy TypeChanges Reflect in Original?Methods
Shallow Copy✅ Yes (for objects inside)Object.assign(), Spread ({...})
Deep Copy❌ NoJSON.parse(JSON.stringify(obj)), structuredClone()

Example:

let obj = { a: 1, b: { c: 2 } };

// Shallow copy
let shallow = { ...obj };
shallow.b.c = 42; 
console.log(obj.b.c); // 42 (changed)

// Deep copy
let deep = JSON.parse(JSON.stringify(obj));
deep.b.c = 99;
console.log(obj.b.c); // 42 (unchanged)

46. What are generators in JavaScript?

A generator function (function*) can pause and resume execution using yield.

Example:

function* generatorFunc() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = generatorFunc();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3

Use case: Iterating over large data sets, asynchronous programming.


47. What is a closure in JavaScript?

A closure is a function that retains access to its parent scope even after the parent function has executed.

Example:

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

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

Use cases:

  • Data encapsulation
  • Creating private variables
  • Memoization

48. What is memoization in JavaScript?

Memoization is an optimization technique that stores the results of expensive function calls.

Example:

function memoize(fn) {
  let cache = {};
  return function (n) {
    if (cache[n] !== undefined) {
      return cache[n]; // Return cached result
    }
    cache[n] = fn(n); // Compute and store result
    return cache[n];
  };
}

const factorial = memoize(n => (n <= 1 ? 1 : n * factorial(n - 1)));

console.log(factorial(5)); // 120 (calculated)
console.log(factorial(5)); // 120 (cached)

Use case: Speeding up recursive calculations like Fibonacci, factorial.


49. What is the event loop in JavaScript?

The event loop manages asynchronous tasks by executing microtasks before macrotasks.

Example:

console.log("Start");

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

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

console.log("End");

// Output:
// Start
// End
// Microtask
// Macrotask

Key concepts:

  • Call stack → Handles synchronous code
  • Task queue → Handles asynchronous code
  • Microtasks execute before macrotasks

50. What is the difference between null and undefined?

ValueMeaningType
nullEmpty or intentional absence of valueObject
undefinedVariable declared but not assignedUndefined

Example:

let x;
console.log(x); // undefined

let y = null;
console.log(y); // null

Key Differences:

  • null is assigned intentionally.
  • undefined is default when no value is assigned.

 


51. What is the difference between map(), forEach(), filter(), and reduce()?

MethodReturns a New Array?Purpose
map()✅ YesTransforms elements
forEach()❌ NoIterates over elements
filter()✅ YesFilters elements based on a condition
reduce()❌ NoReduces array to a single value

Example:

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

// map()
const squared = numbers.map(n => n * n);
console.log(squared); // [1, 4, 9, 16, 25]

// forEach()
numbers.forEach(n => console.log(n * 2)); // Prints: 2, 4, 6, 8, 10

// filter()
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]

// reduce()
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum); // 15

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

MethodModifies Original Array?Returns a New Array?Purpose
slice(start, end)❌ No✅ YesExtracts part of an array
splice(start, deleteCount, ...items)✅ Yes❌ NoRemoves or replaces elements

Example:

const arr = [1, 2, 3, 4, 5];

console.log(arr.slice(1, 4)); // [2, 3, 4] (original array unchanged)

arr.splice(1, 2, 99); 
console.log(arr); // [1, 99, 4, 5] (original array modified)

53. How to remove duplicates from an array?

Example using Set:

const arr = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(arr)];
console.log(unique); // [1, 2, 3, 4, 5]

Example using filter():

const uniqueArr = arr.filter((value, index, self) => self.indexOf(value) === index);
console.log(uniqueArr); // [1, 2, 3, 4, 5]

54. What is destructuring in JavaScript?

Destructuring allows extracting values from arrays or objects.

Example with Arrays:

const [a, b] = [10, 20];
console.log(a, b); // 10, 20

Example with Objects:

const person = { name: "Alice", age: 25 };
const { name, age } = person;
console.log(name, age); // Alice, 25

55. What is the difference between localStorage, sessionStorage, and cookies?

Storage TypeExpirationSize LimitAccessible by Server?
localStorageNever (until manually cleared)5MB❌ No
sessionStorageUntil the session ends (browser closed)5MB❌ No
cookiesSet manually (default: session-based)4KB✅ Yes

Example of localStorage:

localStorage.setItem("name", "Alice");
console.log(localStorage.getItem("name")); // Alice

56. How do you check if an object is empty?

Example using Object.keys():

const obj = {};
console.log(Object.keys(obj).length === 0); // true

Example using JSON.stringify():

console.log(JSON.stringify(obj) === "{}"); // true

57. What is the difference between function declaration and function expression?

Function TypeHoisted?Example
Function Declaration✅ Yesfunction greet() {}
Function Expression❌ Noconst greet = function() {}

Example:

console.log(sayHello()); // Works

function sayHello() {
  return "Hello!";
}

console.log(sayHi()); // Error

const sayHi = function () {
  return "Hi!";
};

Function expressions are not hoisted, unlike function declarations.


58. How do you deep clone an object?

Using structuredClone() (Recommended):

const obj = { a: 1, b: { c: 2 } };
const clone = structuredClone(obj);
console.log(clone); // { a: 1, b: { c: 2 } }

Using JSON.parse(JSON.stringify()):

const deepClone = JSON.parse(JSON.stringify(obj));

⚠️ Limitations:

  • Does not work with functions, undefined, or special objects.

Using recursion for deep cloning:

function deepClone(obj) {
  if (typeof obj !== "object" || obj === null) return obj;
  let copy = Array.isArray(obj) ? [] : {};
  for (let key in obj) {
    copy[key] = deepClone(obj[key]);
  }
  return copy;
}

59. What is the difference between bind(), call(), and apply()?

MethodReturns a New Function?Arguments
bind()✅ YesPasses arguments partially
call()❌ NoPasses arguments one by one
apply()❌ NoPasses arguments as an array

Example:

const obj = { name: "Alice" };

function greet(age) {
  console.log(`Hello, my name is ${this.name} and I'm ${age} years old.`);
}

greet.call(obj, 25); // Hello, my name is Alice and I'm 25 years old.
greet.apply(obj, [25]); // Same as call but with an array
const boundGreet = greet.bind(obj, 25);
boundGreet(); // Binds `this` permanently

60. What are template literals in JavaScript?

Template literals allow embedded expressions and multiline strings.

Example:

const name = "Alice";
const age = 25;

console.log(`My name is ${name} and I am ${age} years old.`);
// Output: My name is Alice and I am 25 years old.

Example of Multi-line Strings:

const multiLine = `This is
a multi-line
string.`;
console.log(multiLine);

 


61. What is a Higher-Order Function (HOF) in JavaScript?

A Higher-Order Function (HOF) is a function that either:

  • Takes another function as an argument, or
  • Returns a function as its result.

Example:

function multiplier(factor) {
  return function (num) {
    return num * factor;
  };
}

const double = multiplier(2);
console.log(double(5)); // 10

Use cases:

  • Functional programming
  • Callback functions
  • Event handling

62. What is a Pure Function in JavaScript?

A pure function always:

  1. Returns the same output for the same input
  2. Has no side effects

Example of a Pure Function:

function add(a, b) {
  return a + b;
}

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

Example of an Impure Function:

let total = 0;
function addToTotal(num) {
  total += num;
}

Pure functions are beneficial because they are predictable and easier to test.


63. What is the this keyword in JavaScript?

this refers to the object that is executing the current function.

Example in Different Contexts:

console.log(this); // In global scope, `this` refers to `window` (browser) or `global` (Node.js).

const obj = {
  name: "Alice",
  greet: function () {
    console.log(this.name); // "Alice"
  }
};
obj.greet();
  • In functions, this depends on how the function is called.
  • In arrow functions, this is lexically bound (inherits from surrounding scope).

64. What is an IIFE (Immediately Invoked Function Expression)?

An IIFE is a function that executes immediately after it is defined.

Example:

(function () {
  console.log("I run immediately!");
})();

Use cases:

  • Avoid polluting the global namespace
  • Execute code immediately

65. What is the difference between == and === in JavaScript?

OperatorChecksExample
==Value only (loose equality)"5" == 5true
===Value & Type (strict equality)"5" === 5false

Example:

console.log("5" == 5); // true (type coercion)
console.log("5" === 5); // false (strict comparison)

66. What are the different ways to define a function in JavaScript?

1️⃣ Function Declaration:

function greet() {
  return "Hello";
}

2️⃣ Function Expression:

const greet = function () {
  return "Hello";
};

3️⃣ Arrow Function:

const greet = () => "Hello";

4️⃣ Anonymous Function (inside another function):

setTimeout(function () {
  console.log("Hello");
}, 1000);

67. What is the difference between setTimeout() and setInterval()?

MethodExecutionStops When?
setTimeout(func, delay)Runs once after delayManually cleared with clearTimeout()
setInterval(func, interval)Runs repeatedly at intervalManually cleared with clearInterval()

Example of setTimeout():

setTimeout(() => console.log("Runs once after 2 seconds"), 2000);

Example of setInterval():

const intervalId = setInterval(() => console.log("Runs every second"), 1000);
setTimeout(() => clearInterval(intervalId), 5000); // Stops after 5 seconds

68. How do Promises work in JavaScript?

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation.

Example:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Success!"), 2000);
});

myPromise.then(result => console.log(result)); // "Success!" after 2 seconds

Promise States:

  • pending → Initial state
  • fulfilledresolve() is called
  • rejectedreject() is called

69. What is Promise Chaining?

Promise chaining allows executing multiple asynchronous operations sequentially.

Example:

new Promise((resolve) => {
  setTimeout(() => resolve(1), 1000);
})
  .then(result => {
    console.log(result); // 1
    return result * 2;
  })
  .then(result => {
    console.log(result); // 2
    return result * 3;
  })
  .then(result => {
    console.log(result); // 6
  });

70. What is Promise.all(), Promise.race(), and Promise.any()?

MethodBehavior
Promise.all([p1, p2])Resolves when all promises resolve, rejects if any fail.
Promise.race([p1, p2])Resolves/rejects as soon as any promise settles.
Promise.any([p1, p2])Resolves as soon as any promise fulfills, ignores rejections.

Example of Promise.all()

Promise.all([
  new Promise(resolve => setTimeout(() => resolve("First"), 1000)),
  new Promise(resolve => setTimeout(() => resolve("Second"), 2000))
])
.then(console.log); // ["First", "Second"] after 2s

Example of Promise.race()

Promise.race([
  new Promise(resolve => setTimeout(() => resolve("Fastest"), 1000)),
  new Promise(resolve => setTimeout(() => resolve("Slower"), 2000))
])
.then(console.log); // "Fastest" after 1s

Example of Promise.any()

Promise.any([
  new Promise((_, reject) => setTimeout(() => reject("Error"), 1000)),
  new Promise(resolve => setTimeout(() => resolve("Success"), 2000))
])
.then(console.log); // "Success" after 2s

 


71. What is async/await in JavaScript?

async/await is a modern way to handle asynchronous operations in JavaScript, making code look more synchronous.

Example:

async function fetchData() {
  return "Data fetched!";
}

fetchData().then(console.log); // "Data fetched!"

Example with await:

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function fetchData() {
  console.log("Fetching...");
  await delay(2000); // Waits for 2 seconds
  console.log("Data fetched!");
}

fetchData();

Key Points:

  • The await keyword can only be used inside an async function.
  • It pauses execution until the promise resolves.

72. What happens if you forget to use await inside an async function?

If await is missing, the function does not wait for the promise to resolve and continues execution.

Example:

async function fetchData() {
  return new Promise(resolve => setTimeout(() => resolve("Done!"), 1000));
}

async function main() {
  let data = fetchData(); // Forgot `await`
  console.log(data); // Logs a Promise instead of "Done!"
}

main();

✅ Fix it by using await:

let data = await fetchData();
console.log(data); // "Done!"

73. How to handle errors in async/await?

Use try...catch to handle errors in async/await functions.

Example:

async function fetchData() {
  try {
    let response = await fetch("https://invalid.url");
    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.log("Error fetching data:", error.message);
  }
}

fetchData();

74. What is event delegation in JavaScript?

Event delegation is a technique where a parent element listens for events on its children instead of adding event listeners to each child.

Example:

document.getElementById("parent").addEventListener("click", function (event) {
  if (event.target.tagName === "BUTTON") {
    console.log("Button clicked:", event.target.innerText);
  }
});

✅ Why use event delegation?

  • Improves performance for dynamically added elements.
  • Reduces memory usage by avoiding multiple event listeners.

75. What is the debounce() function in JavaScript?

Debouncing ensures a function runs only after a specified delay, useful for optimizing event-heavy operations like search inputs.

Example:

function debounce(func, delay) {
  let timeout;
  return function (...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), delay);
  };
}

window.addEventListener("resize", debounce(() => console.log("Resized!"), 500));

76. What is the throttle() function in JavaScript?

Throttling ensures a function runs at most once in a specified time interval, useful for scroll events.

Example:

function throttle(func, limit) {
  let lastCall = 0;
  return function (...args) {
    let now = Date.now();
    if (now - lastCall >= limit) {
      lastCall = now;
      func.apply(this, args);
    }
  };
}

window.addEventListener("scroll", throttle(() => console.log("Scrolling!"), 1000));

77. What is Object.freeze() and Object.seal()?

MethodCan Modify Properties?Can Add New Properties?Can Delete Properties?
Object.freeze(obj)❌ No❌ No❌ No
Object.seal(obj)✅ Yes❌ No❌ No

Example of Object.freeze():

const obj = { name: "Alice" };
Object.freeze(obj);
obj.name = "Bob"; // ❌ Won't work
console.log(obj.name); // "Alice"

Example of Object.seal():

const obj = { name: "Alice" };
Object.seal(obj);
obj.name = "Bob"; // ✅ Works
obj.age = 30; // ❌ Won't work
console.log(obj); // { name: "Bob" }

78. What is the difference between shallow copy and deep copy?

Copy TypeCopies Nested Objects?Example
Shallow Copy❌ NoObject.assign({}, obj)
Deep Copy✅ YesJSON.parse(JSON.stringify(obj))

Example of Shallow Copy:

const obj = { a: 1, b: { c: 2 } };
const shallowCopy = { ...obj };
shallowCopy.b.c = 99;
console.log(obj.b.c); // 99 (also changed)

Example of Deep Copy:

const deepCopy = JSON.parse(JSON.stringify(obj));
deepCopy.b.c = 50;
console.log(obj.b.c); // 99 (original remains unchanged)

79. What is a Closure in JavaScript?

A closure is a function that remembers variables from its outer scope even after the outer function has finished executing.

Example:

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

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

Closures help in data encapsulation and creating private variables.


80. How does JavaScript handle memory management?

JavaScript uses Garbage Collection (GC) with the Mark-and-Sweep algorithm.

  • Objects are created in memory.
  • Unused objects (not referenced) are garbage collected.

Example:

function createObj() {
  let obj = { name: "Alice" };
  return obj;
}
let ref = createObj(); // `obj` stays in memory
ref = null; // `obj` is now eligible for garbage collection

✅ How to avoid memory leaks?

  • Avoid global variables.
  • Use WeakMap and WeakSet for objects that should be garbage collected automatically.
  • Remove event listeners when no longer needed.

 


81. What is the difference between null and undefined in JavaScript?

TypeMeaningExample
nullExplicit absence of a valuelet x = null;
undefinedVariable declared but not assigned a valuelet y;

Example:

let a; // undefined
let b = null; // null
console.log(typeof a); // "undefined"
console.log(typeof b); // "object" (legacy behavior)

82. What is the difference between map(), filter(), and reduce()?

MethodPurposeReturns
map()Transforms each element in an arrayNew array with transformed values
filter()Filters elements based on a conditionNew array with matching elements
reduce()Accumulates values into a single resultSingle computed value

Example:

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

const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]

const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 15

83. What is the difference between synchronous and asynchronous code?

TypeExecutionExample
SynchronousExecutes line by lineconsole.log("Hello"); console.log("World");
AsynchronousExecutes later, does not blocksetTimeout(() => console.log("Async!"), 1000);

Example of Asynchronous Code:

console.log("Start");
setTimeout(() => console.log("Async Operation"), 2000);
console.log("End");

Output:

Start
End
Async Operation (after 2 seconds)

84. What is the Event Loop in JavaScript?

The Event Loop is responsible for handling asynchronous operations by continuously checking the Call Stack and Task Queue.

Example:

console.log("Start");

setTimeout(() => {
  console.log("Timeout");
}, 0);

console.log("End");

Output:

Start
End
Timeout

✅ Even though setTimeout is 0ms, it runs after synchronous code finishes.


85. What is the difference between localStorage, sessionStorage, and cookies?

Storage TypeExpiryScopeMax Size
localStorageNever expiresSame origin5MB
sessionStorageExpires on tab closeSame tab5MB
cookiesSet expiry manuallySent with every request4KB

Example:

// localStorage
localStorage.setItem("name", "Alice");
console.log(localStorage.getItem("name")); // "Alice"

// sessionStorage
sessionStorage.setItem("name", "Bob");
console.log(sessionStorage.getItem("name")); // "Bob"

// Cookies
document.cookie = "username=John; expires=Fri, 31 Dec 2025 12:00:00 UTC";
console.log(document.cookie);

86. How do you deep clone an object in JavaScript?

A deep clone means copying an object and all its nested objects.

Methods:

  1. Using JSON.parse(JSON.stringify(obj)) (Does not work with functions)
const obj = { a: 1, b: { c: 2 } };
const deepCopy = JSON.parse(JSON.stringify(obj));
deepCopy.b.c = 99;
console.log(obj.b.c); // 2 (original remains unchanged)
  1. Using structured cloning (structuredClone)
const clone = structuredClone(obj);
  1. Using Lodash
const deepClone = _.cloneDeep(obj);

87. What is the difference between apply(), call(), and bind()?

MethodInvocationArguments FormatReturns
call()Calls immediatelyComma-separatedFunction result
apply()Calls immediatelyArray of argumentsFunction result
bind()Returns a new functionComma-separatedBound function

Example:

const person = { name: "Alice" };

function greet(age) {
  console.log(`Hello, my name is ${this.name} and I'm ${age} years old.`);
}

greet.call(person, 25); // "Hello, my name is Alice and I'm 25 years old."
greet.apply(person, [30]); // "Hello, my name is Alice and I'm 30 years old."
const boundGreet = greet.bind(person, 35);
boundGreet(); // "Hello, my name is Alice and I'm 35 years old."

88. What are template literals in JavaScript?

Template literals use backticks (`) to allow multi-line strings and string interpolation.

Example:

const name = "Alice";
const age = 25;

console.log(`My name is ${name} and I am ${age} years old.`);

✅ Supports multi-line strings:

const text = `Hello,
This is a multi-line string.`;
console.log(text);

89. What are tagged template literals?

A tagged template literal allows custom parsing of template strings.

Example:

function highlight(strings, ...values) {
  return strings.reduce((acc, str, i) => `${acc}${str}<b>${values[i] || ""}</b>`, "");
}

const name = "Alice";
const age = 25;

console.log(highlight`My name is ${name} and I am ${age} years old.`);

Output:
My name is <b>Alice</b> and I am <b>25</b> years old.


90. What are WeakMap and WeakSet in JavaScript?

FeatureMapWeakMapSetWeakSet
Holds primitive values✅ Yes❌ No✅ Yes❌ No
Holds objects✅ Yes✅ Yes✅ Yes✅ Yes
Keys are garbage collected❌ No✅ Yes❌ No✅ Yes

Example of WeakMap:

let obj = { name: "Alice" };
let weakMap = new WeakMap();
weakMap.set(obj, "data");
obj = null; // The object is garbage collected

✅ Why use WeakMap?

  • Objects automatically get removed when no longer referenced.
  • Prevents memory leaks.

 

Here are the next 10 JavaScript interview questions with detailed answers and examples:


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

LoopWorks onIterates OverUse Case
for...ofIterables (arrays, strings, sets, maps)ValuesWhen working with iterable data structures
for...inObjectsKeys (property names)When working with object properties

Example:

const arr = [10, 20, 30];

// Using for...of
for (const value of arr) {
  console.log(value); // 10, 20, 30
}

// Using for...in
for (const index in arr) {
  console.log(index); // "0", "1", "2"
}

92. What is function currying in JavaScript?

Currying is a technique where a function takes multiple arguments one at a time instead of all at once.

Example:

function add(a) {
  return function (b) {
    return function (c) {
      return a + b + c;
    };
  };
}

console.log(add(2)(3)(5)); // 10

✅ Use case: Currying is useful for creating reusable and specialized functions.


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

OperatorType ConversionExampleOutput
==Yes (loose equality)"5" == 5true
===No (strict equality)"5" === 5false

Example:

console.log(0 == false); // true (type conversion)
console.log(0 === false); // false (strict comparison)

94. What is the difference between Object.create() and new Object()?

MethodPrototype InheritanceCreates Empty Object?Example
Object.create(proto)Inherits from proto❌ NoObject.create(existingObj)
new Object()No inheritance✅ Yesnew Object()

Example:

const person = { greet: function () { console.log("Hello"); } };

const newPerson = Object.create(person);
newPerson.greet(); // "Hello"

95. How do you make an object immutable in JavaScript?

Use Object.freeze() to make an object immutable.

Example:

const obj = { name: "Alice" };
Object.freeze(obj);
obj.name = "Bob"; // ❌ Won't work
console.log(obj.name); // "Alice"

96. What is the difference between deep copy and shallow copy?

Copy TypeCopies Nested Objects?Example
Shallow Copy❌ NoObject.assign({}, obj)
Deep Copy✅ YesJSON.parse(JSON.stringify(obj))

Example:

const obj = { a: 1, b: { c: 2 } };
const shallowCopy = { ...obj };
shallowCopy.b.c = 99;
console.log(obj.b.c); // 99 (also changed)

const deepCopy = JSON.parse(JSON.stringify(obj));
deepCopy.b.c = 50;
console.log(obj.b.c); // 99 (original remains unchanged)

97. What is the difference between typeof and instanceof?

OperatorUsed forExample
typeofPrimitive typestypeof "hello" // "string"
instanceofObjectsarr instanceof Array // true

Example:

console.log(typeof 42); // "number"
console.log([] instanceof Array); // true
console.log({} instanceof Array); // false

98. What is an Immediately Invoked Function Expression (IIFE)?

An IIFE is a function that executes immediately after its creation.

Example:

(function () {
  console.log("IIFE executed!");
})();

✅ Why use an IIFE?

  • Avoids polluting the global scope.
  • Useful for initializing code.

99. How do you remove duplicates from an array in JavaScript?

Using Set:

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

Using filter():

const unique = numbers.filter((value, index, self) => self.indexOf(value) === index);
console.log(unique); // [1, 2, 3, 4, 5]

100. What is Object.assign() used for?

Object.assign() is used to copy properties from one or more objects to a target object.

Example:

const target = { a: 1 };
const source = { b: 2, c: 3 };

const result = Object.assign(target, source);
console.log(result); // { a: 1, b: 2, c: 3 }

✅ Use case:

  • Cloning objects.
  • Merging multiple objects into one.

 


Final Thoughts – Crack Any JavaScript Interview Like a Pro!

JavaScript interviews can be challenging, but with the right preparation, you can confidently tackle even the trickiest questions. In this guide, we’ve covered 100 must-know JavaScript interview questions, from fundamentals to advanced topics like closures, event delegation, and asynchronous programming.

💡 Key Takeaways:
✅ Understand JavaScript’s core concepts (hoisting, scope, closures)
✅ Master modern JavaScript features (ES6+, promises, async/await)
✅ Practice coding examples to strengthen your problem-solving skills

📌 Pro Tip: Bookmark this page and revisit these questions before your next interview! Want a downloadable PDF version? Let us know in the comments! 🚀

Leave a Reply

Your email address will not be published. Required fields are marked *