Top 100+ JavaScript Interview Questions and Answers (2025)

Table of Contents

Introduction

JavaScript is the heartbeat of modern web development. It powers dynamic websites, interactive apps, and frameworks like React, Angular, and Vue. Whether you’re aiming for a frontend developer role, MERN stack development, or full-stack mastery, JavaScript interviews are inevitable. This guide by Logic Lense compiles 100+ top JavaScript interview questions with detailed, simple answers. If you go through this completely, you will gain clarity and confidence to crack any JavaScript interview smoothly.


1. Basics of JavaScript

Q1. What is JavaScript?

Answer:
JavaScript is a lightweight, interpreted, object-oriented scripting language used to build dynamic web pages. It runs on the client-side (browser) and can also be used on the server-side with Node.js. It adds behaviour and interactivity to static HTML and CSS pages.


Q2. Is JavaScript a compiled or interpreted language?

Answer:
JavaScript is an interpreted language. Traditionally, it was interpreted by the browser, but modern JavaScript engines (like V8 in Chrome) use Just-In-Time (JIT) compilation to improve performance.


Q3. What are the features of JavaScript?

Answer:

  • Lightweight & interpreted

  • Dynamic typing

  • Object-oriented with prototype-based inheritance

  • First-class functions

  • Event-driven programming

  • Runs in browser & server (Node.js)


2. Data Types & Variables

Q4. What are the data types in JavaScript?

Answer:
JavaScript has two types of data types:

  • Primitive: String, Number, Boolean, Null, Undefined, Symbol, BigInt

  • Non-Primitive (Reference Types): Objects, Arrays, Functions


Q5. What is the difference between ‘undefined’ and ‘null’?

Answer:

  • undefined: A variable declared but not assigned a value. Example:

let x;
console.log(x); // undefined
  • null: Represents no value or empty value explicitly assigned. Example:

let x = null;
console.log(x); // null

Q6. What are ‘let’, ‘const’, and ‘var’?

Answer:

  • var: Function scoped, can be redeclared, hoisted as undefined

  • let: Block scoped, cannot be redeclared in same scope, hoisted but not initialised

  • const: Block scoped, must be initialised during declaration, cannot be reassigned


3. Operators & Expressions

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

Answer:

  • == (Loose equality): Compares values after type conversion

  • === (Strict equality): Compares values and types both

Example:

'5' == 5 // true
'5' === 5 // false

Q8. What is NaN in JavaScript?

Answer:
NaN stands for Not a Number. It is a property indicating that a value is not a legal number.

Example:

console.log("abc" / 2); // NaN

4. Functions

Q9. What is a function in JavaScript?

Answer:
A function is a block of reusable code that performs a specific task. It can be called with parameters to execute logic and optionally return a value.


Q10. What are arrow functions?

Answer:
Introduced in ES6, arrow functions provide a shorter syntax and do not have their own ‘this’.
Example:

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

Q11. What is IIFE (Immediately Invoked Function Expression)?

Answer:
An IIFE is a function that runs immediately after declaration.

Example:

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

5. Scope & Hoisting

Q12. What is scope in JavaScript?

Answer:
Scope defines where variables are accessible. Types:

  • Global Scope: Accessible everywhere

  • Function Scope: Variables declared inside a function

  • Block Scope: (ES6) Variables declared with let and const inside { }


Q13. What is hoisting in JavaScript?

Answer:
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

Example:

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

6. Arrays & Objects

Q14. How to declare an array in JavaScript?

Answer:

let arr = [1,2,3,4];

Q15. How to iterate through an array?

Answer:
Using for loop, forEach, map, for..of, etc.

Example with forEach:

arr.forEach(item => console.log(item));

7. ES6 Features

Q16. What are template literals?

Answer:
Template literals allow embedded expressions and multiline strings using backticks (`).

Example:

let name = "Logic Lense";
console.log(`Welcome to ${name}`);

Q17. What is destructuring?

Answer:
Extracting values from arrays or properties from objects into distinct variables.

Example:

const user = {name: "Raj", age: 25};
const {name, age} = user;
console.log(name, age);

8. Asynchronous JavaScript

Q18. What is callback in JavaScript?

Answer:
A callback is a function passed as an argument to another function, executed after the completion of that function.


Q19. What is Promise in JavaScript?

Answer:
A Promise is an object representing the eventual completion or failure of an asynchronous operation.

Syntax:

let promise = new Promise((resolve, reject) => {
 // async task
});

Q20. What is async/await?

Answer:
Introduced in ES8, async/await simplifies writing promises in a synchronous style.

Example:

async function fetchData(){
 let data = await fetch(url);
}

21. What is ‘this’ keyword in JavaScript?

Answer:
‘this’ refers to the object it belongs to.

  • In a method, ‘this’ refers to the owner object.

  • Alone, ‘this’ refers to the global object (window in browsers).

  • In strict mode, alone ‘this’ is undefined.

  • In arrow functions, ‘this’ retains the value of enclosing lexical context.

Example:

const user = {
  name: "Raj",
  getName: function(){
    return this.name;
  }
};
console.log(user.getName()); // Raj

22. What are closures in JavaScript?

Answer:
A closure is a function having access to its outer function scope even after the outer function has returned.

Example:

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

23. Explain event bubbling and event capturing.

Answer:

  • Event Bubbling: Event propagates from child to parent elements (bottom to top).

  • Event Capturing (Trickling): Event propagates from parent to child elements (top to bottom).

By default, JavaScript uses event bubbling.


24. How do you stop event propagation?

Answer:
Use event.stopPropagation() to prevent further propagation of the current event in the capturing and bubbling phases.


25. What is the difference between call(), apply(), and bind()?

Answer:

MethodUsageExample
call()Calls function with given this value and arguments separatelyfunc.call(obj, arg1, arg2)
apply()Calls function with given this value and arguments as an arrayfunc.apply(obj, [arg1, arg2])
bind()Returns a new function, permanently binding this valuelet newFunc = func.bind(obj)

26. What is prototypal inheritance?

Answer:
In JavaScript, objects can inherit properties from other objects via prototype chaining. Each object has a [[Prototype]] (or __proto__) that refers to another object, enabling inheritance.


27. How to create an object in JavaScript?

Answer:

  • Object literal:

const obj = { name: "Raj", age: 25 };
  • Using new Object():

const obj = new Object();
obj.name = "Raj";
  • Using constructor function:

function User(name){
  this.name = name;
}
const u = new User("Raj");
  • Using Object.create():

const obj = Object.create(protoObj);

28. What are higher-order functions?

Answer:
Functions that take other functions as arguments or return functions are called higher-order functions.

Example:

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

29. What is currying in JavaScript?

Answer:
Currying is transforming a function with multiple arguments into a sequence of functions each taking a single argument.

Example:

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

30. What is the spread operator?

Answer:
The spread operator ... expands iterable objects into individual elements.

Example:

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

31. What is the rest parameter?

Answer:
The rest parameter syntax allows representing an indefinite number of arguments as an array.

Example:

function sum(...args){
  return args.reduce((a,b)=>a+b,0);
}
console.log(sum(1,2,3)); // 6

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

Answer:

MethodDescription
slice()Returns a shallow copy of a portion of an array without modifying the original array
splice()Changes the original array by adding/removing elements

Example:

let arr = [1,2,3,4,5];
console.log(arr.slice(1,3)); // [2,3]
arr.splice(1,2); // removes 2,3
console.log(arr); // [1,4,5]

33. How to check if a variable is an array?

Answer:
Use Array.isArray(variable)

Example:

let arr = [1,2,3];
console.log(Array.isArray(arr)); // true

34. Explain JSON.stringify and JSON.parse.

Answer:

  • JSON.stringify: Converts JS object to JSON string

  • JSON.parse: Converts JSON string to JS object

Example:

let obj = {name:"Raj"};
let str = JSON.stringify(obj); // '{"name":"Raj"}'
let newObj = JSON.parse(str);

35. What is the use of setTimeout()?

Answer:
setTimeout() executes a function after a specified delay (in milliseconds).

Example:

setTimeout(() => console.log("Hello"), 2000);

36. What is the event loop in JavaScript?

Answer:
The event loop continuously checks the call stack and task queue, executing tasks in order and handling asynchronous callbacks efficiently, enabling non-blocking behaviour.


37. Explain call stack in JavaScript.

Answer:
Call stack is a mechanism for tracking function execution context. When a function is called, it’s pushed onto the stack; when execution finishes, it’s popped off.


38. What is memoization?

Answer:
Memoization is an optimization technique to cache results of expensive function calls, returning cached result when the same inputs occur again.

Example:

const memo = {};
function factorial(n){
  if(n in memo) return memo[n];
  if(n===0) return 1;
  return memo[n] = n * factorial(n-1);
}

39. How to remove duplicates from an array?

Answer:
Using Set:

let arr = [1,2,2,3,4,4];
let unique = [...new Set(arr)];
console.log(unique); // [1,2,3,4]

40. What is debouncing?

Answer:
Debouncing is limiting the rate at which a function is executed by ensuring it runs only after a certain time has elapsed since the last call. Used in input search, resize events.

Example:

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

41. What is throttling?

Answer:
Throttling limits a function to be called at most once in a specified time interval, regardless of how many times it’s triggered.

Example:

function throttle(func, limit){
  let flag = true;
  return function(){
    if(flag){
      func.apply(this, arguments);
      flag = false;
      setTimeout(() => flag = true, limit);
    }
  }
}

42. Explain localStorage and sessionStorage.

Answer:

StoragePersistenceScope
localStorageNo expiration, persists until clearedAcross tabs & windows
sessionStorageClears when browser/tab closesPer tab session

43. What is AJAX?

Answer:
AJAX (Asynchronous JavaScript And XML) is a technique to send and receive data asynchronously without reloading the webpage, using XMLHttpRequest or Fetch API.


44. Difference between fetch() and XMLHttpRequest?

Answer:

fetch()XMLHttpRequest
Promise-based, cleaner syntaxCallback-based
Modern approachOlder method
More readable chainingVerbose code

45. What is the purpose of try…catch?

Answer:
To handle runtime errors gracefully without breaking the code execution flow.

Example:

try {
  let x = y + 1; // y not defined
} catch(err) {
  console.log(err.message);
}

46. What is a promise chaining?

Answer:
Using multiple .then() calls to handle sequential asynchronous operations.

Example:

fetch(url)
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.log(err));

47. Explain asynchronous vs synchronous in JS.

Answer:

SynchronousAsynchronous
Executes line by line, blockingExecutes without blocking, uses callbacks, promises, async/await
Slow for long tasksEfficient for I/O operations

48. What is Symbol type in JS?

Answer:
Symbol is a primitive data type introduced in ES6, representing unique identifiers, often used for object property keys to avoid name clashes.

Example:

const id = Symbol("id");

49. What is BigInt in JavaScript?

Answer:
BigInt is a primitive data type introduced to represent integers larger than Number.MAX_SAFE_INTEGER (2^53 – 1).

Example:

let big = 123456789012345678901234567890n;

50. What is a generator function?

Answer:
Generator functions use function* syntax and can pause execution using yield and resume later, returning an iterator.

Example:

function* gen(){
  yield 1;
  yield 2;
}
const g = gen();
console.log(g.next()); // {value:1, done:false}

51. What are modules in JavaScript?

Answer:
Modules allow you to break code into reusable files, exporting and importing functionalities between them.

Example:

module1.js

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

module2.js

import { greet } from './module1.js';
greet();

52. Difference between default export and named export?

Answer:

Default ExportNamed Export
Only one per fileMultiple per file
Imported without curly bracesImported with curly braces

Example:

// default export
export default function(){}

// named export
export function greet(){}

53. What is strict mode in JavaScript?

Answer:
Strict mode ("use strict";) enables stricter parsing and error handling, preventing accidental global variables and unsafe actions.

Example:

"use strict";
x = 10; // Error: x is not defined

54. What is the typeof operator?

Answer:
Returns a string indicating the type of the operand.

Example:

console.log(typeof "Hello"); // string
console.log(typeof 10); // number
console.log(typeof null); // object (JS quirk)
console.log(typeof undefined); // undefined

55. What are template engines?

Answer:
Template engines enable you to embed JavaScript code into HTML pages dynamically (e.g. EJS, Handlebars).


56. Explain event delegation.

Answer:
Event delegation uses event bubbling to handle events at a higher level instead of adding listeners to individual elements, improving performance.

Example:

document.querySelector('ul').addEventListener('click', function(e){
  if(e.target.tagName === 'LI'){
    console.log(e.target.textContent);
  }
});

57. What is functional programming?

Answer:
Functional programming treats computation as evaluation of mathematical functions without changing state or data, emphasising pure functions and immutability.


58. Explain map(), filter(), and reduce().

Answer:

  • map(): Returns a new array with function applied to each element.

  • filter(): Returns elements that pass the condition.

  • reduce(): Returns a single value by reducing the array.

Example:

let arr = [1,2,3,4];

arr.map(x => x*2); // [2,4,6,8]
arr.filter(x => x%2==0); // [2,4]
arr.reduce((a,b) => a+b, 0); // 10

59. Explain immutability.

Answer:
Immutability means data cannot be changed once created. In JS, arrays and objects can be mutated but immutability is enforced via practices like using const and spreading for copies.

Example:

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

60. What are async iterators?

Answer:
Async iterators combine async with iterable protocol, allowing asynchronous looping using for await...of.

Example:

async function* gen(){
  yield "Hello";
}
(async ()=>{
  for await (let v of gen()){
    console.log(v);
  }
})();

61. What is WeakMap and WeakSet?

Answer:

  • WeakMap: Keys are objects, references are weak (not preventing garbage collection).

  • WeakSet: Similar to WeakMap but for sets.


62. What is the difference between for…in and for…of?

Answer:

for…infor…of
Iterates over keys of objectIterates over values of iterable
Works with objectsWorks with arrays, strings, etc.

63. What is a polyfill?

Answer:
Polyfill is code that implements modern features on older browsers that do not support them.

Example: Polyfill for Array.prototype.includes

if (!Array.prototype.includes) {
  Array.prototype.includes = function(search) {
    return this.indexOf(search) !== -1;
  };
}

64. What is service worker?

Answer:
Service worker is a script that runs in the background, enabling features like offline support, caching, and push notifications.


65. What are promises states?

Answer:

  • Pending: Initial state

  • Fulfilled: Operation completed successfully

  • Rejected: Operation failed


66. Explain microtask and macrotask queues.

Answer:

  • Microtasks: Processed after current execution ends and before the next macrotask (e.g. promises).

  • Macrotasks: Scheduled via setTimeout, setInterval, I/O tasks.


67. What is the purpose of Object.freeze()?

Answer:
Prevents modification of existing properties and adding new properties to an object.

Example:

const obj = {name:"Raj"};
Object.freeze(obj);
obj.name = "Aman"; // no change

68. What is destructuring assignment?

Answer:
Extracting properties from objects or items from arrays into distinct variables.

Example:

const [a,b] = [1,2];
const {name, age} = {name:"Raj", age:25};

69. What is optional chaining?

Answer:
Introduced in ES2020, it safely accesses deeply nested properties.

Example:

let user = {};
console.log(user?.profile?.email); // undefined instead of error

70. What is nullish coalescing operator?

Answer:
?? returns right operand if left is null or undefined.

Example:

let a = null ?? "default"; // "default"

71. Explain setInterval()

Answer:
Executes a function repeatedly after specified interval.

Example:

setInterval(()=>console.log("Hi"), 1000);

72. How to clear setTimeout or setInterval?

Answer:

let timer = setTimeout(func, 2000);
clearTimeout(timer);

let interval = setInterval(func, 1000);
clearInterval(interval);

73. What is EventTarget.addEventListener()?

Answer:
Attaches an event handler to a specific event type on an element.

Example:

document.getElementById("btn").addEventListener("click", ()=>{});

74. Explain fetch API.

Answer:
Modern way to make network requests returning promises.

Example:

fetch(url)
  .then(res => res.json())
  .then(data => console.log(data));

75. What is JSONP?

Answer:
JSONP (JSON with Padding) is a technique to overcome cross-domain limitations by using script tags, mainly before CORS existed.


76. What is CORS?

Answer:
Cross-Origin Resource Sharing allows or restricts resources from different origins through headers set by the server.


77. What is prototype chain?

Answer:
Chain of objects used to implement inheritance and property lookup.

Example:

obj.__proto__ -> Object.prototype -> null

78. Difference between Object.create() and new?

Answer:

Object.create()new
Creates object with specified prototypeCreates instance using constructor function
No constructor callCalls constructor

79. Explain bind vs arrow functions for ‘this’.

Answer:
Arrow functions inherit ‘this’ from parent scope whereas bind() sets ‘this’ permanently.


80. What is dynamic typing?

Answer:
Variables in JS can hold different types at different times as types are checked at runtime.


81. Difference between synchronous and asynchronous exceptions?

Answer:

  • Synchronous: Caught using try…catch.

  • Asynchronous: Need handling in callback or promise catch block.


82. Explain eval().

Answer:
eval() evaluates JS code represented as string. It should be avoided due to security and performance issues.

Example:

eval("console.log(2+2)");

83. What is event loop starvation?

Answer:
When long-running synchronous tasks block the event loop, preventing asynchronous callbacks from executing.


84. How to clone an object?

Answer:

let obj = {a:1};
let clone = {...obj};

Or

let clone = Object.assign({}, obj);

85. What is DOM?

Answer:
Document Object Model is a programming interface for HTML and XML documents, representing them as tree structures.


86. Explain delegation vs composition vs inheritance.

Answer:

  • Delegation: Object delegates tasks to another object.

  • Composition: Combine simple functions for complex behaviour.

  • Inheritance: Deriving new classes from existing classes.


87. What is a callback hell?

Answer:
Nested callbacks that become hard to read and maintain. Promises and async/await solve this.


88. What is functional composition?

Answer:
Combining two or more functions to produce a new function.

Example:

const compose = (f,g) => x => f(g(x));

89. What is tail call optimization?

Answer:
An optimization where the compiler reuses stack frames for recursive calls in tail position, avoiding stack overflow. JS engines rarely implement it fully.


90. Difference between == and Object.is()?

Answer:

==Object.is()
Loose equalityStrict equality including NaN === NaN
Converts typesNo type conversion

Example:

Object.is(NaN, NaN); // true
NaN === NaN; // false

91. Explain microtask queue vs macrotask queue with example.

Answer:
Microtasks (promises) are executed before the next macrotask (setTimeout).

Example:

console.log("start");
setTimeout(()=>console.log("timeout"),0);
Promise.resolve().then(()=>console.log("promise"));
console.log("end");
// start -> end -> promise -> timeout

92. What is the purpose of Function.prototype.apply()?

Answer:
Calls a function with a given this value and arguments as an array.


93. What is reflow and repaint?

Answer:

  • Reflow: Calculating layout and geometry changes.

  • Repaint: Updating styles without layout change. Reflow triggers repaint but repaint doesn’t trigger reflow.


94. What is hoisting with functions vs variables?

Answer:

  • Function declarations: Hoisted with definition.

  • Variables declared with var: Hoisted as undefined.


95. Difference between function declaration and function expression?

Answer:

Function DeclarationFunction Expression
HoistedNot hoisted
Syntax: function foo(){}Syntax: const foo = function(){}

96. Explain garbage collection in JS.

Answer:
Automatic memory management removing unused objects, typically using reference counting and mark-and-sweep algorithms.


97. What is internationalization (i18n)?

Answer:
Process of designing applications to support multiple languages and regions without code changes.


98. What is NaN?

Answer:
“Not a Number” indicates an invalid number result.

Example:

console.log("abc"/2); // NaN

99. What is chaining in jQuery or JS?

Answer:
Calling multiple methods sequentially on the same object.

Example:

$('#id').css().hide().fadeIn();

100. Final JS Interview Tip

Always explain with examples and practical reasoning. Interviewers value clarity of thought, not just definitions.


Conclusion: Your Final Step to Ace JavaScript Interviews

These 100+ JavaScript interview questions and answers by Logic Lense are designed to build your conceptual clarity and confidence. Bookmark this, revise daily, and practice code snippets to make your preparation unbeatable. JavaScript interviews test both concept clarity and coding confidence. This comprehensive list is designed to ensure that you understand each topic thoroughly, not just memorise answers. Practice these, build small projects, and strengthen logical thinking to stand out in your interviews.


📚 Stay Ahead in Your Coding Journey

➡️ Stay connected with Logic Lense for more Frontend, MERN, and full-stack interview preparation guides.

➡️ Share this with your developer community and strengthen your learning.

➡️Follow Our Youtube Channel to stay in touch with Latest technology

Subscribe to ASP.NET Core Newsletter.

Want to advance your career in .NET and Architecture? Join 1,000+ readers of my newsletter. Each week you will get 1 practical tip with best practices and real-world examples.

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart