0% found this document useful (0 votes)
2 views21 pages

Top 100 JavaScript Interview Questions

Uploaded by

ayushraj3940
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views21 pages

Top 100 JavaScript Interview Questions

Uploaded by

ayushraj3940
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Top 100 JavaScript Interview Questions (Most Asked in Recent Interviews)

These are the questions repeatedly asked in:

 Product companies

 Startups

 FAANG/frontend interviews

 [Link]/backend interviews

 React/Vue/Angular roles

 Senior JavaScript engineer interviews

The most repeated topics in 2025 interviews are:

 Closures

 Event Loop

 Promises

 Async/Await

 Prototypes

 Debounce/Throttle

 Event Delegation

 Memory leaks

 Performance optimization

 Custom polyfills

 JavaScript internals

JavaScript Fundamentals

1. What is JavaScript?

2. Difference between var, let, and const.

Feature var let const

Scope Function-scoped Block-scoped Block-scoped

Reassignment Can be reassigned Can be reassigned Cannot be reassigned

Re- Can be re-declared Cannot be re-declared Cannot be re-declared


declaration

Hoisting Yes (initialized Yes (uninitialized Yes (uninitialized


with undefined) temporal dead zone) temporal dead zone)

3. Difference between == and ===.

The == operator checks only for value equality (performing automatic type conversion if
types differ), while the === operator performs strict equality, requiring both the value and
data type to be identical.

4. What is hoisting?

Hoisting is a JavaScript mechanism where variable and function declarations are moved to
the top of their scope during the compilation phase, before the code is executed. This means
you can use variables and functions before you actually declare them in your source code.

5. What is temporal dead zone?

The Temporal Dead Zone refers to the period where a variable exists in a scope but cannot
be accessed until it is initialized. The TDZ starts from the beginning of the block until the
variable is declared and initialized.

6. What are primitive data types?

JavaScript features 7 primitive data types:

 string (e.g., "Hello")

 number (e.g., 42 or 3.14)

 bigint (for large integers)

 boolean (true or false)

 undefined (unassigned values)

 null (intentional absence of value)

 symbol (unique identifiers)

7. Difference between primitive and reference types.

Feature Primitive Types Reference Types

Data Types String, Number, Boolean, Null, Undefined, Symbol, Big Object, Array, Functio
Int n
Storage Stored directly on the Stack Stored on the Heap;
stack stores a pointer
(reference)

Mutability Immutable (cannot be changed, only replaced) Mutable (properties


can be added or
modified)

Assignmen Copy by Value: New variable gets a real copy Copy by Reference:
t New variable points
to the same object

Compariso Compared by value Compared


n by reference (memor
y address)

8. What is type coercion?

Type coercion is the automatic or implicit conversion of a value from one data type to
another (such as a string to a number).

9. Explain truthy and falsy values.

Truthy and falsy are programming concepts used to evaluate whether a non-Boolean value
(like a string, number, or object) should be treated as true or false in conditional logic.

Falsy Values

Falsy values represent an empty or non-existent state. In languages like JavaScript and
Python, a limited, specific list of values evaluates to false:

 The boolean: false

 Numbers: 0, -0, or 0n (BigInt)

 Strings: "" or '' (empty strings)

 Empty/Missing types: null and undefined

 Mathematical errors: NaN (Not-a-Number)

Truthy Values

A truthy value is simply any value that is not on the falsy list. Whenever these values appear
in a condition, they evaluate to true:

 Booleans: true

 Numbers: Any non-zero number (e.g., 1, -5, 3.14)


 Strings: Any string with characters, including spaces (e.g., "hello", "0", "false")

 Objects & Arrays: Any object, function, or array, even if empty (e.g., {}, [])

10. What is NaN?

11. Difference between null and undefined. \

undefined: Means a variable has been declared but not yet assigned a
value. It is the default state that JavaScript automatically gives to things that
haven't been set.
null: Is an intentional assignment by a developer to indicate that a variable
is deliberately empty or has no value

12. What is scope in JavaScript?

ypes of Scope in JavaScript

JavaScript primarily uses three types of scope:

 Global Scope: Variables declared outside of any function or block have global scope. They
can be accessed and modified from anywhere in your entire program.

 Function (Local) Scope: Variables declared within a function are local to that function. They
cannot be accessed from outside the function where they were defined.

 Block Scope: Introduced in ES6, variables declared with let and const inside a block (code
within {}) are restricted to that specific block. This applies to structures like if statements and
loops.

13. What is lexical scope?

JavaScript uses lexical scoping, meaning the accessibility of variables is determined by their
position in the source code. Nested functions have access to variables declared in their outer
(parent) scopes.

14. What is block scope?

Introduced in ES6, variables declared with let and const inside a block (code within {}) are
restricted to that specific block. This applies to structures like if statements and loops.

15. What is function scope?

Variables declared within a function are local to that function. They cannot be accessed from
outside the function where they were defined.

16. What is global scope?


Variables declared outside of any function or block have global scope. They can be accessed
and modified from anywhere in your entire program.

17. What are template literals?

18. What is destructuring?

19. What is the spread operator?

20. What is the rest operator?

Functions & Closures

21. What are first-class functions?

First-class functions are a programming language feature where functions are treated like
any other variable or data type . In languages with this feature, you can assign functions to
variables, pass them as arguments to other functions, return them from functions, and store
them in data structures.

22. What is a callback function?

A callback function is a function passed into another function as an argument, which is then
executed (or "called back") by the outer function to complete a specific task or routine

Callbacks are a fundamental part of programming (especially in languages like JavaScript).


They are incredibly useful in two main scenarios:

 Asynchronous Operations: They ensure that a block of code doesn't execute until a time-
consuming task (like fetching data from an API, reading a file, or waiting for a user to click a
button) has finished.

 Event Handling: They let you define custom behavior that runs in response to a specific
event.

23. What is a higher-order function?

A higher-order function is a function that either takes one or more functions as arguments or
returns a function as its result.

Methods like .map(), .filter(), and .reduce() in JavaScript are classic higher-order functions

24. What is a closure?

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

25. Real-world use cases of closures.

Data Encapsulation & Private Variables

function createBankAccount(initialBalance) {
let balance = initialBalance; // Private variable

return {

deposit: (amount) => {

balance += amount;

return balance;

},

getBalance: () => balance,

};

const myAccount = createBankAccount(500);

[Link](100); // returns 600

[Link]([Link]); // undefined (cannot be accessed directly)

State Management in UI and React Hooks

function createCounter() {

let count = 0; // Remembers this state

return function () {

count++;

return count;

};

const increment = createCounter();

increment(); // 1

increment(); // 2

Optimization: Memoization (Caching)

function memoizedExpensiveCalculation() {

let cache = {}; // The closure holds this cache

return function (num) {

if (num in cache) return `Fetching cached: ${cache[num]}`;

const result = num * 2; // Simulated heavy work


cache[num] = result;

return `Calculated: ${result}`;

};

const compute = memoizedExpensiveCalculation();

26. What is currying?

Currying is used in JavaScript to break down complex function calls into smaller, more
manageable steps. It transforms a function with multiple arguments into a series of
functions, each taking a single argument.

 It converts a function with multiple parameters into a sequence of functions.

 Each function takes a single argument and returns another function until all arguments are
received.

 Helps in functional programming by enabling function reusability and composition.

// Normal Function

// function add(a, b) {

// return a + b;

// }

// [Link](add(2, 3));

// Function Currying

function add(a) {

return function(b) {

return a + b;

const addTwo = add(5); // First function call with 5

[Link](addTwo(4));

Currying with Arrow Functions


const add = a => b => a + b;

[Link](add(5)(4));

27. What is function composition?

Function composition is the process of combining two or more functions to produce a new
function. It involves building a pipeline where the output of one function serves as the input
for the next.

28. Difference between function declaration and expression.

Feature Function Declaration Function Expression

Hoisting Fully Hoisted. You can call the Not Hoisted. You must define
function before it is defined in it before you can call it.
your code.

Syntax Starts with Defined as part of a larger


the function keyword as a expression, typically assigned
standalone statement. to a variable.

Naming Must have a name. Can be anonymous (no


name) or named.

Execution Processed before any code is Executed only when the


executed. interpreter reaches that
specific line.

 Syntax Examples:

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

o Expression: const add = function(a, b) { return a + b; };

29. What are arrow functions?


30. function multiply(a, b) {
31. return a * b;
32. }
33. Arrow Function:
34. javascript
35. const multiply = (a, b) => a * b;

36. Difference between arrow function and normal function.


37. What is IIFE?

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs the exact
moment it is defined. It is a common design pattern primarily used to create a private, local
scope, which prevents variables and functions from polluting the global namespace.

javascript

(function() {

let message = "Hello World!";

[Link](message); // Output: Hello World!

})();

 Data Privacy: Variables declared inside the IIFE cannot be accessed from the outside,
keeping your implementation details hidden and secure.

 Avoiding Naming Collisions: Since everything inside the IIFE is scoped locally, you can use
common variable names (like i or count) without worrying about overwriting global variables
of the same name.

 Setup Logic: It is highly useful for initialization or setup code that you only need to run once
and do not need to call again

38. What is memoization?

Memoization is an optimization technique in JavaScript used to speed up computer


programs by caching the results of expensive function calls. When a function is called with
the same inputs, the program returns the cached result instead of recalculating it.

39. What is pure function?

A pure function in JavaScript is a function that consistently returns the same output for the
same input and produces no observable side effects.

 Predictability: They are easy to reason about because their behavior is isolated.

 Testability: Since they don't depend on external state, you don't need complex setups or
mocks to unit test them.

 Memoization: Because the same inputs always yield the same output, results can be cached
to improve performance.

 Concurrency: They are safer to use in parallel environments because they don't share or
modify external data.

40. What is recursion?

41. What is debounce?


In JavaScript, debounce is a performance optimization technique used to limit the frequency
of function calls. It ensures that a function is only executed after a specific period of "quiet
time" where no new events are triggered.

function debounce(func, wait) {

let timeout;

return function(...args) {

const context = this;

// Clear the existing timer if the function is called again

clearTimeout(timeout);

// Start a new timer

timeout = setTimeout(() => {

[Link](context, args);

}, wait);

};

42. What is throttle?

In JavaScript, throttling is a performance optimization technique that limits how often a


function can run over a given period of time.

High-frequency events can trigger functions hundreds of times per second, which causes
performance bottlenecks, browser lag (jank), or server overload. Throttling ensures smooth
operation while maintaining a responsive experience.

function throttle(func, limit) {

let inThrottle;

return function(...args) {

if (!inThrottle) {

[Link](this, args); // Execute the function immediately

inThrottle = true; // Set the cooldown flag

setTimeout(() => inThrottle = false, limit); // Reset after the delay

};

}
43. Implement debounce function.

44. Implement throttle function.

45. What is call(), apply(), and bind()?

1. call()

The call() method invokes a function immediately and allows you to pass arguments to the
function one by one (comma-separated).

 Use case: When you need to execute a function right away and know the exact arguments.

 Syntax: [Link](thisContext, arg1, arg2);

2. apply()

The apply() method also invokes a function immediately, but it takes all of its arguments as a
single array.

 Use case: When you have an array of arguments and want to execute a function right away
(or when using variadic functions like [Link](null, myArray)).

 Syntax: [Link](thisContext, [arg1, arg2]);

3. bind()

The bind() method does not execute the function immediately. Instead, it creates a brand-
new function with a permanently locked this context that you can execute later.

 Use case: When you need to pass a function as a callback or event handler, but want to
ensure that this retains the correct object context when it eventually runs.

 Syntax: const newFunc = [Link](thisContext, arg1, arg2);

Quick Comparison

Feature call() apply() bind()

Execution Immediately Immediately Later (creates a new


function)

Argument Passed Passed as an Passed individually


s individually array (or during later
execution)

46. Difference between bind and arrow function.


Comparison of bind() vs. Arrow Functions
Feature bind() Method Arrow Function (=>)

this Binding Explicitly binds this to a specific Lexically inherits this from the
object at creation. surrounding scope.

Function Creates a new copy of an existing Defines a new function with a concise
Creation function with a fixed this. syntax.

Constructors Bound functions can be used Cannot be used as constructors


with new. (throws an error with new).

Arguments Has its own arguments object. Does not have its
Object own arguments object (must use rest
parameters).

Re-binding Cannot be re-bound once a function this value can never be changed
is already bound. via call, apply, or bind.

Objects & Prototypes

41. What is an object?

42. What is prototype inheritance?

43. What is __proto__?

44. Difference between prototype and prototypal inheritance.

45. What is constructor function?

46. What are classes in JavaScript?

47. Difference between class and constructor function.

48. What is object freezing?

49. Difference between seal() and freeze().

50. What is shallow copy vs deep copy?

1. Shallow Copy

When you create a shallow copy, the outer layer is a new object, but inner arrays or objects
point to the same memory addresses as the original.

 JavaScript Example: Using the spread operator ... or [Link]().


2. Deep Copy

When you create a deep copy, every level of the object structure is recursively cloned. The
new object is entirely isolated from the original.

 JavaScript Example: Using structuredClone() or libraries like [Link]().

51. How do you clone an object?

52. What is [Link]()?

53. What is this keyword?

54. Explain this in arrow functions.

55. What is optional chaining?


56. const city = user?.address?.city;

57. What is nullish coalescing operator?

58. What is object destructuring?

59. What is dynamic property access?

60. Difference between Map and Object.

61. Difference between Set and Array.

Arrays

61. Difference between map(), filter(), and reduce().

62. Difference between forEach and map.

63. How does reduce work?

64. Difference between slice and splice.

65. Difference between find and filter.

66. What is flat()?

67. How do you remove duplicates from array?

68. How do you flatten nested arrays?

69. What is array destructuring?

70. What are immutable array methods?

71. Difference between push/pop and shift/unshift.

72. What is chaining in arrays?

73. const products = [


74. { name: 'Shirt', price: 15 },
75. { name: 'Shoes', price: 50 },
76. { name: 'Hat', price: 25 }
77. ];
78.
79. // Chaining filter and map in a single sequence
80. const expensiveTaxed = products
81. .filter(item => [Link] >= 20) // Returns Shoes and Hat
82. .map(item => [Link] * 1.1);

83. How does sort() work internally?

84. What is stable sorting?

85. Implement custom map() polyfill.

Async JavaScript

76. What is asynchronous programming?

Asynchronous programming is a paradigm that allows tasks to run independently in the


background. Instead of freezing a program to wait for a time-consuming operation (like
downloading a file or fetching data), the program continues executing other tasks and
processes the result later, resulting in highly responsive and efficient applications.

77. What is callback hell?

Callback hell is an anti-pattern in asynchronous programming where multiple nested callback


functions are chained together. Commonly referred to as the "Pyramid of Doom", this heavily
indented structure—caused by sequential operations relying on previous results—makes
code incredibly difficult to read, debug, and maintain.

78. What are Promises?

JavaScript Promises make handling asynchronous operations like API calls, file loading, or
time delays easier. Think of a Promise as a placeholder for a value that will be available in the
future. It can be in one of three states

 Pending: The task is in the initial state.

 Fulfilled: The task was completed successfully, and the result is available.

 Rejected: The task failed, and an error is provided.

let checkEven = new Promise((resolve, reject) => {

let number = 4;

if (number % 2 === 0) resolve("The number is even!");

else reject("The number is odd!");

});
checkEven

.then((message) => [Link](message)) // On success

.catch((error) => [Link](error)); // On failure

79. Promise states.

80. Difference between [Link] and [Link].

1. [Link]() Method

Waits for all promises to resolve and returns their results as an


array. If any promise is rejected, it immediately rejects.
[Link]([
[Link]("Task 1 completed"),
[Link]("Task 2 completed"),
[Link]("Task 3 failed")
])
.then((results) => [Link](results))
.catch((error) => [Link](error));

2. [Link]() Method

Waits for all promises to settle (fulfilled or rejected) and returns


results.
[Link]([
[Link]("Task 1 completed"),
[Link]("Task 2 failed"),
[Link]("Task 3 completed")
])
.then((results) => [Link](results));

81. Difference between [Link] and [Link].

3. [Link]() Method

[Link]() Method resolves or rejects as soon as the first


promise settles.
[Link]([
new Promise((resolve) =>
setTimeout(() =>
resolve("Task 1 finished"), 1000)),
new Promise((resolve) =>
setTimeout(() =>
resolve("Task 2 finished"), 500))
]).then((result) =>
[Link](result))
.catch(err => [Link](err));

4. [Link]() Method

[Link]() Method resolves with the first fulfilled promise. If


all are rejected, it rejects with an AggregateError.
[Link]([
[Link]("Task 1 failed"),
[Link]("Task 2 completed"),
[Link]("Task 3 completed")
])
.then((result) => [Link](result))
.catch((error) => [Link](error));

82. What is async/await?

 async/await is a modern programming feature that lets you write asynchronous, non-
blocking code in a clean, sequential manner. Instead of chaining complex callbacks
or .then() statements, it allows asynchronous operations to read and behave like traditional
synchronous code.

 async: Placed before a function declaration, it ensures that the function automatically
returns a Promise.

 await: Placed before a Promise inside an async function, it pauses the function's execution
until the Promise resolves or rejects, without freezing the main thread.

 Under the hood, async/await is "syntactic sugar" built on top of JavaScript Promises. It allows
you to pause and resume function execution so that you can capture resolved values directly
into variables rather than passing them into callback functions.
 function fetchUserData() {
 return fetch('[Link]
 .then(response => [Link]())
 .then(data => [Link]([Link]))
 .catch(error => [Link](error));
 }

 async function fetchUserData() {


 try {
 const response = await fetch('[Link]
 const data = await [Link]();
 [Link]([Link]);
 } catch (error) {
 [Link](error);
 }
 }
83. How does async/await work internally?

84. What is the event loop?

it allows for asynchronous, non-blocking execution, ensuring the main thread doesn't
freeze when handling slow operations

The event loop accomplishes this through a few interconnected components:

 Call Stack: The primary thread where your synchronous code is executed one step at a time.

 Web APIs: Background environments (managed by the browser or [Link]) that handle time-
consuming tasks like setTimeout or fetching data, so they don't block the stack.

 Task Queues (Callback/Macrotask & Microtask): Holding areas where asynchronous tasks
wait once they are completed in the background.

How the Event Loop Works

1. Check the Stack: The event loop continually watches the Call Stack.

2. Execute Synchronous Code: Any immediate code is placed on the Call Stack and runs to
completion.

3. Handle Async: When an asynchronous function is called, it is handed off to the Web APIs.

4. Queue Tasks: Once the background task finishes (e.g., a timer expires), its callback function is
sent to one of the Task Queues.

5. Process the Queue: When the Call Stack is completely empty, the event loop moves the
waiting tasks from the queue onto the Call Stack to be executed.

Not all tasks wait in the same queue. There are two main types:

 Microtask Queue: Has higher priority. Tasks like Promises are placed here and are executed
immediately after the current stack finishes, before moving on to any other queues.

 Callback/Macrotask Queue: Tasks like setTimeout, setInterval, and I/O events are placed
here and are only executed after the Microtask Queue is completely empty.

85. Explain microtask queue and callback queue.

86. Difference between setTimeout and setImmediate.

87. Difference between [Link] and Promise.

88. What are Web APIs?

89. How does JavaScript handle concurrency?

90. Implement [Link] polyfill.

These are among the most repeated senior-level interview questions.

DOM & Browser


91. What is DOM?

92. Difference between DOM and Virtual DOM.

93. What is event bubbling?

94. What is event capturing?

95. What is event delegation?

96. Difference between stopPropagation and preventDefault.

97. What is localStorage vs sessionStorage vs cookies?

98. Key Differences at a Glance


Feature localStorage sessionStorage Cookies

Persistence Permanent (Does not Temporary (Expires when Defined by expiration


expire; must be cleared the browser tab or window date or session-based
manually or via script) is closed)

Capacity ~5MB to 10MB ~5MB Very small (limited to


~4KB)

Server Client-side only (Never Client-side only (Never Sent with every HTTP
Access sent to the server sent to the server request (can affect
automatically) automatically) performance)

Accessibility Accessible across all Tab-specific (Accessible Accessible by both


tabs/windows of the only within the specific client-side scripts and
same origin tab) server-side

99. What causes memory leaks in frontend apps?

Memory leaks in frontend apps occur when applications retain references to unused data,
preventing the browser's garbage collector from freeing up memory. This causes the app's
memory usage to continually grow, leading to sluggishness, frozen screens, and eventual
browser crashes. C

 Global Variables: Creating accidental global variables (e.g., omitting let, const, or var in
JavaScript) or heavily relying on them, meaning they live for the entire lifecycle of the tab.

Closures: Keeping references to variables inside closures that live longer than the scope they
were created in.

 Uncleared Timers & Intervals: Forgetting to clear setInterval or setTimeout functions,


causing them to continually run and hold onto references in the background.
100. How do you optimize website performance?

Optimizing website performance involves improving page loading speeds and responsiveness
by reducing file sizes, streamlining server requests, and optimizing browser rendering. This
enhances user experience, boosts SEO, and increases conversions.

A comprehensive performance strategy focuses on the following key areas:

1. File and Code Optimization

 Minification & Compression: Remove unnecessary characters (spaces, comments) from


HTML, CSS, and JavaScript files. Use formats like Gzip or Brotli to compress files sent from
the server to the browser.

 Asset Bundling: Combine multiple CSS and JavaScript files into fewer files to minimize HTTP
requests.

 Remove Unused Code: Audit your codebase and third-party plugins to eliminate dead or
redundant code.

2. Media Management

 Image Optimization: Compress images without noticeably losing quality and convert them
into modern, web-optimized formats like WebP or AVIF.

 Lazy Loading: Delay the loading of images and videos located below the fold until the user
scrolls down to them.

 Specify Dimensions: Always define width and height attributes for images and videos so the
browser can reserve exact space, preventing layout shifts.

3. Caching and Delivery

 Browser Caching: Instruct the user’s browser to store static files locally (like stylesheets and
logos) so they don't have to be downloaded on repeated visits.

 Content Delivery Networks (CDNs): Route user requests through globally distributed servers
so your website's static files are delivered from a location geographically closest to the user.

 Reduce Redirects: Limit HTTP redirects (like 301 and 302), as they generate additional
requests and slow down the initial page load.

4. Server-Side Improvements

 Fast Hosting: Upgrade to high-performance hosting plans (like VPS or dedicated servers) that
offer sufficient bandwidth and resources.

 Database Optimization: Clean up databases by clearing out spam comments, revisions, and
unused data, and set up indexing for faster query lookups.

 Avoid Render-Blocking Scripts: Place critical CSS in the HTML header, and
use async or defer attributes on JavaScript files so the browser can display page content
without waiting for scripts to download.

How to Measure Progress


Before making changes, establish a performance baseline using official diagnostic tools:

 Use Google PageSpeed Insights to test and evaluate your Core Web Vitals.

 Use GTmetrix or WebPageTest to identify specific loading bottlenecks and track your
improvements over time.

101. Explain CORS.

VERY IMPORTANT Coding Questions (Frequently Asked)

These are repeatedly asked in senior frontend interviews:

 Implement debounce

 Implement throttle

 Implement [Link]

 Flatten nested array

 Deep clone object

 Implement custom bind

 Implement EventEmitter

 Implement memoization

 Implement currying

 LRU Cache implementation

 Polyfill for map/filter/reduce

 Infinite currying

 Retry failed API calls

 Sequential promise execution

 Custom setTimeout

 Build pub-sub system

Most Important Topics to Prepare First

If you are short on time, focus on these first:

1. Closures

2. Event Loop

3. Promises
4. Async/Await

5. this keyword

6. Prototypes

7. Debounce/Throttle

8. call/apply/bind

9. [Link]

10. Event Delegation

11. Polyfills

12. Memory leaks

13. Deep copy vs shallow copy

14. Microtask vs callback queue

15. Array methods

These are the highest-frequency interview topics in recent JavaScript interviews.

You might also like