Top 100 JavaScript Interview Questions and Answers | Coding Examples

JavaScript is one of the most widely used programming languages in the world, powering everything from web applications to server-side scripts and mobile apps. As such, a deep understanding of JavaScript is essential for any developer looking to advance in their career. Whether you're just starting out in web development or you're an experienced developer aiming to enhance your expertise, mastering JavaScript is crucial for building dynamic and interactive applications.

JavaScript interview questions cover a broad spectrum of topics ranging from basic syntax and operations to more advanced concepts such as closures, promises, asynchronous programming, and object-oriented programming. Preparing for these questions requires not just knowing the theory, but also understanding how to write efficient and maintainable code.

This collection of JavaScript interview questions and answers is designed to take you from beginner to advanced levels, ensuring you're well-prepared for any technical interview. The questions include detailed explanations, code examples, and real-world scenarios that will help you not only understand the syntax but also apply it in practical situations. Whether you are preparing for your first JavaScript interview or looking to sharpen your skills, this comprehensive guide will equip you with the knowledge and confidence to excel.

Throughout this guide, we will cover fundamental topics like variables, functions, and data structures, as well as delve into more advanced concepts such as event delegation, closures, the event loop, and JavaScript's prototype chain. By the end of this article, you will have a solid understanding of key JavaScript principles, ready to tackle interview challenges and enhance your development skills.

Let’s begin the journey of mastering JavaScript, one question at a time.

Begineer's Level Interview Questions in JavaScript

Begineer's Level Interview Questions


1. What is JavaScript?

JavaScript is a versatile, lightweight programming language primarily used to add interactivity to web pages. It is an interpreted, high-level, and dynamic language.

Example:

// Example: Adding interactivity

document.getElementById("btn").addEventListener("click", function () {
  alert("Button clicked!");
});

2. What are the different data types in JavaScript?

JavaScript has the following data types:

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

Example:

let str = "Hello";  // String
let num = 42;       // Number
let bool = true;    // Boolean
let obj = { key: "value" }; // Object

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

var: Function-scoped, can be re-declared and updated.
let: Block-scoped, cannot be re-declared but can be updated.
const: Block-scoped, cannot be re-declared or updated.

Example:

var x = 10;         // Function-scoped
let y = 20;         // Block-scoped
const z = 30;       // Immutable

4. What are JavaScript closures?

A closure is a function that has access to its outer function's scope, even after the outer function has returned.

Example:

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

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

==: Compares values after type coercion.
===: Strict comparison without type coercion.

Example:

console.log(5 == "5");  // true
console.log(5 === "5"); // false

6. What is the DOM?

The DOM (Document Object Model) is a programming interface that represents the structure of a web page.

Example:

// Accessing and modifying DOM
document.getElementById("demo").innerText = "Hello DOM!";

7. What is the difference between undefined and null?

undefined: A variable is declared but not assigned.
null: Explicitly assigned to indicate "no value."

Example:

let a;
let b = null;
console.log(a); // undefined
console.log(b); // null

8. What are JavaScript functions?

Functions are blocks of reusable code.

Example:

function add(a, b) {
  return a + b;
}
console.log(add(2, 3)); // 5

9. What is event bubbling and capturing?

Bubbling: Events propagate from the target element up to its ancestors.
Capturing: Events propagate from ancestors to the target.

Example:

document.getElementById("child").addEventListener(
  "click",
  () => console.log("Child clicked"),
  true // Capturing phase
);

10. What are JavaScript promises?

Promises handle asynchronous operations, providing then, catch, and finally methods.

Example:

const promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Done!"), 1000);
});
promise.then((msg) => console.log(msg)); // Done!

11. What are JavaScript arrays, and how do you manipulate them?

Arrays are ordered collections of items, which can store any data type.

Example of common methods:

const arr = [1, 2, 3];

// Adding elements
arr.push(4); // [1, 2, 3, 4]

// Removing elements
arr.pop(); // [1, 2, 3]

// Accessing elements
console.log(arr[1]); // 2

// Iterating through an array
arr.forEach((num) => console.log(num));

// Modifying elements
arr[0] = 10; // [10, 2, 3]

12. What are template literals in JavaScript?

Template literals allow embedding expressions in strings using backticks (`) and ${expression} syntax.

Example:

const name = "John";
const greeting = `Hello, ${name}!`; // Embedding variable
console.log(greeting); // "Hello, John!"

13. What is the difference between function declarations and function expressions?

Function Declaration: Hoisted and can be called before its definition.
Function Expression: Not hoisted; it behaves like a value.

Example:

// Function declaration
function greet() {
  console.log("Hello!");
}

// Function expression
const greet = function () {
  console.log("Hi!");
};

14. What is NaN in JavaScript?

NaN stands for "Not-a-Number" and is returned when a mathematical operation fails.

Example:

console.log(0 / 0); // NaN
console.log(parseInt("abc")); // NaN

// Checking for NaN
console.log(isNaN("abc")); // true

15. What are JavaScript objects?

Objects store key-value pairs and can represent complex data.

Example:

const person = {
  name: "Alice",
  age: 25,
  greet() {
    console.log(`Hello, ${this.name}!`);
  },
};
console.log(person.name); // "Alice"
person.greet(); // "Hello, Alice!"


Intermediate Level Questions in JavaScript

Intermediate Level Questions in JavaScript


16. Explain this keyword in JavaScript.

this refers to the object that is executing the current function.

Example:

const obj = {
  name: "JS",
  greet() {
    console.log(this.name);
  },
};
obj.greet(); // "JS"

17. What are arrow functions in JavaScript?

Arrow functions are a concise syntax for defining functions and do not bind their own this.

Example:

const greet = () => console.log("Hello!");
greet();

18. What is the difference between map, filter, and reduce?

map: Transforms each element in an array.
filter: Filters elements based on a condition.
reduce: Reduces the array to a single value.

Example:

const arr = [1, 2, 3];
const mapped = arr.map((x) => x * 2); // [2, 4, 6]
const filtered = arr.filter((x) => x > 1); // [2, 3]
const reduced = arr.reduce((acc, x) => acc + x, 0); // 6

19. What is asynchronous programming in JavaScript?

Asynchronous programming handles tasks that take time to complete, like API calls or file I/O.

Example:

setTimeout(() => console.log("Async!"), 1000);
console.log("Sync!");

Output:

Sync!
Async!

20. What are JavaScript modules?

Modules enable splitting code into separate files and reusing functionality.

Example: file1.js:

export const greet = () => console.log("Hello!");

file2.js:

import { greet } from "./file1.js";
greet();

21. How does setTimeout differ from setInterval?

setTimeout: Executes a function after a delay.
setInterval: Executes a function repeatedly at specified intervals.

Example:

// setTimeout
setTimeout(() => console.log("Timeout!"), 1000);

// setInterval
setInterval(() => console.log("Interval!"), 1000);

22. What is the difference between call, apply, and bind?

call: Invokes a function with a specified this value and arguments passed individually.
apply: Similar to call, but arguments are passed as an array.
bind: Returns a new function bound to a specific this value.

Example:

const obj = { name: "John" };

function greet(greeting) {
  console.log(`${greeting}, ${this.name}!`);
}

greet.call(obj, "Hello"); // "Hello, John!"
greet.apply(obj, ["Hi"]); // "Hi, John!"
const boundGreet = greet.bind(obj, "Hey");
boundGreet(); // "Hey, John!"

23. What is the spread operator (...)?

The spread operator allows expanding elements of an array or object.

Example:

const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]

const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 }

24. What are default parameters in JavaScript functions?

Default parameters assign initial values if no arguments are provided.

Example:

function greet(name = "Guest") {
  console.log(`Hello, ${name}!`);
}
greet(); // "Hello, Guest!"

25. What is destructuring in JavaScript?

Destructuring unpacks values from arrays or properties from objects into variables.

Example:

// Array destructuring
const [a, b] = [1, 2];

// Object destructuring
const { name, age } = { name: "John", age: 30 };
console.log(name, age); // "John", 30

26. What are async/await keywords?

async/await simplifies handling promises.

Example:

const fetchData = async () => {
  const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
  const data = await response.json();
  console.log(data);
};
fetchData();

27. What are IIFEs (Immediately Invoked Function Expressions)?

IIFEs are functions that execute immediately after being defined.

Example:

(function () {
  console.log("IIFE executed!");
})();

28. Explain debounce and throttle.

Debounce: Delays execution until after a specified period.
Throttle: Ensures execution occurs at most once in a specified period.
Example of debounce:

const debounce = (fn, delay) => {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
};

29. What are closures in JavaScript?

A closure is a function that retains access to its outer scope even after the outer function has executed.

Example:

function outer() {
  let counter = 0;
  return function inner() {
    counter++;
    console.log(counter);
  };
}

const increment = outer();
increment(); // 1
increment(); // 2

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

var: Function-scoped, hoisted, and can be re-declared.
let: Block-scoped, not hoisted, and cannot be re-declared.
const: Block-scoped, not hoisted, and immutable (but the object it refers to can change).

Example:

if (true) {
  var a = 1; // accessible outside the block
  let b = 2; // block-scoped
  const c = 3; // block-scoped
}
console.log(a); // 1
// console.log(b, c); // Error: b and c are not defined

31. What is the purpose of the typeof operator?

The typeof operator returns the type of a variable as a string.

Example:

console.log(typeof 42); // "number"
console.log(typeof "Hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (quirk in JS)
console.log(typeof {}); // "object"

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

==: Compares values only (type coercion).
===: Compares both value and type (strict equality).

Example:

console.log(5 == "5"); // true (type coercion)
console.log(5 === "5"); // false (strict comparison)

33. What are higher-order functions in JavaScript?

Higher-order functions take other functions as arguments or return functions.

Example:

function higherOrder(func) {
  return function (name) {
    func(name);
  };
}

function greet(name) {
  console.log(`Hello, ${name}!`);
}

const customGreet = higherOrder(greet);
customGreet("Alice"); // "Hello, Alice!"

34. How does JavaScript handle asynchronous code with callbacks?

Asynchronous code, like fetching data or timers, uses callbacks to execute a function when the task completes.

Example:

setTimeout(() => console.log("Executed after 2 seconds"), 2000);

35. What is a promise in JavaScript?

A promise represents a value that will be resolved or rejected in the future.

Example:

const fetchData = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Data fetched"), 1000);
});

fetchData.then((data) => console.log(data)); // "Data fetched"

36. Explain the Promise.allSettled method.

Promise.allSettled waits for all promises to either resolve or reject, and it returns an array of their results.

Example:

const promises = [
  Promise.resolve(1),
  Promise.reject("Error"),
  Promise.resolve(2),
];

Promise.allSettled(promises).then((results) => console.log(results));

// [{ status: "fulfilled", value: 1 }, { status: "rejected", reason: "Error" }, { status: "fulfilled", value: 2 }]

37. What are arrow functions in JavaScript?

Arrow functions are a concise syntax for writing functions. They inherit the this value from their enclosing scope.

Example:

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

38. What is event delegation in JavaScript?

Event delegation is a pattern where a parent element handles events for its children using event bubbling.

Example:

document.getElementById("parent").addEventListener("click", (event) => {
  if (event.target.tagName === "BUTTON") {
    console.log("Button clicked:", event.target.textContent);
  }
});

39. What is the difference between synchronous and asynchronous programming?

Synchronous: Code is executed line by line, blocking the thread.
Asynchronous: Code does not block; tasks can run in the background.

Example:

// Synchronous
console.log("Start");
console.log("End");

// Asynchronous
console.log("Start");
setTimeout(() => console.log("Async Task"), 1000);
console.log("End");
// Output: Start, End, Async Task

40. What is the this keyword in JavaScript?

this refers to the context in which a function is executed.

Example:

const obj = {
  name: "Alice",
  greet() {
    console.log(this.name);
  },
};

obj.greet(); // "Alice"

const greet = obj.greet;
greet(); // undefined (global context)

41. How do you create private variables in JavaScript?

Private variables can be created using closures or # for class properties.

Example using closures:

function Counter() {
  let count = 0;
  return {
    increment() {
      count++;
    },
    getCount() {
      return count;
    },
  };
}

const counter = Counter();
counter.increment();
console.log(counter.getCount()); // 1

42. What is the purpose of the try-catch block in JavaScript?

It handles exceptions to prevent the program from crashing.

Example:

try {
  console.log(x); // ReferenceError
} catch (error) {
  console.error("An error occurred:", error.message);
}

43. What are JavaScript modules, and how do you import/export them?

Modules organize code into reusable files.

Use export to make functions or variables available.
Use import to bring them into another file.

Example:

// math.js
export const add = (a, b) => a + b;

// app.js
import { add } from "./math.js";
console.log(add(2, 3)); // 5

44. Explain the concept of immutability in JavaScript.

Immutability means creating a new value instead of modifying the original.

Example with arrays:

const arr = [1, 2, 3];
const newArr = [...arr, 4]; // [1, 2, 3, 4]

45. What is the purpose of the map function in arrays?

map transforms each element of an array.

Example:

const arr = [1, 2, 3];
const doubled = arr.map((num) => num * 2);
console.log(doubled); // [2, 4, 6]

Advanced Level Questions In JavaScript

Advanced Level Questions In JavaScript

46. What are higher-order functions?

Higher-order functions take other functions as arguments or return functions.

Example:

function higherOrder(fn) {
  return fn(5);
}
higherOrder((x) => x * x); // 25

47. What is the event loop in JavaScript?

The event loop allows JavaScript to perform non-blocking asynchronous operations.

Example:

console.log("Start");
setTimeout(() => console.log("Async"), 0);
console.log("End");

Output:

Start
End
Async

48. Explain prototypes in JavaScript.

Prototypes enable inheritance in JavaScript.

Example:

function Person(name) {
  this.name = name;
}
Person.prototype.greet = function () {
  return `Hello, ${this.name}`;
};
const person = new Person("John");
console.log(person.greet()); // "Hello, John"

49. What is memoization in JavaScript?

Memoization optimizes performance by caching function results.

Example:

const memoize = (fn) => {
  const cache = {};
  return (...args) => {
    const key = JSON.stringify(args);
    if (!cache[key]) {
      cache[key] = fn(...args);
    }
    return cache[key];
  };
};
const add = memoize((a, b) => a + b);
console.log(add(1, 2)); // 3

50. What are WebSockets in JavaScript?

WebSockets enable two-way communication between the browser and the server.

Example:

const socket = new WebSocket("ws://example.com");
socket.onopen = () => socket.send("Hello, server!");
socket.onmessage = (event) => console.log(event.data);

51. Explain the Event Loop in detail.

The event loop manages JavaScript's non-blocking behavior by handling asynchronous tasks like callbacks and promises.

Key steps:

Executes code in the call stack.
Pushes asynchronous tasks (like setTimeout) into the task queue.
Processes tasks in the microtask queue (promises) before handling the task queue.

52. What are WeakMap and WeakSet?

WeakMap: Holds key-value pairs with weak references to keys (only objects).
WeakSet: Stores weakly-referenced objects.

Example:

let obj = { key: "value" };
const wm = new WeakMap();
wm.set(obj, "metadata");

// Automatically garbage-collected if `obj` is no longer used.

53. What is hoisting in JavaScript?

Hoisting moves function and variable declarations to the top of their scope.

Example:

console.log(a); // undefined
var a = 10;

54. What is the Promise.all method?

Promise.all resolves when all promises in an array are fulfilled.

Example:

const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);

Promise.all([p1, p2]).then((values) => console.log(values)); // [1, 2]

55. What are JavaScript Generators, and how do they work?

Generators are special functions that can pause execution and resume later. They use the function* syntax and yield keyword.

Example:

function* generatorFunction() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = generatorFunction();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }

56. What is memoization in JavaScript?

Memoization is a performance optimization technique where the result of a function is cached for future use.

Example:

function memoize(fn) {
  const cache = {};
  return function (...args) {
    const key = JSON.stringify(args);
    if (cache[key]) {
      return cache[key];
    }
    const result = fn(...args);
    cache[key] = result;
    return result;
  };
}

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

console.log(memoizedAdd(2, 3)); // 5 (calculated)
console.log(memoizedAdd(2, 3)); // 5 (cached)

57. Explain the debounce function. Why is it used?

debounce limits the rate at which a function executes by delaying it until a certain amount of time has passed since its last invocation.

Example:

function debounce(func, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => func(...args), delay);
  };
}

const log = debounce(() => console.log("Debounced!"), 1000);
log();
log();
log(); // Executes only once after 1 second

58. Explain the throttle function. How does it differ from debounce?

throttle ensures a function executes at most once in a specified interval, regardless of how often it's triggered.

Example:

function throttle(func, interval) {
  let lastTime = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastTime >= interval) {
      lastTime = now;
      func(...args);
    }
  };
}

const log = throttle(() => console.log("Throttled!"), 1000);
log();
log();
log(); // Executes immediately and once every 1 second

59. How can you deep clone an object in JavaScript?

Deep cloning creates a new object with no shared references to the original.

Using JSON.stringify and JSON.parse (basic but limited):

const obj = { a: 1, b: { c: 2 } };
const clone = JSON.parse(JSON.stringify(obj));
Using structured cloning (structuredClone in modern JS):

const clone = structuredClone(obj);

60. What is the difference between shallow and deep copy?

Shallow copy: Copies only the first level of properties.
Deep copy: Recursively copies all levels.

Example:

const obj = { a: 1, b: { c: 2 } };

// Shallow copy

const shallowCopy = { ...obj };
shallowCopy.b.c = 42;
console.log(obj.b.c); // 42

// Deep copy

const deepCopy = JSON.parse(JSON.stringify(obj));
deepCopy.b.c = 100;
console.log(obj.b.c); // 42

61. What is the difference between bind, call, and apply?

call: Invokes a function with a specified this and arguments passed individually.
apply: Same as call but arguments are passed as an array.
bind: Returns a new function with a bound this value.

Example:

const obj = { name: "Alice" };
function greet(greeting) {
  console.log(`${greeting}, ${this.name}`);
}

greet.call(obj, "Hello"); // "Hello, Alice"
greet.apply(obj, ["Hi"]); // "Hi, Alice"
const boundGreet = greet.bind(obj);
boundGreet("Hey"); // "Hey, Alice"

62. Explain the Event Loop in JavaScript.

The event loop ensures non-blocking asynchronous execution.

Call Stack: Executes functions.
Task Queue: Stores callbacks like setTimeout.
Microtask Queue: Handles promises (then, catch).

Example:

console.log("Start");

setTimeout(() => console.log("Timeout"), 0);

Promise.resolve().then(() => console.log("Promise"));

console.log("End");

// Output: Start, End, Promise, Timeout

63. What is the difference between setTimeout and setInterval?

setTimeout: Executes a function after a specified delay.
setInterval: Repeatedly executes a function at specified intervals.

Example:

setTimeout(() => console.log("Executed once"), 1000);

let count = 0;
const interval = setInterval(() => {
  console.log(`Interval: ${++count}`);
  if (count === 3) clearInterval(interval);
}, 1000);

64. What is Currying in JavaScript?

Currying transforms a function with multiple arguments into a sequence of functions that each take a single argument.

Example:

function curry(func) {
  return function curried(...args) {
    if (args.length >= func.length) {
      return func(...args);
    }
    return (...nextArgs) => curried(...args, ...nextArgs);
  };
}

const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);

console.log(curriedAdd(1)(2)(3)); // 6

65. What are WeakMap and WeakSet in JavaScript?

WeakMap: A map where keys are objects and references are weak, meaning they don’t prevent garbage collection.
WeakSet: A set of objects with weak references.

Example:

let obj = { a: 1 };
const weakMap = new WeakMap();
weakMap.set(obj, "value");
console.log(weakMap.get(obj)); // "value"

obj = null; // WeakMap key is garbage-collected

66. What is Object.freeze in JavaScript?

Object.freeze prevents modification of an object’s properties.

Example:

const obj = { name: "Alice" };
Object.freeze(obj);
obj.name = "Bob"; // Error in strict mode
console.log(obj.name); // "Alice"

67. Explain the concept of polyfills in JavaScript.

A polyfill adds functionality to older browsers that lack support for modern features.

Example:

if (!String.prototype.includes) {
  String.prototype.includes = function (search, start = 0) {
    return this.indexOf(search, start) !== -1;
  };
}

68. What is the purpose of Symbol in JavaScript?

Symbol creates unique and immutable keys for objects.

Example:

const sym1 = Symbol("id");
const sym2 = Symbol("id");

console.log(sym1 === sym2); // false

const obj = { [sym1]: "value" };
console.log(obj[sym1]); // "value"

69. Explain optional chaining in JavaScript.

Optional chaining (?.) safely accesses deeply nested properties without causing errors.

Example:

const user = { profile: { name: "Alice" } };
console.log(user?.profile?.name); // "Alice"
console.log(user?.address?.city); // undefined

== and === IIFEs promise asyncawait


70. What is the difference between == and === in JavaScript?

== (Loose equality): Compares values after performing type coercion (converts one or both values to a common type).
=== (Strict equality): Compares both value and type without any type coercion.

Example:

console.log(5 == "5");  // true (type coercion)
console.log(5 === "5"); // false (different types)

71. What are IIFEs (Immediately Invoked Function Expressions)?

An IIFE is a function that is defined and executed immediately. It's often used to create a new scope to avoid polluting the global namespace.

Example:

(function() {
  console.log("IIFE Executed");
})(); // Executes immediately

72. What are JavaScript Promises and how do they work?

A Promise represents a value that may be available now or in the future. It has three states: pending, fulfilled, and rejected.

Example:

let promise = new Promise((resolve, reject) => {
  let success = true;
  if (success) {
    resolve("Success!");
  } else {
    reject("Failure!");
  }
});

promise
  .then(result => console.log(result))  // "Success!"
  .catch(error => console.log(error)); // Not reached in this case

73. What is the difference between Promise.then() and async/await?

Promise.then(): Uses .then() to handle a fulfilled promise and .catch() to handle rejections.

async/await: A syntactic sugar for working with promises in a more synchronous-looking way.

Example using async/await:

async function fetchData() {
  try {
    let response = await fetch('https://api.example.com');
    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.log('Error:', error);
  }
}

74. What is a callback function in JavaScript?

A callback function is a function passed into another function as an argument and executed at a later time.

Example:

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

greet("Alice", function() {
  console.log("Welcome!");
});
// Output: Hello Alice
//         Welcome!

75. Explain the concept of "this" in JavaScript.

this refers to the object it belongs to. Its value depends on how a function is called.

In a regular function, this refers to the global object (in non-strict mode).
In an object method, this refers to the object itself.
In an arrow function, this is lexically inherited from the surrounding code.

Example:

const obj = {
  name: "Alice",
  greet: function() {
    console.log(this.name);
  }
};
obj.greet(); // Alice

76. What are higher-order functions in JavaScript?

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

Example:

function filterArray(arr, callback) {
  return arr.filter(callback);
}

const result = filterArray([1, 2, 3, 4], num => num > 2);
console.log(result); // [3, 4]

77. What are the differences between var, let, and const?

var: Function-scoped, can be re-declared and updated.
let: Block-scoped, can be updated but not re-declared within the same scope.
const: Block-scoped, cannot be updated or re-declared. However, objects and arrays declared with const are mutable.

Example:

var x = 10; // can be redeclared and updated
let y = 20; // can be updated, but not redeclared
const z = 30; // cannot be updated or redeclared

const obj = { name: "Alice" };
obj.name = "Bob"; // valid because the object itself is mutable

78. What is destructuring in JavaScript?

Destructuring is a shorthand syntax for extracting multiple properties from objects or arrays.

Example with objects:

const person = { name: "Alice", age: 25 };
const { name, age } = person;
console.log(name); // Alice
console.log(age);  // 25

Example with arrays:

const numbers = [1, 2, 3];
const [first, second] = numbers;
console.log(first);  // 1
console.log(second); // 2

79. What is the difference between slice() and splice()?

slice(): Returns a shallow copy of a portion of an array without modifying the original.
splice(): Modifies the array by adding, removing, or replacing elements.

Example:

const arr = [1, 2, 3, 4, 5];

// slice() does not modify the original array
console.log(arr.slice(1, 3)); // [2, 3]
console.log(arr); // [1, 2, 3, 4, 5]

// splice() modifies the original array
arr.splice(1, 2);
console.log(arr); // [1, 4, 5]

80. What is the new keyword in JavaScript?

The new keyword creates a new instance of an object. It also binds this to the new object and returns it.

Example:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

const person1 = new Person("Alice", 25);
console.log(person1.name); // Alice

81. What are JavaScript Modules?

Modules allow splitting code into separate files and importing/exporting functionality between them.

Example using export and import:

// module.js
export const greeting = "Hello";

// main.js
import { greeting } from './module.js';
console.log(greeting); // Hello

82. What is Object.create() in JavaScript?

Object.create() creates a new object with a specified prototype object and properties.

Example:

const person = {
  greet() {
    console.log("Hello!");
  }
};

const child = Object.create(person);
child.greet(); // Hello!

83. What is the prototype in JavaScript?

Every JavaScript object has a prototype. It’s an object from which other objects inherit properties and methods.

Example:

function Car(brand) {
  this.brand = brand;
}

Car.prototype.getBrand = function() {
  return this.brand;
};

const car = new Car("Toyota");
console.log(car.getBrand()); // Toyota

84. What is a set in JavaScript?

A Set is a collection of unique values, meaning no duplicates are allowed.

Example:

const set = new Set();
set.add(1);
set.add(2);
set.add(2); // Duplicate, won't be added

console.log(set); // Set { 1, 2 }

85. What is a map in JavaScript?

A Map is an object that holds key-value pairs where keys can be any data type (unlike objects which convert keys to strings).

Example:

const map = new Map();
map.set('name', 'Alice');
map.set(1, 'one');
console.log(map.get('name')); // Alice
console.log(map.get(1)); // one

86. How do you handle errors in JavaScript?

Errors can be handled using try...catch blocks.

Example:

try {
  let result = riskyFunction();
} catch (error) {
  console.log("An error occurred:", error.message);
}

TypeOf Async callbacks, promise


87. What is event delegation in JavaScript?

Event delegation is a technique where you attach a single event listener to a parent element instead of adding individual listeners to each child element. This takes advantage of event propagation (bubbling) to handle events for child elements efficiently.

Example:

const parent = document.getElementById('parent');
parent.addEventListener('click', function(event) {
  if (event.target && event.target.matches('button')) {
    console.log('Button clicked:', event.target);
  }
});

In this case, you don't need to attach listeners to individual buttons, as the parent element listens for clicks on any button inside it.

88. What are closures in JavaScript?

A closure is a function that has access to its own scope, the scope in which it was created, and the global scope. Closures allow you to preserve the state of variables even after the outer function has finished executing.

Example:

function outer() {
  let counter = 0;
  return function inner() {
    counter++;
    console.log(counter);
  };
}

const increment = outer();
increment(); // 1
increment(); // 2

The inner function remembers the counter variable from the outer function even after outer has finished executing.

89. What is the bind() method in JavaScript?

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Example:

function greet() {
  console.log("Hello, " + this.name);
}

const person = { name: "Alice" };
const boundGreet = greet.bind(person);
boundGreet(); // Hello, Alice

In this case, the this inside greet is permanently set to the person object using bind().

90. Explain the concept of JavaScript's event loop and call stack.

The event loop in JavaScript allows asynchronous code (like timers, I/O operations, etc.) to execute while the synchronous code is running. It works with the call stack and callback queue to ensure smooth execution.

The call stack holds functions that are being executed.

When an asynchronous event (like a timer or HTTP request) finishes, its callback is placed in the callback queue.

The event loop checks if the call stack is empty. If it is, it moves the callback from the callback queue to the call stack for execution.

Example:

console.log("Start");

setTimeout(() => {
  console.log("Inside Timeout");
}, 0);

console.log("End");

// Output:
// Start
// End
// Inside Timeout

In the above example, even though the setTimeout has a 0ms delay, it waits until the synchronous code completes before running.

91. What is localStorage in JavaScript?

localStorage is a storage API in the browser that allows you to store key-value pairs in a web browser with no expiration date. Data stored in localStorage persists even after the browser is closed.

Example:

localStorage.setItem("username", "Alice");
console.log(localStorage.getItem("username")); // Alice
localStorage.removeItem("username");

92. What is sessionStorage in JavaScript?

Similar to localStorage, sessionStorage allows storing key-value pairs, but its data is only available for the duration of the page session. Once the browser tab or window is closed, the data is erased.

Example:

sessionStorage.setItem("sessionData", "someValue");
console.log(sessionStorage.getItem("sessionData")); // someValue

93. What is the difference between null and undefined in JavaScript?

null: Represents the intentional absence of any object value.
undefined: Represents a variable that has been declared but not assigned a value, or a function that does not explicitly return anything.

Example:

let a;  // undefined
let b = null;  // null

console.log(a);  // undefined
console.log(b);  // null

94. What is a WeakMap in JavaScript?

A WeakMap is a special type of Map where the keys are objects and the garbage collector can collect them when there are no other references to the object. This is useful for storing data associated with an object without preventing its garbage collection.

Example:

const weakMap = new WeakMap();
let obj = {};
weakMap.set(obj, "value");

console.log(weakMap.get(obj)); // value

obj = null; // obj is eligible for garbage collection now

95. What is the difference between slice() and splice() methods in JavaScript?

slice(): Returns a shallow copy of a portion of an array and does not modify the original array.
splice(): Changes the contents of an array by removing or replacing existing elements.

Example of slice():

const arr = [1, 2, 3, 4, 5];
const newArr = arr.slice(1, 4);  // [2, 3, 4]
console.log(arr);  // [1, 2, 3, 4, 5] (original array is unchanged)

Example of splice():

const arr = [1, 2, 3, 4, 5];
arr.splice(1, 2, "a", "b");  // removes 2 elements from index 1 and adds "a" and "b"
console.log(arr);  // [1, "a", "b", 4, 5]

96. What are setTimeout() and setInterval() in JavaScript?

setTimeout(): Executes a function once after a specified delay (in milliseconds).
setInterval(): Repeatedly executes a function at a specified interval (in milliseconds).

Example of setTimeout():

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

Example of setInterval():

let counter = 0;
const intervalId = setInterval(() => {
  console.log("Counter:", counter);
  counter++;
  if (counter > 5) {
    clearInterval(intervalId);  // Stop after 5 iterations
  }
}, 1000);

97. What is a getter and setter in JavaScript?

Getters and Setters are methods that allow you to define accessors and mutators for properties on objects. They are often used for encapsulating data and performing additional logic when getting or setting property values.

Example:

const person = {
  firstName: "John",
  lastName: "Doe",
  get fullName() {
    return this.firstName + " " + this.lastName;
  },
  set fullName(name) {
    const [first, last] = name.split(" ");
    this.firstName = first;
    this.lastName = last;
  }
};

console.log(person.fullName); // John Doe
person.fullName = "Alice Smith";
console.log(person.firstName); // Alice
console.log(person.lastName);  // Smith

98. What is the new keyword and how does it work in JavaScript?

The new keyword is used to create an instance of a constructor function or class. It performs the following:

Creates a new empty object.
Sets the prototype of the object to the constructor's prototype.
Binds this to the newly created object inside the constructor.
Returns the object (if the constructor doesn’t explicitly return anything).

Example:

function Person(name) {
  this.name = name;
}

const person1 = new Person("John");
console.log(person1.name); // John

99. What is a Rest Parameter in JavaScript?

A rest parameter allows you to pass a variable number of arguments into a function as an array. It's denoted by ... before the parameter name.

Example:

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

console.log(sum(1, 2, 3, 4)); // 10

100. What is a Spread Syntax in JavaScript?

Spread syntax is used to unpack elements from an array or properties from an object into separate variables or arrays/objects. It is denoted by ....

Example with Arrays:

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]

Example with Objects:

const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }

Conclusion


Conclusion

Mastering JavaScript is essential for developers who want to build interactive, high-performance web applications and succeed in technical interviews. The questions and answers covered in this guide span a wide range of topics, from fundamental concepts like variables and functions to more advanced techniques such as closures, promises, and the event loop. Each concept is explained with clear code examples and real-world applications, helping you to not only understand the theory but also implement it effectively in practice.

Preparing for JavaScript interviews requires a deep understanding of both basic and advanced features of the language. By going through this collection of questions and answers, you've equipped yourself with the knowledge needed to tackle challenges at any level, whether you are just starting your coding journey or aiming to master advanced JavaScript concepts.

Remember, while technical expertise is crucial, it's also important to stay curious and continually learn. JavaScript, like all programming languages, evolves over time, and staying up-to-date with new features and best practices will help you maintain your edge in the ever-changing world of web development.

We hope this guide serves as a valuable resource in your journey toward mastering JavaScript and achieving success in interviews. Keep practicing, building projects, and expanding your knowledge — because the more you learn, the more proficient you'll become as a JavaScript developer.

Post a Comment

0 Comments