Top 100 JavaScript Interview Questions

Your ultimate guide to acing JavaScript interviews. Covering core concepts, async, ES6+, and more.

This curated list of JavaScript interview questions covers a wide range of topics, from fundamental concepts to advanced patterns. Use this guide to test your knowledge and prepare for your next technical interview.

Last Updated: Aug 17, 2025

Table of Contents

Core Concepts

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

This is a fundamental question about variable declarations and scope.

  • var: Is function-scoped or globally-scoped. It can be re-declared and updated. It's hoisted to the top of its scope and initialized with undefined.
  • let: Is block-scoped ({}). It can be updated but not re-declared within the same scope. It's hoisted but not initialized, creating a "temporal dead zone" until the declaration is encountered.
  • const: Is block-scoped. It cannot be updated or re-declared and must be initialized at the time of declaration. For objects and arrays, the variable reference is constant, but the properties or elements within can be changed.

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

This question tests your understanding of equality in JavaScript.

  • == (Loose Equality): Compares two values for equality after performing type coercion. For example, '5' == 5 is true.
  • === (Strict Equality): Compares two values for equality without any type coercion. Both the type and the value must be the same. For example, '5' === 5 is false. It is generally recommended to use strict equality to avoid unexpected bugs.

3. What is "hoisting" in JavaScript?

Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

  • var declarations are hoisted and initialized with undefined.
  • let and const declarations are hoisted but not initialized, leading to a ReferenceError if accessed before declaration (the temporal dead zone).
  • Function declarations are also hoisted, which means you can call a function before you define it. Function expressions are not hoisted.

4. What is a closure?

A closure is the combination of a function and the lexical environment within which that function was declared. In simpler terms, a closure gives you access to an outer function's scope from an inner function, even after the outer function has finished executing.

This is commonly used for data privacy, creating function factories, and in event handlers.

5. Explain the this keyword.

The value of this is determined by how a function is called (its execution context).

  • Global Context: In the global scope, this refers to the global object (window in browsers).
  • Function Context: In a simple function call, this also refers to the global object (or undefined in strict mode).
  • Method Context: When a function is called as a method of an object, this refers to the object the method is called on.
  • Arrow Functions: Arrow functions do not have their own this context. They inherit this from their parent scope at the time they are defined.
  • Event Listeners: In an event listener, this typically refers to the element that received the event.

6. What is a Promise?

A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. A promise can be in one of three states:

  • Pending: The initial state; not yet fulfilled or rejected.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

Promises help manage asynchronous code more cleanly than traditional callbacks, avoiding "callback hell".

(See also: Question #46 on async/await)

7. What is the difference between Promises and async/await?

async/await is syntactic sugar built on top of Promises, making asynchronous code look and behave more like synchronous code. This makes it easier to read and write.

  • An async function always returns a Promise.
  • The await keyword can only be used inside an async function. It pauses the execution of the function and waits for the Promise to resolve before continuing.

8. Explain the Event Loop.

The event loop is a mechanism that allows JavaScript, which is single-threaded, to handle asynchronous operations without blocking the main thread. It works with the call stack and message queues.

  1. When an async operation (like setTimeout) is called, it's passed to a Web API in the browser.
  2. When the operation is complete, its callback is placed in the message queue (or task queue).
  3. The event loop continuously checks if the call stack is empty.
  4. If the call stack is empty, the first message from the queue is pushed onto the call stack to be executed.

9. What is destructuring?

Destructuring is an ES6 feature that allows you to unpack values from arrays, or properties from objects, into distinct variables. It provides a cleaner and more concise syntax for extracting data.

Example: const { name, age } = user; or const [first, second] = anArray;

10. Explain the spread and rest operators.

Though they use the same syntax (...), they perform opposite functions.

  • Spread Operator: "Spreads" or expands an iterable (like an array or string) or an object into its individual elements. It's commonly used for making copies of arrays/objects or for combining them.
  • Rest Operator: "Collects" multiple elements and condenses them into a single element (an array). It's used in function parameters to gather all remaining arguments into an array.

11. What are the different data types in JavaScript?

JavaScript has two main categories of data types: Primitive Types and Object Types.

  • Primitive Types: These are immutable (cannot be changed) and are passed by value.
    • string: A sequence of characters.
    • number: Numeric values, including integers and floating-point numbers.
    • boolean: Represents true or false.
    • undefined: A variable that has been declared but not assigned a value.
    • null: Represents the intentional absence of any object value.
    • symbol: A unique and immutable primitive value, often used as an object property key.
    • bigint: For integers of arbitrary precision.
  • Object Type: A collection of properties. This includes arrays, functions, and regular objects. Objects are mutable and passed by reference.

12. What are truthy and falsy values in JavaScript?

In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy.

The list of falsy values is short:

  • false
  • 0 (and -0, 0n)
  • "" (empty string)
  • null
  • undefined
  • NaN (Not a Number)

Everything else, including '0', 'false', [], and {}, is truthy.

13. Explain the difference between null and undefined.

This question checks your understanding of JavaScript's types for "emptiness".

  • undefined typically means a variable has been declared but has not yet been assigned a value. It's the default value.
  • null is an assignment value. It can be assigned to a variable as a representation of no value. It is an explicit way to indicate that a variable should have no value.
  • A key difference is that typeof undefined is 'undefined', while typeof null is 'object'. This is a long-standing bug in JavaScript that is unlikely to be fixed.

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

An IIFE is a JavaScript function that runs as soon as it is defined. It's a design pattern used to create a local scope for variables, preventing them from polluting the global scope.

The syntax involves wrapping a function in parentheses and then immediately calling it: (function() { /* code */ })();

15. What are pure functions?

A pure function is a function that meets two criteria:

  1. Deterministic: Given the same input, it will always return the same output.
  2. No Side Effects: It does not modify any state outside of its own scope (e.g., it doesn't change global variables, mutate its input arguments, or perform I/O operations).

Pure functions are predictable, easier to test, and form the foundation of functional programming.

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

  • Shallow Copy: Copies only the top-level properties, nested objects are shared between the original and the copy.
  • Deep Copy: Creates a completely independent copy, including all nested objects.

17. What is the Temporal Dead Zone?

The period between entering scope and being declared where variables (let/const) cannot be accessed. Attempting to access them results in a ReferenceError.

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

  • Declaration: function foo() {} - hoisted entirely
  • Expression: const foo = function() {} - not hoisted

19. What is the difference between typeof and instanceof?

  • typeof returns a string indicating the type of the operand
  • instanceof checks if an object is an instance of a constructor

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

  • All three methods allow you to set the this value explicitly
  • call takes arguments individually
  • apply takes arguments as an array
  • bind returns a new function with bound context

21. What is the difference between slice and splice?

  • slice returns a shallow copy of a portion of an array without modifying the original
  • splice changes the contents of an array by removing or replacing existing elements

22. What is the difference between forEach and map?

  • forEach executes a function on each element without returning a new array
  • map creates a new array with the results of calling a function on every element

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

  • Object.freeze() makes an object immutable (no changes allowed)
  • Object.seal() prevents adding/removing properties but allows modifying existing ones

24. What is the difference between Array.from() and Array.of()?

  • Array.from() creates an array from an array-like or iterable object
  • Array.of() creates an array with the arguments as elements

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

  • Object.keys() returns an array of a given object's own property names
  • Object.values() returns an array of a given object's own property values
  • Object.entries() returns an array of a given object's own [key, value] pairs

26. What is the difference between String.slice() and String.substring()?

  • Both extract parts of a string
  • slice() can accept negative indexes
  • substring() treats negative indexes as 0

27. What is the difference between Array.reduce() and Array.reduceRight()?

  • Both execute a reducer function on each element
  • reduce() processes from left to right
  • reduceRight() processes from right to left

28. What is the difference between Array.some() and Array.every()?

  • some() returns true if at least one element passes the test
  • every() returns true only if all elements pass the test

29. What is the difference between parseInt() and parseFloat()?

  • parseInt() parses a string and returns an integer
  • parseFloat() parses a string and returns a floating point number

30. What is the difference between isNaN() and Number.isNaN()?

  • isNaN() converts the argument to a Number before testing
  • Number.isNaN() doesn't do type coercion

Functions & Scope

31. What is a higher-order function?

A function that takes one or more functions as arguments or returns a function as its result.

32. What is a callback function?

A function passed into another function as an argument to be executed later.

33. What is a recursive function?

A function that calls itself until a base condition is met.

34. What is a generator function?

A function that can be exited and later re-entered, with its context saved across re-entrances.

35. What is the arguments object?

An array-like object accessible inside functions that contains the values of the arguments passed.

36. What is function composition?

The process of combining two or more functions to produce a new function.

37. What is currying?

The technique of translating a function that takes multiple arguments into a sequence of functions that each take a single argument.

38. What is a factory function?

A function that returns an object without using the new keyword.

39. What is memoization?

An optimization technique that stores the results of expensive function calls.

40. What is the Module Pattern?

A design pattern that uses closures to create private and public encapsulation.

41. What is the Revealing Module Pattern?

A variant of the Module Pattern that explicitly reveals public pointers to private functions.

42. What is a thunk?

A function that wraps an expression to delay its evaluation.

43. What is a trampoline function?

A technique to handle recursion without exceeding the call stack.

44. What is tail call optimization?

A technique where the compiler optimizes recursive calls to reuse the current stack frame.

45. What is a decorator function?

A function that modifies the behavior of another function without changing its source code.

Asynchronous JavaScript

46. Explain Promise.all(), Promise.race(), and Promise.allSettled().

  • Promise.all(iterable): Fulfills when all of the promises in the iterable have fulfilled, or rejects as soon as one of the promises rejects.
  • Promise.race(iterable): Fulfills or rejects as soon as one of the promises in the iterable fulfills or rejects.
  • Promise.allSettled(iterable): Fulfills after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.
  • Promise.any(iterable): Fulfills as soon as any of the promises in the iterable fulfills. If all promises reject, it rejects with an AggregateError.

47. What is a microtask queue?

A queue for microtasks (like Promise callbacks) that has higher priority than the regular task queue.

48. What is the difference between setTimeout and setInterval?

  • setTimeout runs the code once after the delay
  • setInterval runs the code repeatedly with the delay between each execution

49. What is the difference between process.nextTick and setImmediate?

  • process.nextTick executes before the next event loop iteration
  • setImmediate executes during the next event loop iteration

50. What is the difference between Promise.resolve and new Promise?

  • Promise.resolve creates a resolved promise
  • new Promise creates a new promise that can be resolved or rejected

51. What is the difference between Promise.catch and Promise.then with two arguments?

They are functionally equivalent, but catch is more readable for error handling.

52. What is the difference between Promise.finally and Promise.then?

  • finally executes regardless of the promise state
  • then executes only when the promise is resolved

53. What is the difference between Promise.all and Promise.allSettled?

  • all rejects immediately upon any rejection
  • allSettled waits for all promises to complete

54. What is the difference between Promise.race and Promise.any?

  • race settles when any promise settles (fulfill or reject)
  • any settles when any promise fulfills (ignores rejections unless all reject)

55. What is a Web Worker?

A JavaScript script running in the background, independent of the main thread.

56. What is Service Worker?

A type of web worker that acts as a proxy between the web app and the network.

57. What is the difference between Web Worker and Service Worker?

  • Web Workers are for general computation
  • Service Workers are specifically for network proxying and caching

58. What is the difference between requestAnimationFrame and setTimeout?

  • requestAnimationFrame is optimized for animations and runs before the next repaint
  • setTimeout runs at a specified time regardless of the browser's repaint cycle

59. What is the difference between fetch and XMLHttpRequest?

  • fetch is promise-based and simpler to use
  • XMLHttpRequest is event-based and more configurable

60. What is the difference between fetch and axios?

  • fetch is built into browsers
  • axios is a third-party library with more features like request cancellation

ES6+ & Modern Features

61. What are ES6 Modules?

ES6 Modules are the standard, built-in module system in JavaScript. They allow you to split your code into separate files (modules) and share code between them. This improves organization, reusability, and maintainability.

  • You use the export keyword to make variables, functions, or classes available to other modules.
  • You use the import keyword to bring exported code into another module.

62. What is optional chaining (?.)?

Optional chaining is a feature that allows you to safely access deeply nested object properties without having to explicitly check if each level in the chain exists.

If any part of the chain is null or undefined, the expression short-circuits and returns undefined instead of throwing an error. Example: const street = user?.address?.street;

63. What are template literals?

String literals allowing embedded expressions using backtick (`) delimiters.

64. What are default parameters?

Function parameters that have default values if no value or undefined is passed.

65. What are arrow functions?

A shorter syntax for writing functions with lexical this binding.

66. What are Symbols?

A unique and immutable primitive value often used as an object property key.

67. What are Iterators and Iterables?

  • Iterable: An object that defines its iteration behavior
  • Iterator: An object that knows how to access items from a collection one at a time

68. What are Generators?

Functions that can be exited and later re-entered, with their context saved across re-entrances.

69. What are Proxies?

Objects that wrap other objects and can intercept and redefine fundamental operations.

70. What are WeakMaps and WeakSets?

  • Collections that hold weak references to their objects
  • Useful for storing metadata about objects without preventing garbage collection

DOM Manipulation & Events

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

  • innerHTML: Parses and renders HTML content. It can be a security risk (XSS attacks) if you insert untrusted content. It is also slower because it involves HTML parsing.
  • innerText: Returns only the "human-readable" text, taking CSS styles into account (e.g., it won't return text from a hidden element). It is aware of layout and can be slow.
  • textContent: Returns all text content, including that of <script> and <style> tags, and doesn't care about CSS styling. It is much faster and safer than innerHTML for inserting plain text.

72. What is the difference between event.preventDefault() and event.stopPropagation()?

  • event.preventDefault(): Stops the default action of an element from happening. For example, it can prevent a form from submitting or a link from navigating to a new page.
  • event.stopPropagation(): Stops an event from "bubbling up" the DOM tree. When an event occurs on an element, it first runs the handlers on it, then on its parent, and so on, up the DOM tree. stopPropagation() prevents it from moving to the next element in the chain.

73. What is event delegation?

Event delegation is a technique where you add a single event listener to a parent element to manage events for all of its child elements. Instead of adding an event listener to each child, you can listen on the parent and use the event.target property to determine which child element triggered the event.

This is more efficient, especially for lists with many items, as it reduces memory usage and simplifies code when items are added or removed dynamically.

74. What is the difference between getElementById, querySelector, and getElementsByClassName?

  • getElementById returns a single element by ID
  • querySelector returns the first matching element for a CSS selector
  • getElementsByClassName returns a live HTMLCollection of elements with the given class

75. What is the difference between addEventListener and onclick?

  • addEventListener allows multiple event handlers
  • onclick can only have one handler and overwrites previous ones

76. What is the difference between event.target and event.currentTarget?

  • target is the element that triggered the event
  • currentTarget is the element that the event listener is attached to

77. What is the difference between createElement and cloneNode?

  • createElement creates a new element from scratch
  • cloneNode creates a copy of an existing node

78. What is the difference between appendChild and insertBefore?

  • appendChild adds a node as the last child
  • insertBefore adds a node before a specified reference node

79. What is the difference between removeChild and remove?

  • removeChild requires a parent node and removes a specific child
  • remove removes the node it's called on

80. What is the difference between getAttribute and dataset?

  • getAttribute gets any attribute value
  • dataset provides access to data-* attributes

Object-Oriented Programming

81. What is the difference between classical and prototypal inheritance?

This is a fundamental concept for understanding JavaScript's object model.

  • Classical Inheritance: Used in languages like Java or C++, it involves creating classes that are blueprints for objects. A class can inherit from another class to extend its functionality. Objects are instances of classes.
  • Prototypal Inheritance: Used by JavaScript, it involves objects inheriting directly from other objects. There are no classes in the traditional sense. Every object can serve as a prototype for another object, creating a "prototype chain".

82. What is the class keyword in ES6?

The class keyword, introduced in ES6, is primarily syntactic sugar over JavaScript's existing prototype-based inheritance. It provides a cleaner, more familiar syntax for creating constructor functions and handling inheritance, similar to what is found in other object-oriented languages like Java or Python.

Under the hood, it still uses prototypes, but it simplifies the process of creating objects and managing inheritance chains.

83. What is the difference between __proto__ and prototype?

  • __proto__ is the actual object used in the lookup chain
  • prototype is the object used to build __proto__ when creating an object with new

84. What is the difference between composition and inheritance?

  • Inheritance creates an "is-a" relationship
  • Composition creates a "has-a" relationship

85. What is the Mixin pattern?

A way to add functionality to a class by mixing in methods from other objects.

Data Structures

86. What is the difference between a Map and a plain Object?

  • Keys: A Map can have any value as a key (including functions, objects, or any primitive), whereas an Object's keys must be either a String or a Symbol.
  • Order: A Map remembers the original insertion order of the keys. An Object's keys are not guaranteed to be in any specific order.
  • Size: The number of items in a Map is easily retrieved with the .size property, while for an Object, you need to manually count the keys.
  • Performance: Map is optimized for frequent additions and removals of key-value pairs.

87. What is the difference between Set and Array?

  • Set stores unique values only
  • Array allows duplicate values and maintains order

88. What is the difference between WeakMap and Map?

  • WeakMap keys must be objects and are weakly referenced
  • Map keys can be any value and are strongly referenced

89. What is the difference between WeakSet and Set?

  • WeakSet can only contain objects and are weakly referenced
  • Set can contain any value and are strongly referenced

90. What is the difference between ArrayBuffer and TypedArray?

  • ArrayBuffer represents raw binary data
  • TypedArray provides a view for accessing this data in specific formats

Web APIs & Browser Features

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

  • localStorage: Stores data with no expiration date. The data persists even after the browser window is closed and is available in all tabs and windows from the same origin. (Capacity: ~5-10MB)
  • sessionStorage: Stores data for only one session. The data is cleared when the page session ends (i.e., when the browser tab is closed). It is unique to each tab. (Capacity: ~5-10MB)
  • Cookies: Store small amounts of data that are sent back to the server with every HTTP request. They have an expiration date and are primarily used for session management and tracking on the server-side. (Capacity: ~4KB)

92. What is the Same-Origin Policy?

The Same-Origin Policy is a critical security mechanism that restricts how a document or script loaded from one origin can interact with a resource from another origin. An "origin" is defined by the combination of protocol, hostname, and port.

It helps prevent malicious scripts on one page from obtaining sensitive data on another page through that page's DOM.

93. What is the difference between sessionStorage and localStorage?

  • sessionStorage is cleared when the page session ends
  • localStorage persists until explicitly cleared

94. What is the difference between document.write and innerHTML?

  • document.write writes directly to the document stream
  • innerHTML sets the HTML of an element

94. What is the difference between window.onload and DOMContentLoaded?

  • DOMContentLoaded fires when the initial HTML is loaded
  • window.onload fires after all resources (images, etc.) are loaded

Performance & Optimization

96. What are debouncing and throttling?

Both are techniques to control how often a function is executed, which is crucial for performance with events that can fire rapidly, like window resizing, scrolling, or key presses.

  • Debouncing: Groups a sequence of calls into a single one. The function is only executed after a certain amount of time has passed without it being called again. A common use case is for search input fields, where you only want to make an API call after the user has stopped typing.
  • Throttling: Guarantees that the function is executed at most once per specified time interval. For example, it ensures a function attached to a scroll event is not called more than once every 200ms, no matter how fast the user scrolls.

97. What is memoization?

Memoization is an optimization technique used to speed up function calls by caching the results of expensive function calls and returning the cached result when the same inputs occur again. It's particularly useful for pure functions (functions that return the same output for the same input and have no side effects).

98. What is lazy loading?

A technique that delays loading of non-critical resources until they are needed.

99. What is tree shaking?

A technique that eliminates dead code from the final bundle.

Web Security

100. What is Cross-Site Scripting (XSS) and how can you prevent it?

Cross-Site Scripting (XSS) is a security vulnerability where an attacker injects malicious scripts into content from otherwise trusted websites. When a user visits the page, the malicious script runs in their browser, potentially stealing session tokens, cookies, or other sensitive information.

Prevention: The primary way to prevent XSS is to properly sanitize and escape user-provided data before rendering it in the browser. Never trust user input. Use libraries or frameworks that automatically handle escaping (like React or Vue) or use browser features like textContent instead of innerHTML.

DevUtilityTool Logo

About the Author

This guide is curated by the team at DevUtilityTool, who are passionate about creating high-quality, accessible resources that help developers excel in their careers.