Interview Questions

1) What are JavaScript data types?


JavaScript has 7 data types:

  • Primitive types: Number, String, Boolean, Undefined, Null, Symbol, BigInt.
  • Non-primitive type: Object (arrays, functions, etc.).

2) What is the difference between null and undefined?


  • undefined: A variable that has been declared but not assigned a value is undefined.
  • null: A special value representing the intentional absence of any object value.

3) What is a closure?


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

function outer() {
  let count = 0;
  return function inner() {
    count++;
    console.log(count);
  };
}
const counter = outer();
counter(); // 1
counter(); // 2

 

4) What is hoisting in JavaScript?


Hoisting is JavaScript's behavior of moving all declarations (var, function, class) to the top of their containing scope during compilation.

console.log(x); // undefined
var x = 5;

 

5) Explain this in JavaScript.


this refers to the context in which a function is called:

  • In a regular function: refers to the global object.
  • In an object method: refers to the object.
  • In a constructor function: refers to the new instance.
  • In arrow functions: inherits this from the surrounding context.

6) What are arrow functions and how do they differ from regular functions?


Arrow functions are a more concise way to write functions and do not have their own this context. They inherit this from the parent scope.

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

 

7) What is the event loop in JavaScript?


The event loop is a mechanism that allows JavaScript to perform non-blocking I/O operations by putting callbacks and promises in a message queue, executing them asynchronously.

8) What is the difference between == and === in JavaScript?


  • == (Equality): Compares values after type conversion.
  • === (Strict Equality): Compares both value and type.
    '5' == 5;  // true
    '5' === 5; // false
    

     

9) What is a promise?


A promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states: Pending, Fulfilled, and Rejected.

let p = new Promise((resolve, reject) => {
  let success = true;
  if (success) resolve('Success!');
  else reject('Failed!');
});

 

10) What are async/await?


async functions return a promise, and await is used inside async functions to pause the execution until the promise resolves.

async function fetchData() {
  let data = await fetch('url');
  console.log(await data.json());
}

 

11) What is the difference between var, let, and const?


  • var: Function-scoped and can be redeclared.
  • let: Block-scoped and cannot be redeclared within the same scope.
  • const: Block-scoped and cannot be reassigned.

12) What are modules in JavaScript?


Modules in JavaScript are a way to break code into smaller, reusable pieces. Modules can be exported and imported.

// file1.js
export const name = 'John';

// file2.js
import { name } from './file1';

 

13) What is the spread operator?


The spread operator (...) is used to expand elements of an iterable (like arrays) into individual elements.

let arr = [1, 2, 3];
let newArr = [...arr, 4, 5];

 

14) What is the rest parameter?


The rest parameter (...) allows a function to accept an indefinite number of arguments as an array.

function sum(...numbers) {
  return numbers.reduce((acc, curr) => acc + curr, 0);
}

 

15) What are higher-order functions?


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

function multiply(a, b) {
  return a * b;
}

function operate(fn, a, b) {
  return fn(a, b);
}

operate(multiply, 2, 3); // 6

 

16) What is the bind method?


bind() creates a new function that, when invoked, has its this set to the provided value and prepends any arguments to the function.

const obj = { x: 5 };
const getX = function () {
  return this.x;
};
const boundGetX = getX.bind(obj);
console.log(boundGetX()); // 5

 

17) What is the difference between call() and apply()?


  • call(): Calls a function with a given this value and arguments passed individually.
  • apply(): Calls a function with a given this value and arguments passed as an array.

18) What is destructuring in JavaScript?


Destructuring allows extracting values from arrays or objects and assigning them to variables.

const { name, age } = { name: 'John', age: 25 };
const [first, second] = [1, 2];

 

19) What are promises chaining and then method?


Promise chaining allows you to chain multiple .then() calls, where each .then() is executed after the promise resolves.

fetch('/api')
  .then(response => response.json())
  .then(data => console.log(data));

 

20) What is the difference between synchronous and asynchronous execution in JavaScript?


  • Synchronous: Code runs sequentially, blocking the next operation until the current one finishes.
  • Asynchronous: Code can run independently, allowing the program to continue while waiting for the completion of operations (e.g., I/O).

21) Explain the concept of event delegation.


Event delegation is a technique where you attach a single event listener to a parent element instead of multiple listeners to child elements. It takes advantage of event bubbling.

document.querySelector('#parent').addEventListener('click', (event) => {
  if (event.target && event.target.matches('button')) {
    console.log('Button clicked');
  }
});

 

22) What is the setTimeout() function?


setTimeout() is used to execute a function after a specified delay.

setTimeout(() => {
  console.log('Hello after 2 seconds');
}, 2000);

 

23) What is the setInterval() function?


setInterval() repeatedly calls a function with a specified time delay between each call.

setInterval(() => {
  console.log('Repeated message every second');
}, 1000);

 

24) What is the difference between a for loop and forEach loop?


  • for loop: A general-purpose loop that can be used with arrays, objects, etc.
  • forEach loop: An array-specific method that iterates through the array elements.
    arr.forEach((item) => console.log(item));
    

     

25) What is JSON in JavaScript?


JSON (JavaScript Object Notation) is a lightweight data interchange format used to represent structured data. It is often used in APIs for data exchange.

const data = '{"name":"John", "age":30}';
const obj = JSON.parse(data); // Converts JSON string to JavaScript object

 

26) What is localStorage and sessionStorage?


Both are web storage APIs for storing data:

  • localStorage: Persists data across sessions.
  • sessionStorage: Persists data only for the duration of the page session.

27) What is a JavaScript module pattern?


The module pattern is used to encapsulate functionality in a self-contained unit to avoid polluting the global namespace.

const myModule = (function () {
  let privateVar = 'Private';
  return {
    publicMethod: function () {
      console.log(privateVar);
    },
  };
})();

 

28) What is the difference between slice() and splice() in arrays?


  • slice(): Returns a shallow copy of a portion of the array without modifying the original.
  • splice(): Changes the content of an array by removing or replacing elements.

29) What is a template literal in JavaScript?


Template literals allow embedding expressions inside string literals using ${} syntax.

const name = 'John';
const greeting = `Hello, ${name}!`;

 

30) What is the debugger keyword used for in JavaScript?


The debugger keyword is used to pause the execution of JavaScript code, allowing you to inspect the state of the program at that point.

debugger;