javascript interview questions and answers 2022

1/8/2022

Difference between let and const in JavaScript – Best practices and example #javascript interview questions and answers 2025

Go Back

JavaScript Interview Questions and Answers (2025)

Preparing for a JavaScript interview in 2025 requires a solid understanding of both fundamental and advanced concepts. Below is a curated list of common JavaScript interview questions, along with concise answers to help you prepare effectively.
 

JavaScript Interview Questions :

1. What are the primitive data types in JavaScript?

JavaScript has seven primitive data types:

  • String: Represents textual data, e.g., "Hello".
  • Number: Represents both integer and floating-point numbers, e.g., 42 or 3.14.
  • Boolean: Represents true or false.
  • Undefined: Indicates a variable that has been declared but not assigned a value.
  • Null: Represents the intentional absence of any object value.
  • Symbol: Introduced in ES6, represents a unique and immutable identifier.
  • BigInt: Introduced in ES11, represents integers with arbitrary precision.

2. What's the difference between null, undefined, and undeclared variables?

  • Undefined: A variable declared but not assigned a value.
    let a;
    console.log(a); // Output: undefined
    
  • Null: A variable explicitly assigned with no value.
    let b = null;
    console.log(b); // Output: null
    
  • Undeclared: A variable that hasn't been declared in the current scope. Accessing it throws a ReferenceError.
    console.log(c); // ReferenceError: c is not defined
    

3. What is the difference between while and do-while loops in JavaScript?

  • While Loop: Checks the condition before executing the loop's body.
    let i = 0;
    while (i < 5) {
      console.log(i);
      i++;
    }
    
  • Do-While Loop: Executes the loop's body at least once before checking the condition.
    let i = 0;
    do {
      console.log(i);
      i++;
    } while (i < 5);
    

4. What language constructions do you use for iterating over object properties and array items?

  • Arrays:
    • for loop:
      const arr = [1, 2, 3];
      for (let i = 0; i < arr.length; i++) {
        console.log(arr[i]);
      }
      
    • forEach method:
      arr.forEach(item => console.log(item));
      
    • for...of loop:
      for (const item of arr) {
        console.log(item);
      }
      
  • Objects:
    • for...in loop:
      const obj = { a: 1, b: 2 };
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          console.log(key, obj[key]);
        }
      }
      
    • Object.keys with forEach:
      Object.keys(obj).forEach(key => {
        console.log(key, obj[key]);
      });
      

5. What are promises, and how do they work?

Promises are objects representing the eventual completion or failure of an asynchronous operation. They have three states:

  • Pending: Initial state, neither fulfilled nor rejected.
  • Fulfilled: Operation completed successfully.
  • Rejected: Operation failed.
const promise = new Promise((resolve, reject) => {
  // asynchronous operation
  if (success) {
    resolve(result);
  } else {
    reject(error);
  }
});

promise
  .then(result => {
    // handle success
  })
  .catch(error => {
    // handle error
  });

6. What are IIFEs, and where can they be used?

An Immediately Invoked Function Expression (IIFE) is a function that runs as soon as it's defined. It's commonly used to create a local scope and avoid polluting the global namespace.

(function() {
  // code inside IIFE
})();

7. Explain event delegation.

Event delegation is a technique where a single event listener is added to a parent element to manage events for its child elements. This is efficient for handling events on multiple child elements, especially when they are dynamically added or removed.

<ul id="parent">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

<script>
  document.getElementById('parent').addEventListener('click', function(event) {
    if (event.target.tagName === 'LI') {
      console.log('Clicked on', event.target.textContent);
    }
  });
</script>

8. Explain how this works in JavaScript.

The value of this depends on the context in which a function is called:

  • Global Context: In the global scope, this refers to the global object (window in browsers).
  • Function Context: In a regular function, this refers to the global object in non-strict mode and undefined in strict mode.
  • Method Context: When a function is called as a method of an object, this refers to that object.
  • Constructor Context: When using a constructor function with new, this refers to the newly created object.
const obj = {
  name: 'JavaScript',
  showName: function() {
    console.log(this.name);
  }
};
obj.showName(); // Output: JavaScript

SEO-Optimized Article: Understanding JavaScript Closures & ES6 Features

9. What is a Closure in JavaScript & Why Should You Use It?

A closure is a function that retains access to its lexical scope, even when executed outside that scope. Closures are widely used in JavaScript for data encapsulation, callbacks, and maintaining state.

Example of a Closure:

function outer() {  
  let name = "Developer Indian";  
  function inner() {  
    console.log(name);  
  }  
  return inner;  
}  
let closure = outer();  
closure(); // Output: Developer Indian  

Why Use Closures?

  • Encapsulation: Keeps variables private.
  • Data Persistence: Retains state between function calls.
  • Callback Handling: Used in event handlers and asynchronous functions.

 

9. Differences Between let, const, and var

Keyword Scope Reassignment Allowed Hoisting
var Function-scoped Yes Hoisted with undefined
let Block-scoped Yes Hoisted but not initialized
const Block-scoped No Hoisted but not initialized

10. Arrow Functions & Their Advantages

Arrow functions provide a shorter syntax and do not have their own this context, making them useful in callbacks.

let add = (a, b) => a + b;  
console.log(add(2, 3)); // Output: 5  

Advantages:

  • Concise syntax
  • No binding of this (inherits from parent scope)
  • Useful for callbacks & functional programming

11. Destructuring in ES6

Destructuring simplifies extracting values from arrays or objects.

let [a, b] = [1, 2];  
console.log(a); // Output: 1  
const user = { name: "John", age: 30 };
const { name, age } = user;
console.log(name); // Output: John
Difference between let and const in JavaScript – Best practices and example #javascript interview questions and answers 2025

Event Handling & DOM Manipulation

12. What is Event Delegation?

Event delegation allows you to attach a single event listener to a parent element, handling events from child elements efficiently.

document.querySelector("ul").addEventListener("click", function(event) {  
  if (event.target.tagName === "LI") {  
    console.log("List item clicked!");  
  }  
});  

Why Use Event Delegation?

  • Improves performance by reducing event listeners.
  • Handles dynamically added elements efficiently.

13. Event Bubbling vs. Event Capturing

Propagation Type Description
Event Bubbling Events propagate up from target to root.
Event Capturing Events propagate down from root to target.

Debugging & Best Practices

14. Tools for Debugging JavaScript Code

  • Chrome DevTools (Inspect, Debug, Console, Network tools)
  • console.log() (Basic debugging tool)
  • debugger statement (Pauses execution for inspection)

15. Strict Mode in JavaScript

Strict mode enforces stricter parsing and error handling.

"use strict";  
x = 10; // Throws an error  

Benefits of Strict Mode:

  • Prevents accidental global variables.
  • Catches silent errors.
  • Disallows duplicate parameters in functions.

 

Conclusion :


JavaScript is a versatile and powerful language, and mastering its concepts is crucial for any developer. This guide covers top JavaScript interview questions and answers for 2025, helping you prepare for your next interview. From core concepts like inheritance and closures to advanced topics like promises and ES6 features, you’re now equipped to tackle any JS interview with confidence.
These are just some of the most commonly asked JavaScript interview questions. Preparing for a JavaScript interview requires practice, hands-on coding, and a deep understanding of the language's core concepts. Good luck!

Table of content