JAVASCRIPT

JAVASCRIPT Interview Questions and Answers

Basics and Core Concepts

  1. What are JavaScript data types?

    • JavaScript has 7 primitive data types: undefined, null, boolean, number, string, symbol, and bigint. Objects are non-primitive data types.

    js
    // Primitive let name = "Ram"; // String let age = 25; // Number let isOnline = true; // Boolean let nothing = null; // Null let x; // Undefined let id = Symbol("id"); // Symbol let big = 12345678901234567890n; // BigInt // Non-Primitive let person = { name: "Ram" }; // Object let arr = [1, 2, 3]; // Array (object type) let func = function() {}; // Function (object type)
  2. Evaluate 6 + "52" ?

    "652"

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

    • == compares values and performs type coercion, while === compares both values and types.

    js
    1 == "1"; // true 1 === "1"; // false
  4. What is the difference between null and undefined?

    • 🔹 undefined means "Value has not been assigned yet"

      🔹 null means "Value is intentionally set to empty"

    js
    let a = null; // null -> value set to empty let b; // undefined -> value not given
  5. What is a closure?

    • A closure is a function that retains access to its lexical scope even after the function is executed outside that scope.

    js
    function outer() { const a = 10; return function inner() { console.log(a); }; } const closure = outer(); closure(); // Output: 10
  6. What is a callback function?

    • A callback function is passed as an argument to another function and is executed after the completion of that function.

    js
    function greeting(name) {
      console.log("Hello, " + name+"(callback)");
    }

    function main(callback) {
      const name = "Alice";
      console.log("this is main function")
      callback(name);  // calling the callback function
    }

    main(greeting)

⚙️ Functions, Scope, and Execution Context

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

    • var is function-scoped, while let and const are block-scoped. const cannot be reassigned.

    js
    var x = 10; // function-scoped let y = 20; // block-scoped const z = 30; // block-scoped, read-only
  2. What is hoisting in JavaScript?

    • Hoisting is JavaScript's default behavior of moving declarations to the top of their containing scope during compile time.

    js
    console.log(x); // undefined var x = 5;
  3. What is an Arrow function?

    • An arrow function is a shorter and more concise way to write function expressions in JavaScript.It was introduced in ES6 and It improves readability and avoids this binding issues

  4. What is the this keyword in JavaScript?

    • In JavaScript, the this keyword refers to the object that is executing the current function.

      But its value depends on how the function is called, not where it's written.

    js
    const person = {
      name: "Sam",
      gender:"male",
      greet: function() {
        console.log("Hello, " + this.name);
      }
    };

    person.greet(); // Hello, Sam
  5. What is a higher-order function?

    • A higher-order function is one that takes another function as an argument or returns a function as a result.

    js

    Example 1 (Taking function as argument):

    function greet(name) { return "Hello, " + name; } function main(callback) { const name = "Sam"; console.log(callback(name)); } main(greet);

    Example 2 (returns a function):

    function multiplyBy(factor) { return function (number) { return number * factor; }; } const double = multiplyBy(2); console.log(double(5));

🔁 Arrays, Objects, and Iteration

  1. What is the difference between for...in and for...of?

    • for...in iterates over keys (properties) of an object, while for...of iterates over values in an iterable (like arrays).

    js
    const arr = ["a", "b", "c"]; for (let index in arr) { console.log(index); // keys: 0, 1, 2 } for (let value of arr) { console.log(value); // values: "a", "b", "c" }
  2. What is the difference between shallow and deep copy?

    • 🔹 Shallow Copy

      A shallow copy copies only the first level of the object or array.
      If the object has nested objects, they are still referenced, not copied.


      🔹 Deep Copy

      A deep copy copies everything, including nested objects, so the copy is completely independent of the original.


    js
    const original = {
      name: "Sam",
      address: {
        city: "Delhi",
        pin: 110001
      }
    };

    // 🔸 Shallow Copy using spread
    const shallowCopy = { ...original };

    // 🔹 Deep Copy using JSON
    const deepCopy = JSON.parse(JSON.stringify(original));

    // Modify nested value
    original.address.city = "Mumbai";

    console.log(shallowCopy.address.city); //
    console.log(deepCopy.address.city);  
  3. What is array destructuring?

    • Array destructuring allows unpacking values from arrays into distinct variables.

    js
    const arr = [1, 2, 3]; const [first, second] = arr; console.log(first, second); // Output: 1, 2
  4. How do you merge two arrays?

    • You can use the spread operator or concat() to merge arrays.

    js
    Example using spread operator:
    const arr1 = [1, 2]; const arr2 = [3, 4]; const mergedArray = [...arr1, ...arr2];

    Example using concat:
    const merged = arr1.concat(arr2); console.log(merged);
  5. How to filter an array?

    • Use the filter() method to filter an array based on a condition.

    js
    const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter(num => num % 2 === 0);

⏳ Promises, Async/Await, and Callbacks

  1. What is a promise in JavaScript?

    • A Promise is a JavaScript object that represents the result of an asynchronous task like API calls, file reading, timers, etc.

    js
    const promise = new Promise((resolve, reject) => { let success = true; if (success) { resolve("Success"); } else { reject("Failure"); } });
  2. What is async/await?

    • async functions return a promise, and await pauses the execution until the promise is resolved.

    js
    const myPromise = new Promise((resolve, reject) => { const success = true; if (success) { resolve("✅ Operation Successful"); } else { reject("❌ Operation Failed"); } }); myPromise .then((result) => { console.log(result); // ✅ Operation Successful }) .catch((error) => { console.log(error); // ❌ Operation Failed });
  3. How does .then() and .catch() work?

    • .then() is used to handle the success case, while .catch() is used to handle errors.

    js
    const myPromise = new Promise((resolve, reject) => { const success = true; if (success) { resolve("✅ Task completed"); } else { reject("❌ Task failed"); } }); myPromise .then((result) => { console.log("Success:", result); }) .catch((error) => { console.log("Error:", error); });
  4. What is promise chaining?

    • Promise chaining allows you to execute multiple asynchronous operations sequentially.

    js
    Example:
    function placeOrder() {
      return Promise.resolve("Order placed");
    }

    function prepareFood(status) {
      return Promise.resolve(`${status} → Food prepared`);
    }

    function deliverFood(status) {
      return Promise.resolve(`${status} → Food delivered`);
    }

    placeOrder()
      .then(prepareFood)
      .then(deliverFood)
      .then((msg) => console.log("✅", msg))
      .catch((err) => console.log("❌ Error:", err));
  5. What is the purpose of finally() in promises?

    • The .finally() method is used to run some code after a promise is settled, no matter whether it was resolved (✅ success) or rejected (❌ error).

    js
    Example:
    const order = new Promise((resolve, reject) => { const success = true; if (success) { resolve("🍔 Order delivered"); } else { reject("❌ Order failed"); } }); order .then((msg) => { console.log("Success:", msg); }) .catch((err) => { console.log("Error:", err); }) .finally(() => { console.log("🔁 Done with order process (success or fail)"); });

🔄 Event Loop, Timers, and Concurrency

  1. What is the event loop in JavaScript?

    • The event loop manages the execution of code, handling both synchronous and asynchronous operations.

  2. What is the difference between microtasks and macrotasks?

    • Microtasks are executed after the current script has finished, but before rendering or IO tasks (e.g., Promise.then()), whereas macrotasks are handled by the event loop (e.g., setTimeout()).

  3. What is the purpose of setTimeout()?

    • setTimeout() schedules a function to run after a specified delay.

    js
    setTimeout(() => console.log("Delayed"), 1000);
  4. What is setInterval()?

    • setInterval() calls a function repeatedly at specified intervals.

    js
    setInterval(() => console.log("Repeated"), 2000);
  5. What is the clearTimeout() and clearInterval() functions?

    • clearTimeout() cancels a scheduled setTimeout(), and clearInterval() cancels a scheduled setInterval().

    js

    setTimeout:

    const timeoutId = setTimeout(() => { console.log("This will not run"); }, 3000); // Cancel it clearTimeout(timeoutId);

    setInterval:


    const intervalId = setInterval(() => { console.log("Repeating every second"); }, 1000); // Stop it after 5 seconds setTimeout(() => { clearInterval(intervalId); console.log("Stopped the interval"); }, 5000);

🧱 Classes, Inheritance, and Prototypes

  1. What is prototypal inheritance?

    • Prototypal inheritance is when objects inherit properties and methods from other objects via their prototype chain.

    js

    // Constructor function (like a blueprint)
    function Person(name) {
      this.name = name;
    }

    // Adding method to Person's prototype
    Person.prototype.greet = function () {
      console.log("Hello, my name is " + this.name);
    };

    // Create a new object using Person
    const personObj = new Person("Sam");

    personObj.greet();  
  2. How do you create a class in ES6?

    • ES6 classes provide a simpler syntax for creating constructor functions and prototypes.

    js
    // Define a class class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a sound`); } } // Create an object from the class const dog = new Animal("Dog"); dog.speak();
  3. What is inheritance in JavaScript?

    • Inheritance allows one class to extend another and reuse its properties and methods.

    js
    // Parent class class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a sound`); } } // Child class class Dog extends Animal { bark() { console.log(`${this.name} barks 🐶`); } } // Create object const myDog = new Dog("Tommy"); myDog.speak(); // Tommy makes a sound (inherited from Animal) myDog.bark(); // Tommy barks 🐶 (defined in Dog)
  4. How does super() work?

    • super() is used inside a child class constructor to call the constructor or methods of the parent class.

    js
    // Parent class class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a sound`); } } // Child class class Dog extends Animal { constructor(name, breed) { super(name); // Call parent constructor this.breed = breed; } info() { console.log(`${this.name} is a ${this.breed}`); } } const dog = new Dog("Tommy", "Labrador"); dog.speak(); // Tommy makes a sound (from Animal) dog.info(); // Tommy is a Labrador (from Dog)
  5. What is method overriding in JavaScript?

    • Method overriding occurs when a child class defines a method that is already defined in its parent class.

    js
    // Parent class
    class Animal {
      speak() {
        console.log("Animal makes a sound");
      }
    }

    // Child class overrides the speak method
    class Dog extends Animal {
      speak() {
        console.log("Dog barks");
      }
    }

    const dog = new Dog();
    dog.speak();

ES6+ Features

  1. What is destructuring in JavaScript?

  • Destructuring allows you to unpack values from arrays or properties from objects into distinct variables.

js
const person = { name: "John", age: 30 }; const { name, age } = person; // Object destructuring const [a, b] = [1, 2, 3]; // Array destructuring
  1. What is the spread operator (...)?

  • The spread operator is used to expand an iterable or object into individual elements or properties.

js
const arr1 = [1, 2]; const arr2 = [...arr1, 3, 4]; const obj1 = { a: 1 }; const obj2 = { ...obj1, b: 2 };
  1. What is the rest parameter (...args)?

  • The rest parameter collects all remaining arguments into a single array.

js
function sum(...numbers) { return numbers.reduce((acc, num) => acc + num, 0); } console.log(sum(1, 2, 3, 4)); // Output: 10
  1. What is template literals?

  • Template literals provide an easy way to interpolate variables and expressions into strings.

js
const name = "John"; const greeting = `Hello, ${name}`;
  1. What is the Map object?

  • The Map object in javascript is a collection of key-value pairs like an object "{}", where both keys and values can be any data type.

js
const myMap = new Map();

// Set values
myMap.set("name", "Sam");
myMap.set("ID number",123);
myMap.set("Boolean", true);

console.log(myMap.get("name"));     // Sam
console.log(myMap.get("ID number"));        // 123
console.log(myMap.get("Boolean"));       // true
console.log(Object.fromEntries(myMap)) // whole object

Modules and Import/Export

  1. What is the difference between CommonJS and ES6 modules?

  • CommonJS uses require and module.exports for imports and exports, while ES6 uses import and export.

js
// CommonJS const foo = require('./foo'); module.exports = foo; // ES6 import foo from './foo'; export default foo;
  1. How to import/export specific members in ES6?

  • You can import and export specific members from modules using named exports.

js
// foo.js export const foo = 1; export const bar = 2; // app.js import { foo, bar } from './foo';
  1. What is dynamic import?

  • Dynamic import allows you to import a module asynchronously.

js

// multiply.js export function multiply(a, b) { return a * b; }

// main.js // ✅ Dynamically import multiply.js and call multiply() import('./multiply.js').then(module => { const result = module.multiply(8, 5); console.log(`Result: ${result}`); }).catch(error => { console.error('Failed to load module:', error); });
  1. What is default export?

  • A default export allows a module to export a single value, which can be imported without curly braces.

js
// greet.js export default function greet() { console.log("Hello"); } // app.js import greet from './foo';
  1. What is export * from?

  • It re-exports everything from another module.

js

math.js

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


export const multiply = (a, b) => a * b;


allMath.js


export * from './math.js'; // re-exports all functions


main.js


import { add, multiply } from './allMath.js';


console.log(add(2, 3)); // 5


console.log(multiply(4, 5)); // 20


Error Handling and Debugging

  1. How do you handle errors in JavaScript?

  • JavaScript provides try...catch for handling exceptions, and finally ensures code runs after execution.

js
try { throw new Error("Something went wrong"); } catch (err) { console.error(err.message); } finally { console.log("Executed regardless of success or failure"); }
  1. What is throw in JavaScript?

  • The throw statement allows you to create custom errors.

js
throw new Error("Custom error message");
  1. What are custom errors?

  • You can create custom error classes by extending the built-in Error class.

js
class MyError extends Error { }

try {
    throw new MyError("Hey Something went wrong!");
} catch (err) {
    console.log("Caught:", err.message); //Output:Hey Something went wrong!
}
  1. What is console.trace() used for?

  • console.trace() displays the stack trace, which is useful for debugging.

js
function foo() { console.trace("Stack trace"); } foo();
  1. What is debugger in JavaScript?

  • The debugger keyword pauses the execution of code, allowing you to inspect the state of the program.

js
function test() { debugger; // Execution stops here console.log("Hello"); } test();

Memory Management and Optimization

  1. What is garbage collection in JavaScript?

  • JavaScript automatically manages memory by removing objects that are no longer reachable in the code.

  1. What are closures and memory leaks?

  • Closures can sometimes result in memory leaks if they hold references to large objects even after they are no longer needed.

  1. How to optimize memory usage in JavaScript?

  • Avoid unused variables

  • Don’t hold references unnecessarily

  • Use lazy-load for data and modules

  • Use efficient data structures like Set, Map, WeakMap

  1. What is a memory leak in JavaScript?

  • A memory leak happens when your program keeps storing data in memory that is no longer needed, and JavaScript’s garbage collector is unable to remove it — causing your app to use more and more memory over time.


  • let bigData = []; setInterval(() => { bigData.push(new Array(1000000).fill("💣")); // keeps growing }, 1000);
    Problem: bigData keeps growing and never gets cleared Result: Memory usage goes up, app becomes slow or crashes
  1. Which storage API stores data persistently?

  • localStorage


Performance Optimization

  1. What is event delegation in JavaScript?

  • Event delegation means assigning an event listener to a parent element, and handling events for its child elements.

HTML
<ul id="menu">
  <li>Home</li>
  <li>About</li>
  <li>Contact</li>
</ul>

<script>
// ✅ Add one listener to the parent
document.getElementById("menu").addEventListener("click", (event) => {
  if (event.target.tagName === "LI") {
    console.log("Clicked:", event.target.textContent);
  }
});
</script>
  1. What is debouncing?

  • Debouncing limits the rate at which a function is executed, commonly used for search input fields or resize events.

HTML
<input id="search" placeholder="Type..." />

<script>
  function debounce(fn, delay) {
    let timeout;
    return (...args) => {
      clearTimeout(timeout);
      timeout = setTimeout(() => fn(...args), delay);
    };
  }

  const search = debounce((e) => {
    console.log("Search:", e.target.value);
  }, 500);

  document.getElementById("search").addEventListener("input", search);
</script>
  1. What is throttling?

  • Throttling ensures that a function is called at most once in a specified time period, even if it's triggered many times.

HTML
<button id="btn">Click Me</button>

<script>
  function throttle(fn, delay) {
    let wait = false;
    return () => {
      if (!wait) {
        fn();
        wait = true;
        setTimeout(() => wait = false, delay);
      }
    };
  }

  document.getElementById("btn").onclick = throttle(() => {
    console.log("Clicked!");
  }, 5000); // 2 sec
</script>
  1. What is lazy loading in JavaScript?

  • Lazy loading involves loading resources or scripts only when they are needed to improve performance.


  • HTML

    <button id="load">Load Feature</button> <script type="module"> document.getElementById("load").onclick = async () => { const module = await import('data:text/javascript,export function greet(){ console.log("Hello from lazy-loaded code!"); }'); module.greet(); }; </script>
  1. What is the difference between synchronous and asynchronous code?

  • Synchronous code is executed line by line, while asynchronous code allows functions to execute independently of the main program flow (using callbacks, promises, etc.).



  1.  What is an IIFE ?

  • IIFE (Immediately Invoked Function Expression) is a function that runs immediately after it’s defined.

    js

    (function () { console.log("I am an IIFE!"); })();


  1. How to create an immutable object in JavaScript

  • We will use Object.freeze() to create an immutable object in JavaScript.
js
// Normal (mutable) object
const user1 = {
  name: "Ranit",
  age: 25
};

user1.age = 30;
console.log("Mutable:", user1.age); // ✅ Output: 30

//Immutable object using Object.freeze()
const user2 = Object.freeze({
  name: "Amit",
  age: 28
});

user2.age = 35; // ❌ Change won't happen
console.log("Immutable:", user2.age); // ✅ Output: 28
  1. What is localStorage and sessionStorage?

  • localStorage stores data with no expiration time, while sessionStorage stores data for the duration of the page session.

  1. What do you mean by Currying in JavaScript?

  • Currying is a technique where a function with multiple arguments is transformed into a series of functions, each taking one argument at a time.

js
// Normal function function add(a, b) { return a + b; } console.log(add(2, 3)); // 5 // Currying version function curriedAdd(a) { return function (b) { return a + b; }; } console.log(curriedAdd(2)(3)); // ✅ Output: 5
  1. What is Reduce() in javascript?

  • reduce() is a method used to combine all elements of an array into a single value, using a function that runs on each element one by one.

    js

    const numbers = [10, 20, 30]; const total = numbers.reduce((acc, curr) => { return acc + curr; }, 0); // initial value is 0 console.log(total); // Output: 60


Scroll to Top