Top JavaScript Interview Questions and Answers for 2025



 JavaScript is one of the most popular programming languages, used extensively for building interactive websites and web applications. If you're preparing for a JavaScript interview, here’s a comprehensive guide to the different types of questions you may encounter, from basic to advanced levels.


1. What is JavaScript? Explain its features.
JavaScript is a high-level, interpreted programming language used primarily for web development. JavaScript was developed by Brendan Eich in 1995 while he was working at Netscape Communications Corporation. It enables interactive web elements, dynamic content, and behavior changes within web pages. Its key features include being lightweight, versatile, and supporting both object-oriented and functional programming paradigms. Brendan Eich created the language in just 10 days, as it was originally intended as a lightweight scripting language for use within web browsers. Initially named “Mocha,” it was later renamed “LiveScript” before settling on the name “JavaScript” as a marketing decision to associate it with the growing popularity of Java programming language at that time. JavaScript was officially released in Netscape Navigator 2.0 in September 1995.

2. What are the different data types present in JavaScript?
i. Primitive Data Type 1. String 2. Null 3. Number 4. Bollean 5. Undefined 6. Symbol
ii. Refrence Data Type 1. Array 2. Object

3. Explain the differences between let, const, and var in variable declaration.
var declares a variable globally scoped or functionally scoped that can be reassign & redeclare, let declares a block-scoped variable that can be reassigned but not redeclare, and const declares a block-scoped variable that cannot be reassigned. let and const are part of ES6 (ECMAScript 2015) and have a more predictable scope than var.

4. What are the differences between undefined and null in JavaScript?
undefined represents a variable that has been declared but has not been assigned a value. null is an assignment value representing the absence of any object value. In other words, undefined means a variable has been declared but not defined, while null represents the intentional absence of an object value.

5. Describe the differences between == and === in JavaScript.
== is the equality operator and checks for equality after performing type coercion, which means it tries to convert operands to the same type before comparing. === is the strict equality operator and checks for equality without type coercion; it returns true only if the operands are of the same type and have the same value.

6. Explain the concept of hoisting in JavaScript.
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compilation phase. However, only declarations are hoisted, not initialization. 
For example:
javascriptCopy code console.log(x); // Output: undefined var x = 5;
is interpreted as: var x; console.log(x); // Output: undefined x = 5;

7. What are callbacks? How are they used in JavaScript?
Callbacks are functions passed as arguments to other functions to be executed later or asynchronously. They are commonly used in asynchronous operations or to ensure that certain code runs only after another code has finished execution.

8. How do you handle asynchronous operations in JavaScript?
Asynchronous operations in JavaScript can be handled using callbacks, promises, async/await, and event listeners. These mechanisms help manage code execution when dealing with operations that may take time to complete, like fetching data from an API or reading files.

9. What is the Event Loop in JavaScript? How does it work?
The Event Loop is a mechanism that handles asynchronous operations in JavaScript. It continuously checks the call stack and the task queue. When the call stack is empty, it takes the first task from the queue and pushes it onto the call stack, allowing it to be executed.

10. What is the purpose of the this keyword in JavaScript?
this refers to the context within which a function is executed. Its value is determined by how the function is called. In the global scope, this refers to the global object (e.g., window in browsers). Inside a function, this depends on how the function is invoked: in regular function calls, it refers to the global object, but in methods, it refers to the object that called the method.

11. What is the purpose of the bind, call, and apply methods?
•bind(): Creates a new function that, when called, has its this keyword set to a specific value, and arguments can be partially or fully preset.
•call(): Invokes a function with a specified this value and passes arguments individually.
•apply(): Similar to call(), but it accepts arguments as an array.

12. What is a Promise in JavaScript?
A Promise is an object representing the eventual completion or failure of an asynchronous operation. It provides a cleaner way to work with asynchronous code compared to callbacks, allowing chaining and handling success or failure through .then() and .catch() methods.

13. Explain the concepts of async and await in JavaScript.
async functions are functions that operate asynchronously by implicitly returning a Promise. They allow the use of await, which pauses the execution of an async function until a Promise is settled (resolved or rejected), making asynchronous code more readable and manageable.

14. What are arrow functions in JavaScript?
Arrow functions are a concise way to write function expressions in JavaScript, introduced in ES6. They have a shorter syntax than regular functions and lexically bind this, meaning they don’t have their own this and use this from the surrounding code.

15. Explain the concept of the Event Loop and how it handles concurrency in JavaScript.
The Event Loop is a mechanism in JavaScript that handles asynchronous operations by putting events in a queue and executing them in a loop. It manages the call stack, the task queue (also known as the callback queue), and the microtask queue. This allows JavaScript to be non-blocking and handle multiple concurrent operations efficiently.

16. What is destructuring in JavaScript?
Destructuring is a feature in JavaScript that allows for extracting data from arrays or objects into distinct variables, making it more convenient to work with complex data structures.

17. Explain the difference between map, forEach, and filter array methods in JavaScript.
•map() creates a new array by applying a function to each element of the original array.
•forEach() executes a provided function once for each array element.
•filter() creates a new array with elements that pass a test specified by a provided function.

18.What is the purpose of the typeof operator in JavaScript?
The typeof operator is used to determine the data type of a variable or an expression, returning a string indicating the type (e.g., 'number', 'string', 'boolean', 'object', 'function', 'undefined', etc.).

19. Explain the difference between NaN and isNaN() in JavaScript.
•NaN stands for “Not a Number” and is a specific value in JavaScript representing an unrepresentable value.
•isNaN() is a function that checks whether a value is NaN or can be converted into a NaN value. However, it has some quirks and may return unexpected results.

20. Explain the concept of scope in JavaScript.
Scope refers to the visibility and accessibility of variables in different parts of a program. JavaScript has function scope (variables defined inside a function are local to that function) and block scope (variables declared with let and const are block-scoped, limited to the block they are declared in).

21. What are template literals in JavaScript?
Template literals are a way to create strings in JavaScript, introduced in ES6, using backticks ( ) instead of single or double quotes. They allow embedded expressions (${expression}) within the string, making string interpolation and multiline strings more convenient.

22. Explain the concept of NaN and how to check for NaN in JavaScript.
NaN stands for “Not a Number” and is a special value of the number type that indicates an unrepresentable value resulting from an invalid mathematical operation.
To check for NaN, you can use the isNaN() function. However, note that isNaN() can sometimes produce unexpected results when checking non-numeric values. Alternatively, Number.isNaN() was introduced to provide a more reliable check for NaN.

23. What are the differences between Object.keys(), Object.values(), and Object.entries()?
•Object.keys() returns an array containing the keys of an object.
•Object.values() returns an array containing the values of an object.
•Object.entries() returns an array of arrays, where each inner array consists of a key-value pair (as arrays) from the object.

24. Explain the concept of the spread operator (...) in JavaScript.
The spread operator (...) is used to expand elements of an iterable (like arrays, strings, or objects) into individual elements. It is commonly used for array/object destructuring, function arguments, and array/object merging.

25. What is the purpose of the localStorage and sessionStorage objects in JavaScript?
• localStorage and sessionStorage are web storage APIs that allow web applications to store key-value pairs locally within the user’s browser.
• localStorage persists data across browser sessions, while sessionStorage stores data for the duration of the session.

26. Explain the concept of try...catch in JavaScript.
try...catch is a control structure used for error handling in JavaScript. Code that may potentially throw an error is placed within the try block, and if an error occurs, it is caught and handled in the catch block.

27. What is a callback hell? How can it be mitigated in JavaScript?
Callback hell refers to the situation where multiple nested callbacks occur, making the code complex, difficult to read, and manage. It usually happens in asynchronous operations. To mitigate callback hell, various approaches like using named functions, modularization (breaking down functions), promises, or async/await can be employed to write cleaner, more readable asynchronous code.

28. Explain the concept of JSON in JavaScript.
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is based on a subset of the JavaScript language and is commonly used for data transmission between a server and a web application.

29. Explain the concept of currying in JavaScript.
Currying is the process of converting a function with multiple arguments into a sequence of functions, each taking a single argument. This allows partial application of the function, providing a powerful way to create reusable higher-order functions.

30. What are Web Workers in JavaScript?
Web Workers are a browser feature that allows running scripts in background threads, separate from the main execution thread. They enable multi-threaded JavaScript and are commonly used for handling computationally expensive tasks without blocking the UI.

33. What are IIFE (Immediately Invoked Function Expressions) in JavaScript?
IIFE is a design pattern in JavaScript where a function is defined and executed immediately after being created. It helps avoid polluting the global scope and is often used to create private scopes for variables.

34. Explain the concept of the arguments object in JavaScript.
The arguments object is an array-like object available inside functions that contain the values of all the arguments passed to that function. It allows accessing all arguments passed to a function regardless of the number of parameters defined.

35. Explain the concept of memoization in JavaScript.
Memoization is an optimization technique used to cache the results of expensive function calls and return the cached result when the same inputs occur again. It helps in improving performance by avoiding redundant computations.

36. What is the purpose of the fetch API in JavaScript?
The fetch API is used to make asynchronous HTTP requests in JavaScript. It provides a more powerful and flexible way to handle network requests compared to older methods like XMLHttpRequest.

37. What are the differences between for...in and for...of loops in JavaScript?
• for...in iterates over the enumerable properties of an object, including properties in the prototype chain, and is generally used for iterating over object keys.
• for...of iterates over iterable objects (like arrays, strings, maps, sets, etc.) and is used to access their values directly.

38. Explain the concept of event delegation in JavaScript.
Event delegation is a technique where a single handler is attached to a parent element to manage events on its child elements. Instead of attaching event handlers to multiple child elements, events are captured and handled at a higher level, improving performance and reducing memory usage.

39. What is the purpose of the Symbol data type in JavaScript?
Symbol is a primitive data type introduced in ES6 that represents a unique identifier. It’s often used as an object property key to avoid name collisions in cases where multiple parts of a program may access the same object.

40. Explain the concept of the Promise.all() method in JavaScript.
Promise.all() is a method that takes an array of promises as an input and returns a single promise. It resolves when all the promises in the array have resolved, or rejects immediately if any of the promises reject. It’s commonly used for handling multiple asynchronous operations concurrently.

41. What are generator functions in JavaScript? Explain their usage and benefits.
Generator functions are special functions that can be paused and resumed, allowing for a sequential execution of code. They use the yield keyword to pause execution and return values one at a time. They provide a way to work with sequences and can be more memory efficient than regular functions for handling large datasets.

42. Explain the concept of a polyfill in JavaScript.
A polyfill is a piece of code (usually a JavaScript snippet) used to provide modern functionality in older browsers that do not support certain features or APIs. Polyfills enable developers to use newer features while ensuring backward compatibility.

43. What is the purpose of the Map and Set objects in JavaScript?
• Map is a collection of key-value pairs where keys can be of any data type. It allows for easy iteration and data retrieval based on keys.
• Set is a collection of unique values, which means it cannot contain duplicate values. It’s commonly used to create lists of unique items.

44. Explain the concept of prototypal inheritance vs classical inheritance.
• Prototypal inheritance in JavaScript is based on prototypes, where objects inherit properties and methods directly from other objects. It is more flexible and dynamic.
• Classical inheritance, often found in languages like Java or C++, involves creating classes and instances, where objects are created from class blueprints. It’s a more rigid and hierarchical structure.

45. Explain the purpose and usage of the async attribute in <script> tags.
The async attribute in <script> tags is used to asynchronously load and execute scripts without blocking the rendering of the web page. It allows the browser to continue parsing and rendering the page while the script is being fetched in the background. When the script is downloaded, it’s executed without pausing the rendering.

46. What is the difference between the textContent property and the innerHTML property in JavaScript?
• textContent sets or gets the text content of an element, treating any content as raw text, even HTML tags. It doesn’t parse the content as HTML.
• innerHTML sets or gets the HTML content of an element, allowing HTML tags to be inserted or retrieved as part of the content. It parses content as HTML.

47. Explain the concept of the Event-driven programming paradigm in JavaScript.
Event-driven programming is a programming paradigm based on the occurrence of events, like user actions (clicks, keypresses), timer events, or system events. The program responds to these events by executing predefined code blocks (event handlers) associated with those events.

48. What are the differences between localStorage and sessionStorage?
• localStorage stores data with no expiration date, allowing data to persist even after the browser is closed and reopened.
• sessionStorage stores data for a single session (tab/window), and the data is cleared when the session ends (when the tab/window is closed).

49. Explain the purpose of the yield keyword in generator functions in JavaScript.
The yield keyword is used in generator functions to pause the execution and yield a value. It allows generators to produce a sequence of values one at a time, maintaining their state between each yield statement.

50. What are the differences between document.onload and window.onload in JavaScript?
• document.onload is an event that fires when the DOM and all its contents (such as images, stylesheets, etc.) are fully loaded.
• window.onload is an event that fires when the entire page, including all its resources like images, stylesheets, and frames, has finished loading

Mutability in JavaScript

JavaScript divides data types into:

1. Primitive Data Types

  • Number

  • String

  • Boolean

  • Null

  • Undefined

  • BigInt

  • Symbol

2. Non-Primitive (Reference) Data Types

  • Object

  • Array

  • Function

  • Date

  • Map / Set
    (and all objects)


🔵 1. Primitive Data Types → Immutable

Immutable means:
➡️ You cannot change the actual value stored in memory
➡️ If you modify, JS creates a new value instead of changing the old one

✔ Example:

let x = "hello"; x[0] = "H"; // ❌ doesn't change the string console.log(x); // "hello"

Strings cannot be edited character by character.

Another example:

let a = 10; let b = a; // copy value b = 20; console.log(a); // 10 (unchanged) console.log(b); // 20

➡️ Changing b does NOT affect a
➡️ Because primitives are copied by value


🟣 2. Non-Primitive Data Types → Mutable

Mutable means:
➡️ You can change the value stored inside the object/array
➡️ The reference stays the same

✔ Example (Objects are mutable)

let obj = { name: "Pranjal" }; obj.name = "Dev"; // value **modified** console.log(obj); // { name: "Dev" }

You can change values without creating a new object.

✔ Example (Arrays are mutable)

let arr = [1, 2, 3]; arr.push(4); console.log(arr); // [1, 2, 3, 4]

🟡 Reference Behavior (Important)

let a = { city: "Delhi" }; let b = a; // reference copy b.city = "Mumbai"; console.log(a.city); // "Mumbai" 😮 console.log(b.city); // "Mumbai"

➡️ Both point to same memory location
➡️ Mutating one changes the other


📌 Summary Table

Type Examples Mutable? Stored as Copied as
Primitive number, string, boolean... ❌ Immutable Value Value
Non-Primitive object, array, function ✅ Mutable Reference Reference

💡 Simple Explanation in One Line

  • Primitive = Value stored directly → Cannot be changed → New value created when modified

  • Non-Primitive = Stored as reference → Internal values can be changed



Conclusion

JavaScript interviews often span from basic concepts to advanced, real-world problem-solving scenarios. The key is to understand both the theoretical aspects of JavaScript and its practical applications. Whether you're being asked about closures, asynchronous programming, or object-oriented concepts, being well-prepared with these questions and explanations will give you the edge in your interview.

Post a Comment

Previous Post Next Post