storieasy-logo

JavaScript Interview Questions and Answers : From Basics to Advanced With Examples

milan

Milan Patel

29 Jun 2025

|

35 min to read

JavascriptInterviewQuestion

JavaScript

JavaScriptInterview

FrontendInterview

JavaScriptQuestions

JS2025

JSInterview

JSForInterviews

Get the latest JavaScript interview questions and answers for 2025, covering beginner to advanced topics with clear explanations and code examples.

Introduction

JavaScript is the heart of modern web development. Whether you're a fresher or an experienced developer preparing for a front-end or full-stack role, mastering JavaScript interview questions is crucial.

This blog covers the most frequently asked JS questions in 2025 โ€“ ranging from core concepts to real-world coding challenges โ€“ with unique insights, clear examples, and deep explanations.

1. ๐Ÿ“ฆ What are the differences between var, let, and const?

Explanation:

KeywordScopeHoistingReassignableRedeclarable
varFunctionYes (undefined)โœ…โœ…
letBlockYes (Temporal Dead Zone)โœ…โŒ
constBlockYes (Temporal Dead Zone)โŒ โŒ

Example:

1function test() {
2  if (true) {
3    var a = 1;
4    let b = 2;
5    const c = 3;
6  }
7  console.log(a); // 1
8  console.log(b); // ReferenceError
9}
10test();

2. โšก What is a closure in JavaScript?

Explanation:

A closure gives you access to an outer functionโ€™s scope from an inner function, even after the outer function has returned.

Example:

1function outer() {
2  let counter = 0;
3  return function inner() {
4    counter++;
5    console.log(counter);
6  };
7}
8const count = outer();
9count(); // 1
10count(); // 2

Closures are widely used in data encapsulation and functional programming.

3. ๐ŸŒ€ Explain the Event Loop and Call Stack

Explanation:

JavaScript is single-threaded but handles asynchronous tasks using the event loop, callback queue, and call stack.

Example:

1console.log('A');
2
3setTimeout(() => console.log('B'), 0);
4
5Promise.resolve().then(() => console.log('C'));
6
7console.log('D');

Output:

1A  
2D  
3C  
4B

โœ… Promise (microtask) runs before setTimeout (macrotask).

4. ๐Ÿ“š What is the difference between = = and = = =?

Answer:

  • = = compares values after type coercion.
  • = = = compares values and types (strict equality).

Example:

1console.log('5' == 5);  // true
2console.log('5' === 5); // false

Best Practice: Always use = = = to avoid unpredictable bugs.

5. ๐Ÿง  What is hoisting in JavaScript?

Explanation:

Hoisting is JavaScriptโ€™s default behavior of moving declarations to the top of the scope.

Example:

1console.log(a); // undefined
2var a = 5;

But for let and const:

1console.log(b); // ReferenceError
2let b = 10;

6. ๐Ÿ› ๏ธ How does this work in JavaScript?

Answer:

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

Example:

1const user = {
2  name: "Milan",
3  greet() {
4    console.log(`Hi, I'm ${this.name}`);
5  }
6};
7user.greet(); // Hi, I'm Milan
8

In arrow functions, this is lexically bound:

1const obj = {
2  name: "Test",
3  greet: () => console.log(this.name)
4};
5obj.greet(); // undefined (or window.name)

7. ๐Ÿ” Explain prototypal inheritance in JavaScript.

Explanation:

All JavaScript objects inherit properties and methods from a prototype.

Example:

1function Animal(name) {
2  this.name = name;
3}
4Animal.prototype.sound = function () {
5  return "Some sound";
6};
7
8const dog = new Animal("Dog");
9console.log(dog.sound()); // Some sound

8. What are higher-order functions?

Answer:

Functions that take other functions as arguments or return functions.

Example:

1function greet(name) {
2  return function (message) {
3    console.log(`${message}, ${name}`);
4  };
5}
6
7const greetMilan = greet('Milan');
8greetMilan('Hello'); // Hello, Milan

9. ๐Ÿ”„ What are the differences between map(), forEach(), filter(), and reduce()?

Comparison Table:

MethodReturn ValuePurposeMutates?
map()New arrayTransform itemsโŒ
forEach()undefinedLoop without returnโŒ
filter()New arrayFilter itemsโŒ
reduce() Any (accumulator)Reduce to single valueโŒ

Example:

1const nums = [1, 2, 3, 4];
2const doubled = nums.map(n => n * 2); // [2, 4, 6, 8]

10. ๐Ÿงช What are Promises and async/await?

Explanation:

Promises represent eventual completion of asynchronous tasks. async/await simplifies handling them.

Example:

1async function fetchData() {
2  try {
3    const res = await fetch('https://api.example.com/data');
4    const data = await res.json();
5    console.log(data);
6  } catch (err) {
7    console.error('Error:', err);
8  }
9}

11. ๐Ÿงผ Explain Debouncing and Throttling.

Debouncing:

Runs function after delay if no repeated triggers.

1function debounce(fn, delay) {
2  let timer;
3  return function (...args) {
4    clearTimeout(timer);
5    timer = setTimeout(() => fn(...args), delay);
6  };
7}

Throttling:

Runs function once in a time window, regardless of repeated calls.

1function throttle(fn, delay) {
2  let lastCall = 0;
3  return function (...args) {
4    const now = new Date().getTime();
5    if (now - lastCall >= delay) {
6      lastCall = now;
7      fn(...args);
8    }
9  };
10}
11

12. ๐Ÿงฉ What are JavaScript Modules?

Answer:

Modules allow splitting code into reusable, independent files using import and export.

Example:

math.js

1export function add(a, b) {
2  return a + b;
3}

main.js

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

13. ๐Ÿ” Explain memory management in JavaScript.

  • JavaScript uses automatic garbage collection
  • Two main concepts:
    • Reachability: Objects accessible from the root are kept
    • Reference Counting: Unused values are cleaned up

14. ๐Ÿšฆ What are short-circuit and logical operators?

Example:

1console.log(null || "default"); // "default"
2console.log("value" && 42);     // 42

15. ๐Ÿงฉ What is optional chaining and nullish coalescing?

Example:

1const user = {};
2console.log(user?.profile?.email); // undefined
3
4console.log(null ?? "fallback");  // "fallback"
5console.log(0 ?? 5);              // 0

Deep Dive into JavaScript Concepts (2025 Edition)

1. ๐Ÿ“ฆ Var vs Let vs Const โ€“ Detailed Insights

JavaScript now strongly encourages let and const over var due to scoping and predictability issues.

  • var: Function-scoped, can be redeclared, prone to hoisting confusion.
  • let: Block-scoped, can be updated but not redeclared within the same scope.
  • const: Block-scoped, cannot be updated or redeclared; ideal for constants and objects that shouldnโ€™t be reassigned.

Example:

1function demoScope() {
2    if(true){
3        var a = 10;
4        let b = 20;
5        const c = 30;
6    }
7    console.log(a); // 10
8    console.log(b); // Error: b is not defined
9    console.log(c); // Error: c is not defined
10}

Best Practice: Use const by default, let only when mutation is required, and avoid var.

2. โšก Closures โ€“ Real Use Cases

Example:

1function counter() {
2    let count = 0;
3    return function() {
4        count++;
5        return count;
6    }
7}
8
9const increment = counter();
10console.log(increment()); // 1
11console.log(increment()); // 2

Closures are critical in callback handling, module pattern, and event listeners.

3. ๐ŸŒ€ Event Loop โ€“ Practical Understanding

The event loop is central to JavaScriptโ€™s asynchronous behavior. Understanding it helps debug tricky scenarios.

Example:

1console.log('Start');
2setTimeout(() => console.log('Timeout'), 0);
3Promise.resolve().then(() => console.log('Promise'));
4console.log('End');

4. Prototypal Inheritance โ€“ Advanced Example

Every object has a prototype chain:

Example:

1function Person(name){
2    this.name = name;
3}
4Person.prototype.greet = function() {
5    return `Hello, ${this.name}`;
6}
7const user = new Person('Milan');
8console.log(user.greet()); // Hello, Milano

5. Async/Await โ€“ Modern Best Practices

Using async/await simplifies Promises:

Example:

1async function fetchData() {
2    try {
3        const response = await fetch('https://api.example.com/data');
4        const data = await response.json();
5        console.log(data);
6    } catch(error) {
7        console.error('Error fetching data', error);
8    }
9}

6. Debouncing and Throttling โ€“ Real Scenarios

  • Debounce: Search input autocomplete
  • Throttle: Scroll event optimization

Example:

1const debounce = (fn, delay) => {
2    let timer;
3    return function(...args) {
4        clearTimeout(timer);
5        timer = setTimeout(() => fn.apply(this, args), delay);
6    }
7}

Final Words

JavaScript is evolving constantly, and so are interview patterns. The best way to prepare is to master core concepts, practice with real examples, and understand how things work under the hood.

Subscribe to our Newsletter

Provide your email to get email notification when we launch new products or publish new articles

email

Share with your friends: