Top 100 JavaScript Interview Questions and Answers (2025 Updated)

JavaScript is one of the most popular programming languages for web development, powering everything from dynamic websites to complex web applications. If you’re preparing for a JavaScript interview, whether for a frontend, backend, or full-stack developer role, understanding key concepts is crucial.

In this detailed guide, we’ve compiled the most commonly asked JavaScript interview questions, from beginner to advanced, along with clear explanations and examples.

What is JavaScript?

JavaScript is a lightweight, interpreted, object-oriented programming language primarily used to create interactive and dynamic content on websites. It runs on the client-side in the browser but can also be used on the server-side using Node.js.

JavaScript Interview Questions and Answers

Here are the Top 100 JavaScript Interview Questions and Answers..

Top 100 JavaScript Interview Questions and Answers
Top 100 JavaScript Interview Questions and Answers

Basic JavaScript Interview Questions

These are essential questions to test your understanding of JavaScript fundamentals.

1. What is JavaScript?

JavaScript is a lightweight, interpreted scripting language used to create dynamic and interactive web content. It can run in browsers and on servers (via Node.js).

2. What are the data types in JavaScript?

JavaScript has 7 primitive types:

  • String
  • Number
  • Boolean
  • Null
  • Undefined
  • BigInt
  • Symbol
    and 1 non-primitive type: Object (includes Arrays, Functions, etc.)

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

KeywordScopeReassignmentHoisting
varFunction✅ Yes✅ Yes
letBlock✅ Yes❌ No
constBlock❌ No❌ No

4. What is hoisting in JavaScript?

Hoisting is JavaScript’s behavior of moving variable and function declarations to the top of the scope before execution.

console.log(a); // undefined
var a = 5;

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

  • == compares values only (type conversion allowed).
  • === compares values and types.
5 == "5";   // true
5 === "5";  // false

6. What are template literals?

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

let name = "Vishal";
console.log(`Hello, ${name}!`);

7. What are objects in JavaScript?

Objects store data in key-value pairs.

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

8. What is an array in JavaScript?

An array is an ordered list of values.

let colors = ["red", "green", "blue"];
console.log(colors[0]); // red

9. How do you check the type of a variable?

Using the typeof operator:

typeof 42;        // "number"
typeof "hello";   // "string"

10. What is NaN?

NaN stands for “Not a Number”. It represents an invalid numerical operation.

console.log("abc" / 2); // NaN

11. What are truthy and falsy values?

Falsy values include:
false, 0, "", null, undefined, NaN.
Everything else is truthy.

12. What is the difference between null and undefined?

  • null: assigned by the programmer (intentional absence).
  • undefined: variable declared but not assigned a value.

13. What is an operator in JavaScript?

Operators perform operations on operands, e.g., +, -, *, /, %, ===, &&, ||.

14. What are functions in JavaScript?

Functions are reusable blocks of code.

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

15. What are arrow functions?

A shorter way to write functions:

const add = (a, b) => a + b;

16. What are default parameters?

They assign default values if no argument is provided.

function greet(name = "Guest") {
  return `Hello, ${name}`;
}

17. What is a loop?

Loops execute code repeatedly until a condition is met.

for (let i = 0; i < 3; i++) console.log(i);

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

  • for → loops using an index.
  • for...of → loops directly over values.
for (let n of [10, 20, 30]) console.log(n);

19. What are conditional statements?

Used to perform actions based on conditions.

if (x > 0) console.log("Positive");
else console.log("Negative");

20. What is a switch statement?

Alternative to multiple if conditions.

switch(color) {
  case 'red': console.log('Stop'); break;
  default: console.log('Go');
}

21. What are comments in JavaScript?

They are ignored by the compiler:

// single-line
/* multi-line */

22. What is DOM in JavaScript?

DOM (Document Object Model) is a programming interface for HTML. JavaScript can manipulate HTML elements via the DOM.

23. What is event handling in JavaScript?

Responding to user interactions like clicks or keypresses.

button.addEventListener("click", () => alert("Clicked!"));

24. What is JSON?

JSON (JavaScript Object Notation) is a format for storing and transferring data.

let user = '{"name":"John"}';
JSON.parse(user);

25. How do you convert a string to a number?

Using Number() or parseInt().

Number("10");  // 10
parseInt("20"); // 20

26. What is type coercion?

Automatic type conversion by JavaScript.

"5" + 5; // "55"
"5" - 2; // 3

27. What are JavaScript events?

Events are actions that occur (click, load, input) to which code can respond.

28. What is the purpose of this keyword?

this refers to the current context (object calling the function).

29. What is a callback function?

A function passed as an argument to another function.

function greet(name, callback) {
  callback(`Hello ${name}`);
}
greet("Vishal", console.log);

30. What are ES6 features?

Introduced in 2015, ES6 includes:

Modules

  • let, const
  • Arrow functions
  • Template literals
  • Default parameters
  • Classes
  • Promises

Intermediate JavaScript Interview Questions

These questions go deeper into functional programming, asynchronous behavior, and ES6+ concepts that are frequently asked in interviews.

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

  • Declaration: Named function that’s hoisted.
  • Expression: Assigned to a variable; not hoisted.
// Declaration
function greet() { return "Hi"; }

// Expression
const greet = function() { return "Hi"; };

32. What are Immediately Invoked Function Expressions (IIFE)?

Functions that execute immediately after they are defined.

(function() {
  console.log("IIFE runs immediately");
})();

33. What are closures in JavaScript?

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

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

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

  • Synchronous: Executes line by line.
  • Asynchronous: Doesn’t block; uses callbacks, promises, or async/await.

35. What are promises in JavaScript?

Promises represent the result of an asynchronous operation.

const data = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Done!"), 1000);
});

36. What are async and await?

Used to simplify promise handling.

async function getData() {
  const result = await fetchData();
  console.log(result);
}

37. What is event bubbling and capturing?

  • Bubbling: Event propagates from child to parent.
  • Capturing: Event propagates from parent to child.
element.addEventListener('click', handler, true); // Capturing

38. What is the event loop in JavaScript?

The event loop handles asynchronous callbacks in a single-threaded environment, managing the call stack and callback queue.

39. What is a callback hell?

Nested callbacks that make code hard to read:

doA(() => {
  doB(() => {
    doC(() => console.log("Done"));
  });
});

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

  • Shallow copy: Copies only top-level properties.
  • Deep copy: Copies nested objects too.
let obj2 = JSON.parse(JSON.stringify(obj1)); // Deep copy

41. What is destructuring in JavaScript?

Extracting values from arrays or objects into variables.

const { name, age } = { name: "John", age: 25 };

42. What are rest and spread operators?

  • Rest (...args) combines multiple arguments into an array.
  • Spread (...array) expands elements.
function sum(...nums) { return nums.reduce((a,b) => a+b); }

43. What are JavaScript modules?

They allow you to import/export code between files.

// export.js
export const x = 10;

// import.js
import { x } from './export.js';

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

MethodPurposeReturns
map()Transforms array elementsNew array
filter()Filters based on conditionNew array
reduce()Accumulates valuesSingle value

45. What is a higher-order function?

A function that takes another function as an argument or returns one.

function apply(fn, x, y) {
  return fn(x, y);
}

46. What are arrow functions and how are they different?

Arrow functions have no own this, arguments, or prototype.

47. What are classes in JavaScript?

Blueprints for creating objects.

class Person {
  constructor(name) {
    this.name = name;
  }
}

48. What is inheritance in JavaScript?

Classes can extend other classes to inherit properties and methods.

class Student extends Person {
  constructor(name, grade) {
    super(name);
    this.grade = grade;
  }
}

49. What are prototypes?

Every JavaScript object has a prototype from which it can inherit properties.

50. What is prototypal inheritance?

Objects inherit directly from other objects via the prototype chain.

51. What is the bind() method?

bind() creates a new function with a specific this value.

let person = { name: "John" };
function greet() { console.log(this.name); }
let bound = greet.bind(person);
bound(); // John

52. What are call() and apply() methods?

Used to invoke a function with a specific this and arguments.

greet.call(person);
greet.apply(person);

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

MethodChanges Original ArrayPurpose
slice()Extracts elements
splice()Adds/removes elements

54. What is a constructor function?

A function used to create multiple object instances.

function Car(model) {
  this.model = model;
}

55. What is memoization?

Caching results of expensive function calls.

const memo = {};
function fib(n) {
  if (memo[n]) return memo[n];
  return memo[n] = n < 2 ? n : fib(n-1) + fib(n-2);
}

56. What are generators in JavaScript?

Functions that can be paused and resumed.

function* numbers() {
  yield 1;
  yield 2;
}

57. What is the fetch() API?

Used for making HTTP requests.

fetch("https://api.example.com")
  .then(res => res.json())
  .then(data => console.log(data));

58. What is CORS?

CORS (Cross-Origin Resource Sharing) allows web pages to request data from a different domain securely.

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

StorageExpiryCapacityScope
localStorageNo expiry~5MBDomain-wide
sessionStorageUntil tab closes~5MBPer tab
cookiesOptional expiry4KBSent with requests

60. What is a polyfill?

A polyfill is code that implements modern JS features on older browsers that don’t support them.

Advanced JavaScript Interview Questions

These questions are often asked in senior developer interviews and test your understanding of deep JavaScript internals, asynchronous behavior, and performance optimization.

61. What is the difference between execution context and call stack?

  • Execution Context: The environment in which JavaScript code is evaluated and executed.
  • Call Stack: A stack data structure that keeps track of execution contexts in order.

62. What are the types of execution contexts?

  1. Global Execution Context (default)
  2. Functional Execution Context
  3. Eval Execution Context

63. What is a lexical scope?

Lexical scope means variables are accessible based on where they were declared in code, not where they are called.

function outer() {
  let a = 10;
  function inner() {
    console.log(a); // 10
  }
  inner();
}

64. What is the temporal dead zone (TDZ)?

The period between variable declaration and initialization where accessing the variable throws an error.

console.log(x); // ReferenceError
let x = 5;

65. What is currying in JavaScript?

Transforming a function with multiple arguments into a series of functions taking one argument each.

function add(a) {
  return function(b) {
    return a + b;
  };
}
console.log(add(2)(3)); // 5

66. What is debouncing?

Debouncing ensures a function executes only after a certain delay since the last call — useful in search boxes or resize events.

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

67. What is throttling?

Throttling limits how frequently a function can run over time.

function throttle(fn, limit) {
  let inThrottle;
  return function(...args) {
    if (!inThrottle) {
      fn(...args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
}

68. What is the difference between deep and shallow equality?

  • Shallow equality: compares references
  • Deep equality: compares values recursively

69. What are WeakMap and WeakSet?

  • WeakMap: Holds key-value pairs where keys are objects and are weakly referenced.
  • WeakSet: Stores objects weakly without preventing garbage collection.

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

MethodCan Add New PropsCan Modify ExistingCan Delete
freeze()
seal()

71. What is the purpose of the Symbol type?

Symbols create unique, immutable identifiers used as object property keys.

const id = Symbol('id');

72. What is the difference between microtask and macrotask queues?

  • Microtasks: Promise.then, process.nextTick
  • Macrotasks: setTimeout, setInterval
    Microtasks run before macrotasks in the event loop.

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

  • setTimeout() runs once after delay
  • setInterval() runs repeatedly at intervals

74. What is the purpose of the new keyword?

It creates a new instance of an object with a constructor function.

function Car(model) { this.model = model; }
const c = new Car("BMW");

75. What are tagged template literals?

Functions that process template literals before returning output.

function tag(strings, ...values) {
  return strings[0] + values[0].toUpperCase();
}
tag`hello ${"world"}`; // "hello WORLD"

76. What is optional chaining (?.)?

Safely accesses deeply nested object properties.

let user = {};
console.log(user.profile?.name); // undefined (no error)

77. What is nullish coalescing (??)?

Returns the right-hand value only if the left-hand value is null or undefined.

let name = null ?? "Guest"; // Guest

78. What are async iterators?

They allow asynchronous iteration over data sources using for await...of.

for await (let item of asyncGenerator()) {
  console.log(item);
}

79. What is a proxy object in JavaScript?

A Proxy allows customizing behavior of objects like reading, writing, or deleting properties.

let user = { name: "John" };
let proxy = new Proxy(user, {
  get(target, prop) {
    return prop in target ? target[prop] : "Not Found";
  }
});

80. What is reflection in JavaScript?

Reflection provides methods to introspect and modify objects (via the Reflect API).

Reflect.get(obj, "name");

81. What is the difference between == and Object.is()?

Object.is() is like === but treats NaN as equal to NaN and +0 different from -0.

82. What are pure functions?

Functions with no side effects and consistent outputs for the same inputs.

83. What is immutability in JavaScript?

Data that cannot be changed after creation. Immutable practices improve predictability in code.

84. What are service workers?

Scripts that run in the background of the browser, enabling offline functionality and caching.

85. What is the shadow DOM?

An encapsulated DOM tree inside a web component that isolates styles and structure.

86. What are web components?

Reusable custom elements with encapsulated HTML, CSS, and JS.

87. What is tree shaking?

A build optimization technique that removes unused code during bundling (e.g., Webpack, Rollup).

88. What is the difference between innerHTML and textContent?

  • innerHTML parses HTML tags
  • textContent only retrieves or sets text

89. What are dynamic imports?

Imports that occur at runtime rather than compile time.

import('./module.js').then(module => module.run());

90. What is the difference between window.onload and document.addEventListener('DOMContentLoaded')?

  • window.onload: Fires after all assets are loaded (images, scripts).
  • DOMContentLoaded: Fires after the HTML is fully loaded and parsed.

JavaScript Coding Questions

These coding questions test practical skills and problem-solving using JavaScript.

91. Reverse a string in JavaScript

function reverseString(str) {
  return str.split('').reverse().join('');
}
console.log(reverseString("JavaScript")); // tpircSavaJ

92. Check if a number is prime

function isPrime(num) {
  if (num < 2) return false;
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (num % i === 0) return false;
  }
  return true;
}
console.log(isPrime(7)); // true

93. Find the largest number in an array

let arr = [3, 9, 2, 15, 7];
let max = Math.max(...arr);
console.log(max); // 15

94. Remove duplicates from an array

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

95. Sum all numbers in an array

let arr = [1, 2, 3, 4, 5];
let sum = arr.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 15

96. Check if a string is a palindrome

function isPalindrome(str) {
  return str === str.split('').reverse().join('');
}
console.log(isPalindrome("level")); // true

97. Flatten a nested array

let nested = [1, [2, [3, 4]], 5];
let flat = nested.flat(2);
console.log(flat); // [1,2,3,4,5]

98. Count occurrences of a value in an array

let arr = [1,2,2,3,2,4];
let count = arr.filter(x => x === 2).length;
console.log(count); // 3

99. Merge two arrays and remove duplicates

let arr1 = [1,2,3], arr2 = [3,4,5];
let merged = [...new Set([...arr1, ...arr2])];
console.log(merged); // [1,2,3,4,5]

100. Convert an array of objects to a single object

let arr = [{id:1, name:"A"}, {id:2, name:"B"}];
let obj = Object.fromEntries(arr.map(item => [item.id, item.name]));
console.log(obj); // {1:"A", 2:"B"}

FAQs

1. Is JavaScript the same as Java?

No, JavaScript and Java are two entirely different languages. JavaScript is mainly for web interactivity, while Java is a general-purpose programming language.

2. Is JavaScript synchronous or asynchronous?

JavaScript is single-threaded and synchronous by default but supports asynchronous operations through callbacks, promises, and async/await.

3. What is the difference between frontend and backend JavaScript?

  • Frontend JS: Runs in browsers (using DOM, events, etc.)
  • Backend JS: Runs on servers using Node.js to handle requests and data.

4. What are ES6 features in JavaScript?

Some major ES6 features include:

  • Arrow functions
  • Template literals
  • Let and const
  • Default parameters
  • Destructuring
  • Promises
  • Modules

5. Why should you use JavaScript for web development?

Because JavaScript is fast, versatile, and supported by all browsers. It’s the backbone of modern web frameworks like React, Vue, and Angular.

Conclusion

JavaScript interviews often test both conceptual understanding and coding logic. To perform well, focus on core fundamentals like scope, closures, async programming, and object prototypes. Practicing these JavaScript interview questions will help you approach your next interview with confidence and clarity.

Whether you’re a beginner or an experienced developer, mastering these topics will make you stand out as a strong JavaScript professional.


Photo of author
Authored by Vishal Agarhari
Vishal Agarhari is a blogger, content writer, and editor with over 6 years of experience in creating insightful articles across technology and finance. Passionate about simplifying complex ideas, he combines his technical knowledge and writing expertise to craft SEO-friendly content that educates, engages, and inspires readers.

Hide Ads for Premium Members by Subscribing
Hide Ads for Premium Members. Hide Ads for Premium Members by clicking on subscribe button.
Subscribe Now