Go2X

On This Page:

Frontend

JavaScript Interview Questions

Prepare for your next tech interview with the most asked JavaScript interview questions and answers. It includes basic to advanced concepts, coding problems, and real-world scenarios for freshers and experienced developers.

Febuary 18, 2026
30 mins read

Interview Questions for Freshers

1. What is JavaScript?

JavaScript is a high-level, single-threaded, asynchronous programming language that is mainly used for developing dynamic and interactive web applications. It runs in the browser to manage user interactions, manipulate the DOM, and communicate with servers, and it can also run on the backend using environments such as Node.js.

2. Is javascript a statically typed or a dynamically typed language?

JavaScript is a dynamically typed language. This means that the type of the variable is determined at runtime, and not at compile time. You do not need to declare the type of the variable, and the type of the variable can change during runtime. This is very flexible but can sometimes cause runtime errors.

Example

javascript
1let value = 10;      // Number
2console.log(typeof value); // "number"
3
4value = "Hello";     // Now String
5console.log(typeof value); // "string"
6
7value = true;        // Now Boolean
8console.log(typeof value); // "boolean"

3. What are the different data types present in javascript?

JavaScript has two categories of data types: primitive and non-primitive. Primitive types include Number, String, Boolean, Undefined, Null, BigInt, and Symbol. Non-primitive types include Object, Array, and Function. Primitive types are immutable and stored by value, whereas non-primitive types are stored by reference.

Primitive types

  • String - It represents a series of characters and is written with quotes. A string can be represented using a single or a double quote.

  • Number - It represents a number and can be written with or without decimals.

  • BigInt - This data type is used to store numbers which are above the limitation of the Number data type. It can store large integers and is represented by adding "n" to an integer literal.

  • Boolean - It represents a logical entity and can have only two values: true or false. Booleans are generally used for conditional testing.

  • Undefined - When a variable is declared but not assigned, it has the value of undefined and it's type is also undefined.

  • Null - It represents a non-existent or a invalid value.

  • Symbol - It is a new data type introduced in the ES6 version of javascript. It is used to store an anonymous and unique value.

Example:

javascript
1// String
2let str = "Hello";
3// Number
4let num = 42;
5// BigInt
6let big = 12345678901234567890n;
7// Boolean
8let bool = true;
9// Undefined
10let undef;
11// Null
12let empty = null;
13// Symbol
14let sym = Symbol("id");

Non-primitive types

Primitive data types can store only a single value. To store multiple and complex values, non-primitive data types are used.

Object - Used to store collection of data.

Example:

javascript
1// Collection of data in key-value pairs
2var obj1 = {
3   x: 43,
4   y: "Hello Doe!",
5   z: function(){
6      return this.x;
7   }
8}
9
10// Collection of data as an ordered list
11var array1 = [5, "Hello", true, 4.1];

4. What is NaN property in JavaScript?

NaN is short for “Not-a-Number” and is used to denote an invalid or undefined numeric result in JavaScript. NaN is returned when a mathematical operation does not result in a valid number, like dividing zero by zero or when a string containing a non-numeric value is converted to a number. NaN is a special value of type number, and it is the only value that is not equal to itself. To detect NaN, we use Number.isNaN().

Example

javascript
1console.log(0 / 0);              // NaN
2console.log(parseInt("Hello"));  // NaN
3console.log(typeof NaN);         // "number"
4console.log(NaN === NaN);        // false
5console.log(Number.isNaN(NaN));  // true

5. What is the difference between null and undefined? When do you get each one?

undefined means a variable has been declared but not assigned a value, while null is an intentional assignment that represents the absence of a value. undefined is automatically assigned by JavaScript, whereas null is explicitly set by the developer.

Example

javascript
1let a;              // Declared but not assigned
2let b = null;       // Intentionally assigned empty value
3
4console.log(a);     // undefined
5console.log(b);     // null
6
7console.log(typeof a); // "undefined"
8console.log(typeof b); // "object"

6. What is a Variable Scope in JavaScript?

Variable scope in JavaScript is the area in the code where a variable can be accessed. There are three basic types of scopes in JavaScript: global scope, function scope, and block scope. Variables declared with var are function-scoped, and variables declared with let and const are block-scoped. Scopes ensure that there are no conflicts between variables and determine the accessibility of data in different parts of a program.

Example:

javascript
1let globalVar = "I am global"; // Global Scope
2
3function test() {
4  var functionVar = "I am function scoped"; // Function Scope
5  
6  if (true) {
7    let blockVar = "I am block scoped"; // Block Scope
8    console.log(blockVar); // Accessible here
9  }
10  
11  console.log(functionVar); // Accessible here
12  // console.log(blockVar); // ReferenceError
13}
14
15test();
16console.log(globalVar); // Accessible everywhere

7. Difference between " == " and " === " operators.

The ==operator checks equality after performing type coercion, meaning it converts operands to the same type before comparing. The === operator checks both value and type without performing type conversion. In modern JavaScript, we prefer === to avoid unexpected behavior caused by implicit type coercion.

Example:

javascript
1var x = 2;
2var y = "2";
3
4(x == y)  // Returns true since the value of both x and y is the same
5(x === y) // Returns false since the typeof x is "number" and typeof y is "string"

8. What's the difference between var, let, and const?

There are three ways to declare a variable in JavaScript: using var, let, and const.However, these three have different scopes, levels of hoisting, and capabilities of reassignment.

  • var: Declares variables with function or global scope and allows re-declaration and updates within the same scope.

  • let: Declares variables with block scope, allowing updates but not re-declaration within the same block.

  • const: Declares block-scoped variables that cannot be reassigned after their initial assignment.

Example:

javascript
1// var: function or global scope, can be re-declared and updated
2var x = 10;
3var x = 20; // re-declaration allowed
4console.log("var:", x); // 20
5
6// let: block scope, can be updated but not re-declared in same block
7let y = 30;
8// let y = 40; Error (can't re-declare in same block)
9y = 40; // update allowed
10console.log("let:", y); // 40
11
12// const: block scope, cannot be reassigned
13const z = 50;
14// z = 60; Error (can't reassign)
15console.log("const:", z); // 50

9. What is the Temporal Dead Zone?

Temporal Dead Zone (TDZ) is the period between entering a scope and the point where a let or const variable is declared. During this time, accessing the variable causes a ReferenceError, because the variable exists but hasn't been initialized yet.

Example:

javascript
1// TDZ example
2console.log(x);            // ReferenceError (x in TDZ)
3let x = 10;
4
5console.log(y);            // undefined (var is initialized at hoist time)
6var y = 10;

10. What are arrow functions?

Arrow functions are a shorthand syntax for defining functions in JavaScript, added in ES6. They are a concise way to define a function, and unlike regular functions, arrow functions do not have their own this. They inherit this from their surrounding (lexical) scope. Arrow functions are commonly used in callbacks and functional programming patterns.

Example:

Normal Function

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

Arrow Function

javascript
1const add = (a, b) => {
2  return a + b;
3};

Shorter Version (Implicit Return)

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

11. What is the rest parameter and spread operator?

The rest parameter and spread operator both use the same syntax ..., but they serve different purposes.

The rest parameter is used in function parameters to collect multiple arguments into a single array.

The spread operator is used to expand elements of an array or object into individual elements.

Example:

Rest Parameter (Collect values)

javascript
1function sum(...numbers) {
2  return numbers.reduce((total, num) => total + num, 0);
3}
4
5console.log(sum(1, 2, 3, 4)); // 10

Spread Operator (Expand values)

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

12. How many ways can an HTML element be accessed in JavaScript code?

There are several ways to access HTML elements in JavaScript using DOM selection methods. The most common methods include: getElementById(), getElementsByClassName(), getElementsByTagName(), querySelector(), and querySelectorAll(). These methods allow us to select elements by id, class, tag name, or CSS selector.

Example

html
1<div id="title" class="heading">Hello</div>
javascript
1// By ID
2document.getElementById("title");
3
4// By Class Name
5document.getElementsByClassName("heading");
6
7// By Tag Name
8document.getElementsByTagName("div");
9
10// By CSS Selector (first match)
11document.querySelector("#title");
12
13// By CSS Selector (all matches)
14document.querySelectorAll(".heading");

Interview Questions for Experienced

1. What is DOM?

The Document Object Model (DOM) is a way of representing an HTML document as a tree of nodes. When a browser loads an HTML page, it breaks down the HTML and builds a DOM tree where every element, attribute, and bit of text is represented as an object. This makes it possible for JavaScript to dynamically manipulate the HTML elements on a webpage, such as changing the text, styles, or attributes, or even removing elements, without having to reload the page.

2. What do you mean by BOM?

BOM (Browser Object Model) refers to a set of objects that the browser offers, which enables JavaScript to interact with the browser window, rather than just the content of the webpage. While the DOM is focused on the HTML document, the BOM enables JavaScript to interact with browser objects such as the window object, the history object, the location object, the navigator object, and the screen object.

Example

javascript
1// Accessing browser window
2console.log(window.innerWidth);
3
4// Redirecting to another page
5window.location.href = "https://google.com";
6
7// Showing alert
8window.alert("Hello John!");

3. What is the difference between client-side and server-side JavaScript?

The key difference between client-side JavaScript and server-side JavaScript is the execution environment of the code. Client-side JavaScript code is executed in the browser, and its primary use is for DOM manipulation, handling events, and making API calls. Server-side JavaScript code is executed on the server, usually in a Node.js environment, and is responsible for handling database operations, authentication, and response generation for client requests.

Example

Client-Side JavaScript (Browser)

html
1<button onclick="showMessage()">Click</button>
2<script>
3  function showMessage() {
4    alert("Hello John!");
5  }
6</script>

Server-Side JavaScript (Node.js)

javascript
1const http = require("http");
2
3http.createServer((req, res) => {
4  res.write("Hello from Server");
5  res.end();
6}).listen(3000);

4. Explain Hoisting in javascript.

Hoisting is the behavior of JavaScript where the declarations of variables and functions are moved to the top of their scope during the creation phase. Variables declared with var are initialized as undefined, while let and const are hoisted but remain in the temporal dead zone until initialization. Function declarations are fully hoisted, but function expressions are not.

Example 1:

javascript
1hoistedVariable = 3;
2console.log(hoistedVariable); // outputs 3 even when the variable is declared after it is initialized
3var hoistedVariable;

Example 2:

javascript
1hoistedFunction();  // Outputs " Hello Doe! " even when the function is declared after calling
2
3function hoistedFunction(){ 
4  console.log(" Hello Doe! ");
5}

Example 3:

javascript
1// Hoisting takes place in the local scope as well
2function doSomething(){
3  x = 33;
4  console.log(x);
5  var x;
6}

Note - Variable initializations are not hoisted, only variable declarations are hoisted:

javascript
1var x;
2console.log(x); // Outputs "undefined" since the initialization of "x" is not hoisted
3x = 23;

Note - To avoid hoisting, you can run javascript in strict mode by using "use strict" on top of the code:

javascript
1"use strict";
2x = 23; // Gives an error since 'x' is not declared
3var x;

5. Are arrow functions hoisted? Why or why not?

Arrow functions are not hoisted like regular function declarations. Since arrow functions are usually assigned to variables declared with let or const, only the variable declaration is hoisted, not the function definition. Therefore, accessing an arrow function before its definition results in a ReferenceError due to the Temporal Dead Zone.

Example

javascript
1sayHello(); // Error
2
3const sayHello = () => {
4  console.log("Hello");
5};

6. Is JavaScript compiled or interpreted?

JavaScript is neither purely compiled nor purely interpreted. Modern JavaScript engines use Just-In-Time (JIT) compilation, meaning the code is first parsed and compiled into bytecode, and then optimized into machine code at runtime. So, JavaScript is technically a JIT-compiled language that behaves like an interpreted language from the developer's perspective.

Example

javascript
1function add(a, b) {
2  return a + b;
3}
4console.log(add(5, 10));

When this runs:

  1. The JavaScript engine parses the code.

  2. It converts it into bytecode.

  3. Frequently executed code is optimized into machine code using JIT.

  4. The result 15 is printed.

7. What happens when you declare the same var twice?

In JavaScript, if a variable is declared with the keyword var more than once in the same scope, it does not throw an error. JavaScript allows redeclaration with var, and the latest assignment overwrites the previous value. This behavior can sometimes lead to bugs, which is why let and const are preferred in modern JavaScript.

Example

javascript
1var x = 10;
2var x = 20;  // Redeclaration allowed
3console.log(x); // 20

8. Explain passed by value and passed by reference.

In JavaScript, primitive data types are passed by value, which means a copy of the actual value is passed to the function, and therefore any changes made in the function will not affect the original variable. Non-primitive data types, such as objects and arrays, are passed by reference, which means the reference, or memory address, is passed to the function, and therefore any changes made in the function will affect the original object.

Example

Pass by Value (Primitive)

javascript
1function update(num) {
2  num = 20;
3}
4
5let x = 10;
6update(x);
7console.log(x); // 10

Pass by Reference (Object)

javascript
1function update(obj) {
2  obj.name = "John";
3}
4
5let user = { name: "Doe" };
6update(user);
7console.log(user.name); // "John"

9. What are callbacks?

A callback is a function that is passed as an argument to another function and is executed after some operation is completed. Callbacks are commonly used in asynchronous operations like API calls, file handling, and timers. Since functions are first-class citizens in JavaScript, they can be passed and executed later as callbacks.

Example:

Simple Callback Example

javascript
1function greet(name, callback) {
2  console.log("Hello " + name);
3  callback();
4}
5
6function sayBye() {
7  console.log("Goodbye!");
8}
9
10greet("John", sayBye);

Asynchronous Callback Example

javascript
1setTimeout(function() {
2  console.log("This runs after 2 seconds");
3}, 2000);

10. What is an Immediately Invoked Function in JavaScript?

Immediately Invoked Function Expression (IIFE): An IIFE is a function in JavaScript that is immediately invoked after it is created. It is mostly used to create a private scope and prevent the global namespace from being polluted. IIFEs were used before the use of let and const to handle variable scope.

Example

javascript
1(function() {
2  console.log("I run immediately!");
3})();

With Parameters:

javascript
1(function(name) {
2  console.log("Hello " + name);
3})("John");

11. What is the difference between map() and forEach()?

The main difference between map() and forEach() is that map() returns a new array with changed elements, while forEach() does not return anything and is used only for iterating over an array. map() is used when you want to modify data, whereas forEach() is used when you just want to perform an action on each element.

Example

javascript
1const numbers = [1, 2, 3];
2
3// Using map()
4const doubled = numbers.map(num => num * 2);
5console.log(doubled); // [2, 4, 6]
6
7// Using forEach()
8const result = numbers.forEach(num => num * 2);
9console.log(result); // undefined

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

The main difference between slice() and splice() is that slice() returns a shallow copy of a portion of an array without modifying the original array, while splice() modifies the original array by adding, removing, or replacing elements.

Example

javascript
1const arr = [1, 2, 3, 4, 5];
2
3// slice()
4const sliced = arr.slice(1, 4);
5console.log(sliced); // [2, 3, 4]
6console.log(arr);    // [1, 2, 3, 4, 5] (unchanged)
7
8// splice()
9const spliced = arr.splice(1, 2);
10console.log(spliced); // [2, 3]
11console.log(arr);     // [1, 4, 5] (modified)

13. What are shallow copies and deep copies?

In a shallow copy, a new object is created, but only the top-level properties are copied. This means that the nested objects are still references to the original object. In a deep copy, a new object is created that is completely independent of the original object, including the nested objects. This means that any changes made to the new object will not affect the original object.

Example

Shallow Copy

javascript
1const original = {
2  name: "John",
3  address: { city: "Jaipur" }
4};
5
6const shallowCopy = { ...original };
7shallowCopy.address.city = "Delhi";
8
9console.log(original.address.city); // Delhi

Deep Copy

javascript
1const original = {
2  name: "John",
3  address: { city: "Jaipur" }
4};
5
6const deepCopy = JSON.parse(JSON.stringify(original));
7deepCopy.address.city = "Delhi";
8
9console.log(original.address.city); // Jaipur

14. What are promises?

A Promise in JavaScript is an object that holds the eventual completion or failure of an asynchronous operation. It assists in dealing with asynchronous code in a cleaner manner than using callbacks. A Promise has three states: pending, fulfilled (resolved), and rejected. We use .then() to handle success and .catch() to handle errors.

Promise States

  1. Pending: Initial state

  2. Fulfilled: Operation completed successfully

  3. Rejected: Operation failed

Example

javascript
1const myPromise = new Promise((resolve, reject) => {
2  let success = true;
3
4  if (success) {
5    resolve("Operation Successful");
6  } else {
7    reject("Operation Failed");
8  }
9});
10
11myPromise
12  .then(result => {
13    console.log(result);
14  })
15  .catch(error => {
16    console.log(error);
17  });

15. What is async/await in JavaScript and how does it work?

async/await is the modern way to deal with asynchronous code in JavaScript. Theasync keyword is used to declare a function that always returns a Promise, and the await keyword pauses the execution of the function until the Promise is resolved or rejected. This makes asynchronous code look and feel like synchronous code.

Example

javascript
1function fetchData() {
2  return new Promise((resolve) => {
3    setTimeout(() => {
4      resolve("Data received");
5    }, 2000);
6  });
7}
8
9async function getData() {
10  try {
11    const result = await fetchData();
12    console.log(result);
13  } catch (error) {
14    console.log(error);
15  }
16}
17
18getData();

16. What is the use of a constructor function in javascript?

A constructor function in JavaScript is used to create and initialize multiple objects with the same structure and behavior. It acts as a blueprint for creating objects. When used with the new keyword, it creates a new object, sets this to that object, and allows us to assign properties and methods to it.

Example

javascript
1function Person(name, age) {
2  this.name = name;
3  this.age = age;
4}
5
6const user1 = new Person("John", 22);
7const user2 = new Person("Doe", 25);
8
9console.log(user1.name); // John
10console.log(user2.age);  // 25

17. What are object prototypes?

Object prototypes in JavaScript are the way through which objects inherit properties and methods from other objects. Each object in JavaScript has a hidden property called [[Prototype]] that points to another object. This creates a prototype chain, which helps objects access properties and methods defined in the prototype. This is how inheritance is achieved in JavaScript.

Example

javascript
1function Person(name) {
2  this.name = name;
3}
4
5// Adding method to prototype
6Person.prototype.greet = function() {
7  return "Hello, " + this.name;
8};
9
10const user = new Person("John");
11console.log(user.greet()); // Hello, John

Advanced JavaScript Interview Questions

1. What is Lexical Scoping?

Lexical Scoping (Static Scoping) means a variable’s scope is determined by its position in the source code, allowing inner functions to access variables defined in their outer (parent) scope.

  • The scope of a variable is determined by its position in the source code .

  • JavaScript uses lexical scoping.

  • The inner function looks up variables in the outer function where it was defined, not where it was called.

Example:

javascript
1let name = "Global";
2
3function outer() {
4  let name = "Outer";
5  
6  function inner() {
7    console.log(name);
8  }
9  
10  return inner;
11}
12
13const fn = outer();
14fn(); // "Outer"

2. What is Dynamic Scoping?

Dynamic Scoping means a variable’s value is determined by the function call stack at runtime, allowing a function to access variables from its caller’s scope rather than its lexical (defined) scope. JavaScript does not support true dynamic scoping — it uses lexical (static) scoping, but dynamic-like behavior can be simulated.

  • The scope is determined by the call stack at runtime, not where the function is written.

  • Languages like older versions of Lisp or Bash use dynamic scoping.

  • The function uses variables from the function that called it, even if it was defined elsewhere.

Example:

javascript
1let name = "Global";
2
3function printName() {
4  console.log(name);
5}
6
7function caller() {
8  let name = "Caller";
9  printName();
10}
11
12caller();

3. Explain "this" keyword.

The "this" keyword in JavaScript refers to the object that is currently executing the function. Its value depends on how the function is called, not where it is defined. In a global context, this refers to the global object; inside an object method, it refers to the object itself; in a regular function, it may refer to the global object (or undefined in strict mode); and in arrow functions, this is lexically inherited from the surrounding scope.

Example

Inside an Object Method

javascript
1const user = {
2  name: "John",
3  greet: function() {
4    console.log(this.name);
5  }
6};
7
8user.greet(); // John

Arrow Function Behavior

javascript
1const user = {
2  name: "John",
3  greet: () => {
4    console.log(this.name);
5  }
6};
7
8user.greet(); // undefined

4. Explain call(), apply() and bind() methods.

call(), apply(), and bind() are methods used to control the value of this inside a function.

  • call() invokes the function immediately with a specified "this" value and arguments passed individually.

  • apply() also invokes the function immediately but takes arguments as an array.

  • bind() does not execute the function immediately; instead, it returns a new function with this permanently bound to the specified object.

Example

javascript
1const person1 = { name: "John" };
2const person2 = { name: "Doe" };
3
4function greet(city, country) {
5  console.log(`Hello, I am ${this.name} from ${city}, ${country}`);
6}

call()

javascript
1greet.call(person1, "Jaipur", "India");
2// Hello, I am John from Jaipur, India

apply()

javascript
1greet.apply(person2, ["Delhi", "India"]);

bind()

javascript
1const boundGreet = greet.bind(person1, "Mumbai", "India");
2boundGreet();

5. Explain Higher Order Functions in javascript.

A Higher-Order Function in JavaScript is a function that either takes another function as an argument or returns a function as its result. Because functions are first-class citizens in JavaScript, they can be treated like variables, passed as arguments, and returned from other functions.

Example:

javascript
1function greet(name) {
2  return "Hello " + name;
3}
4
5function processUserInput(callback) {
6  const name = "John";
7  console.log(callback(name));
8}
9
10processUserInput(greet); // Hello John

6. What is currying in JavaScript?

Currying in JavaScript is a functional programming technique where a function with multiple arguments is transformed into a sequence of functions, each taking one argument at a time. It is used to convert a function that takes multiple arguments into a sequence of functions, each taking one argument at a time. Instead of passing all the arguments at once, we pass them one by one.

Normal Function

javascript
1function multiply(a, b) {
2  return a * b;
3}
4
5console.log(multiply(2, 3)); // 6

Curried Version

javascript
1function multiply(a) {
2  return function(b) {
3    return a * b;
4  };
5}
6
7const double = multiply(2);  // a = 2
8console.log(double(5));      // 10

7. Explain Closures in JavaScript.

A closure in JavaScript is a phenomenon where an inner function has access to variables in the outer scope even after the outer function has finished executing. Closures help a function “remember” the state of the surrounding environment, which can be very useful for data privacy, state management, and creating reusable functions.

Example

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

Explanation

  1. createCounter() defines a variable count.

  2. It returns an inner function.

  3. Even after createCounter() finishes execution, the inner function still remembers count.

  4. That memory retention is called a closure.

8. Why do closures exist? What problem do they solve?

Closures are necessary because JavaScript follows lexical scoping, which means that a function can use variables from its outer scope even after the execution of the outer function is over. Closures are useful in maintaining data privacy, state, and in creating factories for functions. They overcome the problem of maintaining state variables.

9. What is memoization?

Memoization is an optimization technique used to improve performance by storing the results of expensive function calls and returning the cached result when the same inputs occur again. It helps avoid repeated calculations and is commonly used in recursive or heavy computation functions.

Example

javascript
1function memoizedAdd() {
2  const cache = {};
3  
4  return function(num) {
5    if (cache[num]) {
6      console.log("Fetching from cache");
7      return cache[num];
8    } else {
9      console.log("Calculating result");
10      const result = num + 10;
11      cache[num] = result;
12      return result;
13    }
14  };
15}
16
17const add = memoizedAdd();
18console.log(add(5)); // Calculating result → 15
19console.log(add(5)); // Fetching from cache → 15

10. Explain Event loop.

The Event Loop is a mechanism in JavaScript that allows asynchronous operations to be handled even though JavaScript is single-threaded. It continuously checks the call stack and the callback queue (and microtask queue). If the call stack is empty, the event loop pushes queued callbacks into the stack for execution. This enables non-blocking behavior for tasks like API calls, timers, and promises.

How It Works (Step-by-Step)

  1. Call Stack: Executes synchronous code first.

  2. Web APIs: Handle async operations like setTimeout, fetch, etc.

  3. Callback Queue / Task Queue: Stores completed async callbacks.

  4. Microtask Queue: Stores promise callbacks (higher priority).

  5. Event Loop: Moves tasks to call stack when it is empty.

11. How does the Call Stack work?

The Call Stack is a data structure that JavaScript uses to manage the execution of functions. It is based on the Last In, First Out (LIFO) principle. When a function is called, it is pushed onto the Call Stack, and when it completes its execution, it is popped off the Call Stack. JavaScript runs one function at a time using the Call Stack.

How It Works (Step-by-Step)

  1. Global execution context is pushed onto the stack.

  2. When a function is called → it is pushed onto the stack.

  3. When the function completes → it is removed (popped).

  4. Execution continues with the next function in the stack.

12. What is the difference between the Callback Queue and Microtask Queue?

The main difference between the Callback Queue and the Microtask Queue lies in priority. The Microtask Queue has higher priority and is executed before the Callback Queue. Promise callbacks (.then, .catch, async/await) go into the Microtask Queue, while functions like setTimeout, setInterval, and DOM events go into the Callback Queue. The Event Loop always clears the Microtask Queue completely before processing tasks from the Callback Queue.

Example

javascript
1console.log("Start");
2
3setTimeout(() => {
4  console.log("Timeout");
5}, 0);
6
7Promise.resolve().then(() => {
8  console.log("Promise");
9});
10
11console.log("End");

Output

javascript
1Start
2End
3Promise
4Timeout

13. What is event delegation?

Event delegation is a technique in JavaScript where instead of attaching event listeners to multiple child elements, we attach a single event listener to their parent element and use event bubbling to handle events. This improves performance and reduces memory usage, especially when dealing with many dynamic elements.

JavaScript events bubble up from the target element to its parent elements. We can capture the event at the parent level and determine which child triggered it using event.target.

Example

Without Event Delegation

javascript
1const buttons = document.querySelectorAll("button");
2
3buttons.forEach(button => {
4  button.addEventListener("click", () => {
5    console.log("Button clicked");
6  });
7});

With Event Delegation

javascript
1document.getElementById("parent").addEventListener("click", function(event) {
2  if (event.target.tagName === "BUTTON") {
3    console.log("Button clicked:", event.target.textContent);
4  }
5});

14. What is Debouncing in JavaScript?

Debouncing is a performance optimization technique that delays the execution of a function until a specified time has passed since the last time it was invoked. It ensures that a function runs only after the user has stopped triggering the event for a certain duration. It is commonly used in search inputs, resize events, and API calls to avoid unnecessary repeated executions.

Example

javascript
1function debounce(func, delay) {
2  let timer;
3
4  return function(...args) {
5    clearTimeout(timer);
6    timer = setTimeout(() => {
7      func(...args);
8    }, delay);
9  };
10}
11
12const handleSearch = debounce((event) => {
13  console.log("Searching for:", event.target.value);
14}, 500);
15
16document.getElementById("search").addEventListener("input", handleSearch);

15. What is Throttling?

Throttling is a performance optimization technique that ensures a function executes at most once within a specified time interval, even if it is triggered multiple times. It is commonly used in events like scroll, resize, or mousemove to limit excessive function calls.

Example

javascript
1function throttle(func, delay) {
2  let lastCall = 0;
3
4  return function(...args) {
5    const now = new Date().getTime();
6    if (now - lastCall >= delay) {
7      lastCall = now;
8      func(...args);
9    }
10  };
11}
12
13window.addEventListener(
14  "scroll",
15  throttle(() => {
16    console.log("Scroll event triggered");
17  }, 1000)
18);

16. How does the JS engine optimize code at a high level?

At a high level, the JavaScript engine optimizes code using Just-In-Time (JIT) compilation. First, the engine parses the code and converts it into bytecode. Then, as the code runs, it monitors frequently executed parts (hot code) and compiles them into optimized machine code for faster execution. Modern engines also perform optimizations like inline caching, hidden classes, dead code elimination, and function inlining. If assumptions about the code change, the engine can de-optimize and recompile it.

Output Based Questions

1. Predict the output of the following JavaScript code snippets:

javascript
1console.log(a);
2var a = 10;

Output: undefined

2. Predict the output of the following JavaScript code snippets:

javascript
1console.log(b);
2let b = 20;

Output: ReferenceError

3. Predict the output of the following JavaScript code snippets:

javascript
1for (var i = 0; i < 3; i++) {
2  setTimeout(() => console.log(i), 100);
3}

Output:

javascript
13
23
33

Why? - var is function scoped

4. Predict the output of the following JavaScript code snippets:

javascript
1for (let i = 0; i < 3; i++) {
2  setTimeout(() => console.log(i), 100);
3}

Output:

javascript
10
21
32

5. Predict the output of the following JavaScript code snippets:

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

Output:

javascript
1Start
2End
3Promise
4Timeout

6. Predict the output of the following JavaScript code snippets:

javascript
1console.log(typeof NaN);

Output: "number"

7. Predict the output of the following JavaScript code snippets:

javascript
1let obj1 = { a: 1 };
2let obj2 = obj1;
3
4obj2.a = 5;
5
6console.log(obj1.a);

Output: 5

8. Predict the output of the following JavaScript code snippets:

javascript
1const obj = {
2  name: "JS",
3  greet: function() {
4    console.log(this.name);
5  }
6};
7
8const fn = obj.greet;
9fn();

Output: undefined

9. Predict the output of the following JavaScript code snippets:

javascript
1console.log([1, 2, 3].map(num => {
2  if (num > 1) return num * 2;
3}));

Output: [undefined, 4, 6]

10. Predict the output of the following JavaScript code snippets:

javascript
1var x = 10;
2
3function test() {
4  console.log(x);
5  var x = 20;
6}
7
8test();

Output: undefined

11. Predict the output of the following JavaScript code snippets:

javascript
1let a = { value: 1 };
2
3function change(obj) {
4  obj.value = 2;
5  obj = { value: 3 };
6}
7
8change(a);
9console.log(a.value);

Output: 2

12. Predict the output of the following JavaScript code snippets:

javascript
1console.log([] + {});
2console.log({} + []);

Output:

javascript
1[object Object]
20

13. Predict the output of the following JavaScript code snippets:

javascript
1function test() {
2  a = 5;
3}
4test();
5console.log(a);

Output: 5

14. Predict the output of the following JavaScript code snippets:

javascript
1const obj = {
2  name: "JS",
3  greet: () => {
4    console.log(this.name);
5  }
6};
7
8obj.greet();

Output: undefined

15. Predict the output of the following JavaScript code snippets:

javascript
1console.log("Start");
2
3setTimeout(() => console.log("Timeout 1"), 0);
4
5Promise.resolve()
6  .then(() => {
7    console.log("Promise 1");
8    setTimeout(() => console.log("Timeout 2"), 0);
9  })
10  .then(() => console.log("Promise 2"));
11
12console.log("End");

Output:

javascript
1Start
2End
3Promise 1
4Promise 2
5Timeout 1
6Timeout 2

Found this helpful?

Share it with your network

Related Articles

Frontend

React JS Interview Questions

Prepare for your React interview with the most asked questions for freshers and experienced developers. Covers hooks, lifecycle, performance optimization, and real-world scenarios.

Backend

Python Interview Questions

Master your Python interviews with frequently asked questions covering basics, OOP, data structures, Django, and real coding scenarios for freshers and experienced professionals.

Go2X

India's leading training and placement platform offering hands-on learning, powered by 200+ IITian and industry experts, connecting students to 1,000+ hiring and referral partners.

Let's Go2X

Stay updated with Go2X

Get course updates, interview tips, and career insights delivered to your inbox.

Contact Us

Locate Us

1st Floor, Plot No 332, Phase IV, Udyog Vihar,
Sector 19, Gurugram, Haryana 122015

Email

support@go2x.live

Phone

+91 94107 10085

© 2025 Go2X Private Limited. All rights reserved.

Made with 🧡 and a lot of late nights.

About UsPrivacy PolicyTerms of ServiceRefund Policy