Top 100 JavaScript Interview Questions and Answers

Top 100 JavaScript Interview Questions and Answers

Are you gearing up for a JavaScript interview and feeling the pressure to stand out? In today’s competitive tech landscape, a solid grasp of JavaScript fundamentals and advanced concepts is non-negotiable for any aspiring developer. This comprehensive guide, “Top 100 JavaScript Interview Questions & Answers (2025 Edition),” is meticulously crafted to equip you with the knowledge and confidence to ace your next technical challenge.

We’ve delved deep into the core of JavaScript, from its foundational principles to the latest features and best practices that senior developers expect. Whether you’re a junior developer seeking your first role or a seasoned professional aiming for a significant career leap, these questions cover the spectrum of what you’ll encounter. You’ll find detailed explanations on crucial topics like:

  • Execution Context & Hoisting: Understand how JavaScript code is parsed and executed, and the nuances of variable and function hoisting.
  • Closures & Scope: Demystify one of JavaScript’s most powerful (and often misunderstood) features, and its impact on data encapsulation.
  • Prototypes & Inheritance: Grasp the object-oriented nature of JavaScript and how objects inherit properties and methods.
  • Asynchronous JavaScript: Navigate the world of Promises, Async/Await, and event loops, essential for modern web development.
  • ES6+ Features: Stay current with destructuring, arrow functions, template literals, and other modern JavaScript enhancements.
  • DOM Manipulation & Event Handling: Learn how to interact with the browser’s Document Object Model and manage user interactions effectively.
  • Performance Optimization: Discover strategies to write efficient, scalable, and high-performing JavaScript applications.
  • Error Handling & Debugging: Master techniques for identifying, understanding, and resolving issues in your code.

Each question is accompanied by a clear, concise answer, often including code examples to illustrate the concepts practically. Beyond just memorizing answers, this guide encourages a deeper understanding, enabling you to articulate your reasoning and demonstrate true mastery during your interview.

Don’t leave your next JavaScript interview to chance. Arm yourself with the “Top 100 JavaScript Interview Questions & Answers (2025 Edition)” and walk into your next opportunity with the expertise to impress!

Top 100 JavaScript Interview Questions and Answers (Part 1 of 4)

1. What is JavaScript?

JavaScript is a lightweight, interpreted, and object-oriented programming language used primarily to create interactive and dynamic web pages. It runs in browsers and on servers (via Node.js).

2. How is JavaScript different from Java?

  • Java is a compiled, class-based, strongly typed language.
  • JavaScript is interpreted, prototype-based, and loosely typed.
    They share syntax similarities but are unrelated languages.

3. What are data types in JavaScript?

JavaScript has:

  • Primitive types: String, Number, Boolean, Null, Undefined, Symbol, BigInt
  • Non-primitive types: Object, Array, Function

4. What are primitive and non-primitive data types?

  • Primitive: Single immutable values (e.g., “Hello”, 42, true).
  • Non-primitive: Collections or references (e.g., {}, [], functions).

5. What are variables in JavaScript?

Variables store data values.
They can be declared using var, let, or const.

6. What’s the difference between var, let, and const?

  • var → Function-scoped, hoisted, can be redeclared.
  • let → Block-scoped, not hoisted, can be updated.
  • const → Block-scoped, cannot be updated or redeclared.

7. What is hoisting in JavaScript?

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

8. What are closures?

A closure is a function that retains access to variables in its parent scope, even after the parent function has finished executing.

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

9. Difference between == and ===?

  • == checks for value equality after type conversion.
  • === checks for value and type equality (strict comparison).

10. What is NaN in JavaScript?

NaN stands for “Not a Number.” It represents an invalid or unrepresentable numeric value (e.g., parseInt(“abc”)).

11. What is the typeof operator?

It returns the type of a variable or value:

typeof “hello” // “string” typeof 10 // “number”

12. What is the use of this keyword?

this refers to the object that is executing the current function. Its value depends on how the function is called (global, object method, constructor, etc.).

13. Difference between null and undefined?

  • undefined: A variable declared but not assigned a value.
  • null: An assigned value that represents “no value.”

14. What are template literals?

Template literals use backticks (`) to embed variables easily:

let name = “John”; console.log(`Hello, ${name}!`);

15. How do you write comments in JavaScript?

// Single-line comment /* Multi-line comment */

16. What are truthy and falsy values?

  • Falsy: false, 0, “”, null, undefined, NaN
  • Everything else is truthy.

17. What is coercion?

Coercion is the automatic or implicit conversion of values from one data type to another (e.g., “5” * 2 → 10).

18. What is a callback function?

A callback is a function passed as an argument to another function and executed later, usually after an operation completes.

function greet(name, callback) { console.log(“Hello ” + name); callback(); } greet(“John”, () => console.log(“Welcome!”));

19. What is parseInt() and parseFloat() used for?

  • parseInt() converts a string to an integer.
  • parseFloat() converts a string to a floating-point number.

20. What does isNaN() do?

isNaN(value) checks if a value is Not a Number.

isNaN(“abc”) // true isNaN(123) // false

21. What are function declarations and expressions?

  • Declaration:
    function greet() { return “Hi”; }
  • Expression:
    const greet = function() { return “Hi”; };

22. What are arrow functions?

Arrow functions are concise alternatives to regular functions:

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

They don’t have their own this.

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

A function executed immediately after creation:

(function() { console.log(“Runs instantly”); })();

24. Difference between call(), apply(), and bind()?

  • call() → invokes a function with arguments individually.
  • apply() → invokes with arguments as an array.
  • bind() → returns a new function with this bound to a given object.

25. What is lexical scope?

Lexical scope means that a function can access variables from its parent scope due to where it’s defined (not where it’s called).

Top 100 JavaScript Interview Questions and Answers (Part 2 of 4)

26. What are higher-order functions?

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

function calculate(a, b, operation) { return operation(a, b); } calculate(4, 2, (x, y) => x + y); // 6

27. What is function currying?

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

function multiply(a) { return function(b) { return a * b; }; } multiply(3)(5); // 15

28. What are default parameters in functions?

They allow parameters to have default values if no value is passed.

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

29. Can functions return other functions?

Yes. JavaScript supports first-class functions.

function outer() { return function inner() { return “Hello from inner!”; }; } outer()(); // “Hello from inner!”

30. What is recursion in JavaScript?

A function calling itself until a base condition is met.

function factorial(n) { return n === 0 ? 1 : n * factorial(n – 1); }

31. What are objects in JavaScript?

Objects are collections of key-value pairs used to store structured data.

let user = { name: “John”, age: 30 };

32. How do you create an object?

  • Using object literal: {}
  • Using new Object()
  • Using constructor functions or classes

33. How do you clone an object in JavaScript?

let obj2 = Object.assign({}, obj1); // or let obj2 = { …obj1 };

34. What is object destructuring?

Extracting values from objects easily:

const user = { name: “Alice”, age: 25 }; const { name, age } = user;

35. What is array destructuring?

Similar to objects but for arrays:

const colors = [“red”, “green”]; const [first, second] = colors;

36. What are array methods like map(), filter(), and reduce()?

  • map() → transforms elements
  • filter() → filters based on condition
  • reduce() → reduces array to single value

Example:

let nums = [1, 2, 3]; nums.map(n => n * 2); // [2, 4, 6] nums.filter(n => n > 1); // [2, 3] nums.reduce((a, b) => a + b); // 6

37. How do you merge two arrays?

let arr = arr1.concat(arr2); // or let arr = […arr1, …arr2];

38. How do you remove duplicates from an array?

let unique = […new Set(arr)];

39. Difference between forEach() and map()?

  • forEach() → Executes function but returns undefined
  • map() → Returns a new array

40. How do you sort an array of objects by a property?

arr.sort((a, b) => a.age – b.age);

41. What is the DOM?

The Document Object Model represents the structure of an HTML document as a tree that JavaScript can manipulate.

42. How do you select elements in the DOM?

  • document.getElementById()
  • document.querySelector()
  • document.querySelectorAll()

43. How do you add or remove HTML elements dynamically?

let div = document.createElement(‘div’); document.body.appendChild(div); document.body.removeChild(div);

44. What are event listeners?

Functions that run when an event occurs.

button.addEventListener(‘click’, () => console.log(‘Clicked!’));

45. What is event bubbling and capturing?

  • Bubbling: Event propagates from child → parent.
  • Capturing: Event propagates from parent → child.

46. What is event delegation?

Using a single event listener on a parent element to handle events for its children.

document.querySelector(‘ul’).addEventListener(‘click’, e => { if (e.target.tagName === ‘LI’) console.log(‘Item clicked’); });

47. Difference between window.onload and document.ready?

  • window.onload → Runs after all assets (images, scripts) load.
  • document.ready → Runs when the DOM is ready (faster).

48. How can you prevent the default action in an event?

event.preventDefault();

49. How do you stop event propagation?

event.stopPropagation();

50. How do you handle forms using JavaScript?

Use event listeners for submit:

form.addEventListener(‘submit’, e => { e.preventDefault(); console.log(‘Form submitted’); });

Top 100 JavaScript Interview Questions and Answers (Part 3 of 4)

51. What is asynchronous programming?

Asynchronous programming allows code to run without blocking other operations. It’s useful for tasks like API calls or timers where waiting is inefficient.

52. What are callbacks?

Callbacks are functions passed as arguments that are executed after another function completes.

setTimeout(() => console.log(“Done”), 1000);

53. What are Promises?

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

const data = new Promise((resolve, reject) => { setTimeout(() => resolve(“Success!”), 1000); }); data.then(console.log);

54. Difference between synchronous and asynchronous code?

  • Synchronous: Executes line by line.
  • Asynchronous: Doesn’t block; continues running other code while waiting for results.

55. What are async and await?

They simplify working with Promises.

async function fetchData() { const res = await fetch(‘/data’); return res.json(); }

56. What is the event loop in JavaScript?

It manages execution of multiple pieces of code — handles callbacks and asynchronous tasks by moving them from the queue to the call stack.

57. What are microtasks and macrotasks?

  • Microtasks: Promises, queueMicrotask
  • Macrotasks: setTimeout, setInterval, setImmediate
    Microtasks have higher priority and run before macrotasks.

58. Difference between setTimeout() and setInterval()?

  • setTimeout() → runs code once after a delay.
  • setInterval() → runs code repeatedly at given intervals.

59. What is Promise chaining?

Using multiple .then() calls to handle a series of asynchronous operations.

fetchData() .then(res => process(res)) .then(final => console.log(final));

60. What are Fetch API and AJAX?

Both are used to make network requests.

  • AJAX: Older XML-based approach.
  • Fetch API: Modern Promise-based method for HTTP requests.

61. How do you handle errors in JavaScript?

By using try, catch, and finally blocks.

try { throw new Error(“Oops!”); } catch (err) { console.log(err.message); }

62. What are try, catch, and finally?

  • try → code that may throw errors
  • catch → handles the error
  • finally → runs regardless of success or failure

63. What are custom errors in JavaScript?

You can create your own error types using the Error class.

class ValidationError extends Error { constructor(message) { super(message); this.name = “ValidationError”; } }

64. What is the throw statement used for?

It allows you to manually throw exceptions.

throw new Error(“Something went wrong!”);

65. How can you debug JavaScript code in the browser?

  • Use console.log()
  • Use Debugger in Chrome DevTools (Sources tab)
  • Add debugger; statement inside code.

66. What is prototypal inheritance?

Objects in JavaScript can inherit properties and methods from another object via the prototype chain.

67. What is the prototype chain?

Each object has an internal link ([[Prototype]]) to another object. When a property is not found, JavaScript looks up the prototype chain until it finds it or reaches null.

68. Difference between classical and prototypal inheritance?

  • Classical (Java): Uses classes and blueprints.
  • Prototypal (JS): Uses existing objects as templates for new ones.

69. What is a constructor function?

A function used to create objects with the new keyword.

function User(name) { this.name = name; } let u1 = new User(“Alice”);

70. What are classes in JavaScript?

ES6 introduced classes as syntactic sugar for prototype-based inheritance.

class Person { constructor(name) { this.name = name; } greet() { return `Hello, ${this.name}`; } }

71. What is encapsulation in JavaScript?

Encapsulation hides data implementation details. You can use closures or private class fields (#property) to achieve it.

72. Difference between shallow copy and deep copy?

  • Shallow copy: Copies only top-level properties (e.g., Object.assign).
  • Deep copy: Copies nested objects too (e.g., structuredClone() or JSON methods).

73. What are Symbols in JavaScript?

Symbols are unique and immutable identifiers used as object keys to avoid naming collisions.

let id = Symbol(‘id’);

74. Difference between Object.seal() and Object.freeze()?

  • seal() → prevents adding/removing properties but allows editing existing ones.
  • freeze() → makes the object completely immutable.

75. What are generators and iterators?

Generators are special functions that can pause and resume execution.

function* count() { yield 1; yield 2; } const c = count(); c.next(); // {value:1, done:false}

Top 100 JavaScript Interview Questions and Answers (Part 4 of 4)

76. What are cookies, localStorage, and sessionStorage?

They are client-side storage options:

  • Cookies: Small data sent with every HTTP request.
  • localStorage: Stores data with no expiration.
  • sessionStorage: Stores data until the browser tab is closed.

77. Difference between localStorage and sessionStorage?

Feature localStorage sessionStorage
Persistence Permanent Until tab closes
Shared between tabs Yes No
Storage limit ~5MB ~5MB

78. How do you store data in localStorage?

localStorage.setItem(“name”, “John”);

79. How do you delete an item from localStorage?

localStorage.removeItem(“name”); // or clear all localStorage.clear();

80. How do you handle cross-origin requests?

By configuring CORS (Cross-Origin Resource Sharing) on the server. The server must include the header:
Access-Control-Allow-Origin: * (or specific domain).

81. What are ES6 modules?

They allow importing and exporting code across files.

// math.js export function add(a, b) { return a + b; } // app.js import { add } from ‘./math.js’;

82. Difference between default export and named export?

  • Default export: One export per file.
  • Named export: Multiple exports allowed.

export default function greet() {} export const PI = 3.14;

83. How do you import and export functions or variables?

// Export export const name = “JS”; // Import import { name } from ‘./file.js’;

84. What is CommonJS vs ES6 Module System?

  • CommonJS (Node.js): Uses require() and module.exports.
  • ES6 Modules (browser): Uses import and export.

85. What is tree-shaking in JavaScript?

A build optimization technique that removes unused (dead) code from the final bundle in modern bundlers like Webpack or Rollup.

86. How do you improve JavaScript performance?

  • Use async loading for scripts
  • Minimize DOM manipulation
  • Debounce or throttle frequent events
  • Cache data
  • Use efficient algorithms and loops

87. What is debouncing?

Delays execution of a function until after a certain period of inactivity.
Useful for search boxes or resize events.

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

88. What is throttling?

Limits a function to execute only once in a given time frame.

function throttle(fn, delay) { let last = 0; return function(…args) { const now = Date.now(); if (now – last >= delay) { fn(…args); last = now; } }; }

89. What are memory leaks and how do you prevent them?

Memory leaks occur when memory isn’t released after use.
Prevention:

  • Remove unused event listeners.
  • Nullify references.
  • Use WeakMap and WeakSet.

90. What is lazy loading in JavaScript?

Loading resources (like images or scripts) only when needed to reduce initial load time.

91. What are unit tests in JavaScript?

They test individual pieces (functions, components) of your code to ensure they work as expected.

92. What are popular JavaScript testing frameworks?

  • Jest
  • Mocha
  • Jasmine
  • Cypress (for UI)

93. What is Jest used for?

Jest is a testing framework by Facebook used for unit testing, snapshot testing, and mocking in JavaScript and React applications.

94. Difference between Mocha and Jasmine?

  • Mocha: Flexible testing framework (requires assertion libraries).
  • Jasmine: All-in-one framework with built-in assertions.

95. What is the difference between console.log() and debugging tools?

console.log() outputs messages to the console, while browser debugging tools (like Chrome DevTools) allow step-by-step code execution and inspection.

96. What are template literals in ES6?

They allow embedding variables in strings with backticks:

let name = “John”; console.log(`Hello ${name}`);

97. What are destructuring assignments?

Extracting values from arrays or objects into variables.

const { name, age } = person; const [a, b] = [10, 20];

98. What are spread and rest operators?

  • Spread (): Expands arrays or objects.
  • Rest (): Collects multiple arguments into an array.

const arr = [1, 2, 3]; const newArr = […arr, 4]; function sum(…nums) { return nums.reduce((a, b) => a + b); }

99. What are Promises and how do they improve callbacks?

Promises simplify asynchronous code and avoid callback hell by chaining .then() and .catch() instead of nesting functions.

100. What new features were introduced in ES6 and later?

Some major additions include:

  • let and const
  • Arrow functions
  • Classes
  • Template literals
  • Destructuring
  • Modules (import/export)
  • Promises, async/await
  • Spread/rest operators
  • Optional chaining (?.)
  • Nullish coalescing (??)

Conclusion

Mastering JavaScript isn’t just about syntax — it’s about understanding how the language works under the hood.
These 100 JavaScript interview questions and answers cover everything from fundamentals to advanced ES6+ features.
Review them regularly to strengthen your foundation and prepare confidently for your next developer interview.