?
40%

Complete your profile to find better job opportunities

JavaScript Interview Questions and Answers for 2026 (Freshers to Experienced)

August 1, 202620 min read
JavaScript Interview Questions and Answers for 2026 (Freshers to Experienced)

If you are preparing for a frontend or full-stack role in India, JavaScript interview questions are the single most important topic to master. Whether you are sitting for a fresher round at a Bangalore product startup or a senior interview at a Pune services company, interviewers keep circling back to the same core ideas: scope, hoisting, closures, the this keyword, prototypes, and asynchronous behaviour. This guide collects 45+ of the most commonly asked JavaScript interview questions, each with a concise, correct answer and runnable code where it helps. Work through it top to bottom and you will walk into your next round with real confidence rather than memorised one-liners.

The questions are grouped by subtopic and roughly ordered from basics to advanced, so freshers can start at the top and experienced candidates can jump to closures, the event loop, and output-based puzzles. Let us begin.

Basics and Data Types

1. What are the data types in JavaScript?

JavaScript has eight data types. Seven are primitives: string, number, bigint, boolean, undefined, symbol, and null. The eighth is object, which includes arrays, functions, dates, and plain objects. Primitives are immutable and compared by value; objects are compared by reference.

2. What is the difference between null and undefined?

undefined means a variable has been declared but no value has been assigned, or a property does not exist. null is an intentional assignment representing "no value". A quirk to remember: typeof undefined is "undefined" but typeof null is "object" (a long-standing bug in the language kept for backward compatibility).

let a;
console.log(a);        // undefined
let b = null;
console.log(b);        // null
console.log(typeof null);      // "object"
console.log(null == undefined);   // true
console.log(null === undefined);  // false

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

== (loose equality) compares values after performing type coercion, so 5 == "5" is true. === (strict equality) compares both value and type without coercion, so 5 === "5" is false. As a rule, prefer === to avoid surprising coercions.

Expression == result === result
5 == "5" true false
0 == false true false
null == undefined true false
NaN == NaN false false
"" == 0 true false

4. What are truthy and falsy values?

A falsy value is treated as false in a boolean context. There are exactly eight: false, 0, -0, 0n, "", null, undefined, and NaN. Everything else is truthy, including "0", "false", [], and {}.

if ([]) console.log("empty array is truthy"); // prints
if ("0") console.log("non-empty string is truthy"); // prints

5. What is NaN and how do you check for it?

NaN stands for "Not a Number" and is the result of an invalid numeric operation such as 0/0 or parseInt("abc"). It is the only value in JavaScript that is not equal to itself, so NaN === NaN is false. Use Number.isNaN(value) to check reliably; avoid the global isNaN() because it coerces its argument first.

console.log(Number.isNaN(NaN));       // true
console.log(Number.isNaN("hello"));   // false (not coerced)
console.log(isNaN("hello"));          // true (coerced, misleading)

6. What is type coercion?

Type coercion is the automatic conversion of a value from one type to another. It happens implicitly during operations like "5" + 1 (produces "51" because + favours string concatenation) or "5" - 1 (produces 4 because - forces numeric conversion). Understanding coercion rules is key to answering output-based JavaScript interview questions.

var, let, const and Scope

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

This is one of the most frequently asked JavaScript interview questions in India, especially in frontend fresher rounds.

Feature var let const
Scope Function Block Block
Hoisting Yes, initialised as undefined Yes, but in TDZ Yes, but in TDZ
Re-declaration Allowed Not allowed Not allowed
Re-assignment Allowed Allowed Not allowed

Note that const prevents re-assignment of the binding, not mutation of the underlying object. You can still push to a const array.

const arr = [1, 2];
arr.push(3);           // allowed, mutating contents
console.log(arr);      // [1, 2, 3]
// arr = [4];          // TypeError: assignment to constant variable

8. What are the types of scope in JavaScript?

There are three: global scope (declared outside any function, accessible everywhere), function scope (variables declared with var inside a function), and block scope (variables declared with let/const inside {}). Block scope was introduced in ES6.

9. What is lexical scope?

Lexical (or static) scope means a function's access to variables is determined by where it is defined in the source code, not where it is called from. Inner functions can access variables of their outer functions, forming a scope chain.

10. What is the Temporal Dead Zone (TDZ)?

The TDZ is the period between entering a scope and the point where a let or const variable is declared. Accessing the variable in this window throws a ReferenceError. This is why let and const are said to be hoisted but not initialised.

console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 5;

Hoisting

11. What is hoisting?

Hoisting is JavaScript's behaviour of moving declarations to the top of their scope during the compile phase. var declarations are hoisted and initialised as undefined. Function declarations are hoisted entirely (you can call them before they appear). let and const are hoisted but stay in the TDZ.

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

greet();        // "Hi" (function declaration fully hoisted)
function greet() { console.log("Hi"); }

12. Are function expressions hoisted?

No, not in the same way. Only the variable holding the function expression is hoisted, not the function body. Calling it before assignment gives an error.

sayHi(); // TypeError: sayHi is not a function
var sayHi = function () { console.log("Hi"); };

13. What is the difference between a function declaration and a function expression?

A function declaration (function foo() {}) is fully hoisted and can be called before its definition. A function expression (const foo = function () {}) is assigned to a variable and only callable after that line executes. Arrow functions are always expressions.

Closures

14. What is a closure?

A closure is a function that retains access to variables from its outer (enclosing) scope even after that outer function has finished executing. Closures are created every time a function is defined and are the foundation of data privacy, currying, and many callback patterns.

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

Here the inner function "closes over" count, keeping it alive between calls.

15. What is a practical use of closures?

Data encapsulation. Because the inner variable cannot be accessed directly from outside, closures let you build private state, module patterns, and memoization caches. They are also behind the classic once and debounce utilities.

16. What is the classic closure loop bug and how do you fix it?

Using var in a loop with an async callback captures the same variable, so all callbacks log the final value. Fix it by using let (block-scoped per iteration) or an IIFE.

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

17. What is currying?

Currying transforms a function that takes multiple arguments into a chain of functions each taking a single argument. It relies on closures and is popular in functional programming and interview coding rounds.

const add = a => b => c => a + b + c;
console.log(add(1)(2)(3)); // 6

The this Keyword, call, apply and bind

18. What is the this keyword?

this refers to the object that is executing the current function. Its value is determined by how the function is called (the call-site), not where it is defined. In the global context it is the window object (or undefined in strict mode). Inside a method, it is the object owning the method.

19. How does this behave in an arrow function?

Arrow functions do not have their own this. They inherit this lexically from the surrounding scope at the time they are defined. This makes them ideal for callbacks where you want to preserve the outer this.

const obj = {
  name: "Goodspace",
  regular() { return this.name; },
  arrow: () => this.name,
};
console.log(obj.regular()); // "Goodspace"
console.log(obj.arrow());   // undefined (this is outer scope)

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

All three set this explicitly. call invokes the function immediately with arguments passed individually. apply invokes immediately with arguments as an array. bind returns a new function with this permanently bound, to be called later.

function intro(city, role) {
  return `${this.name} is a ${role} in ${city}`;
}
const user = { name: "Riya" };
console.log(intro.call(user, "Pune", "developer"));
console.log(intro.apply(user, ["Pune", "developer"]));
const bound = intro.bind(user);
console.log(bound("Pune", "developer"));

21. What is the value of this in a regular function called standalone?

In non-strict mode it is the global object (window in browsers). In strict mode it is undefined. This is a common trap in output-based JavaScript interview questions.

Prototypes and Inheritance

22. What is the prototype in JavaScript?

Every JavaScript object has an internal link to another object called its prototype. When you access a property that does not exist on the object, the engine looks up the prototype chain until it finds it or reaches null. This is how JavaScript implements inheritance, known as prototypal inheritance.

23. What is the prototype chain?

The prototype chain is the series of linked prototype objects the engine traverses during property lookup. For example, an array's chain is myArray -> Array.prototype -> Object.prototype -> null. Methods like map live on Array.prototype, shared by all arrays without duplication.

const arr = [1, 2, 3];
console.log(arr.__proto__ === Array.prototype);          // true
console.log(Array.prototype.__proto__ === Object.prototype); // true

24. How does inheritance work with ES6 classes?

ES6 class syntax is syntactic sugar over prototypes. extends sets up the prototype chain and super calls the parent constructor. Under the hood it is still prototypal inheritance.

class Animal {
  constructor(name) { this.name = name; }
  speak() { return `${this.name} makes a sound`; }
}
class Dog extends Animal {
  speak() { return `${this.name} barks`; }
}
console.log(new Dog("Bruno").speak()); // "Bruno barks"

25. What is the difference between __proto__ and prototype?

prototype is a property of constructor functions, used to build the prototype of objects created with new. __proto__ is the actual reference on every object pointing to its prototype. In short, instance.__proto__ === Constructor.prototype.

26. What are the ways to create an object in JavaScript?

Object literal ({}), constructor function with new, Object.create(proto), ES6 classes, and factory functions that return an object. Object.create is useful when you want to set the prototype explicitly.

Asynchronous JavaScript

27. What is the difference between synchronous and asynchronous code?

Synchronous code runs line by line, blocking the next line until the current one finishes. Asynchronous code allows long-running tasks (network calls, timers) to run in the background and notify you later via callbacks, promises, or async/await, keeping the single-threaded main thread responsive.

28. What is a callback and what is callback hell?

A callback is a function passed to another function to be executed later. Callback hell is deeply nested callbacks that become hard to read and maintain, often forming a "pyramid of doom". Promises and async/await were introduced to flatten this nesting.

29. What is a Promise?

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states: pending, fulfilled, and rejected. Once settled, a promise cannot change state. You consume it with .then(), .catch(), and .finally().

const p = new Promise((resolve, reject) => {
  setTimeout(() => resolve("done"), 100);
});
p.then(res => console.log(res)).catch(err => console.log(err));

30. What is the difference between Promise.all, Promise.race, Promise.allSettled, and Promise.any?

  • Promise.all waits for all to fulfil, rejects immediately if any one rejects.
  • Promise.race settles as soon as the first promise settles, fulfilled or rejected.
  • Promise.allSettled waits for all and returns each result's status, never short-circuiting.
  • Promise.any fulfils with the first fulfilled promise, rejects only if all reject.
const results = await Promise.allSettled([
  Promise.resolve(1),
  Promise.reject("err"),
]);
console.log(results);
// [{status:"fulfilled", value:1}, {status:"rejected", reason:"err"}]

31. What is async/await?

async/await is syntactic sugar over promises that lets you write asynchronous code that reads like synchronous code. An async function always returns a promise, and await pauses execution until the awaited promise settles. Use try/catch for error handling.

async function getUser() {
  try {
    const res = await fetch("/api/user");
    const data = await res.json();
    return data;
  } catch (err) {
    console.error("Failed:", err);
  }
}

32. What is the event loop?

The event loop is the mechanism that lets single-threaded JavaScript handle asynchronous operations. Synchronous code runs on the call stack. When async tasks complete, their callbacks are queued. The event loop moves queued callbacks onto the stack only when the stack is empty. This is a favourite among experienced JavaScript interview questions.

33. What is the difference between the microtask queue and the macrotask queue?

Microtasks (promise callbacks, queueMicrotask, MutationObserver) have higher priority and run completely before the next macrotask. Macrotasks include setTimeout, setInterval, and I/O. After each macrotask, the entire microtask queue is drained.

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

The promise logs before the timeout because microtasks run before the next macrotask.

ES6 and Modern JavaScript Features

34. What are template literals?

Template literals use backticks and allow embedded expressions with ${} and multi-line strings without concatenation. They also support tagged templates for custom string processing.

const name = "Amit";
console.log(`Hello ${name}, 2 + 2 = ${2 + 2}`);

35. What is destructuring?

Destructuring lets you unpack values from arrays or properties from objects into distinct variables in a single statement, with support for defaults and renaming.

const { name, city = "Delhi" } = { name: "Sara" };
const [first, , third] = [10, 20, 30];
console.log(name, city, first, third); // Sara Delhi 10 30

36. What is the difference between the spread and rest operators?

Both use .... Spread expands an iterable into individual elements (copying arrays/objects, passing arguments). Rest collects multiple elements into a single array (function parameters, destructuring). Context determines which one it is.

const merged = [...[1, 2], ...[3, 4]]; // spread -> [1,2,3,4]
function sum(...nums) {                 // rest
  return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6

37. What is optional chaining and nullish coalescing?

Optional chaining (?.) safely accesses nested properties, returning undefined instead of throwing if a reference is null or undefined. Nullish coalescing (??) returns the right operand only when the left is null or undefined, unlike || which also triggers on falsy values like 0 or "".

const user = { profile: null };
console.log(user.profile?.name);       // undefined, no error
console.log(user.count ?? 10);         // 10
console.log(0 || 5);                   // 5
console.log(0 ?? 5);                   // 0

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

map transforms each element and returns a new array of the same length. filter returns a new array with elements that pass a test. reduce accumulates all elements into a single value.

const nums = [1, 2, 3, 4];
console.log(nums.map(n => n * 2));            // [2, 4, 6, 8]
console.log(nums.filter(n => n % 2 === 0));   // [2, 4]
console.log(nums.reduce((a, b) => a + b, 0)); // 10

39. What is the difference between forEach and map?

map returns a new array of transformed values and is chainable. forEach returns undefined and is used purely for side effects. Use map when you need the result, forEach when you just want to iterate.

40. What are Set and Map?

A Set is a collection of unique values, handy for removing duplicates. A Map is a keyed collection where keys can be any type, unlike plain objects whose keys are strings or symbols. WeakMap and WeakSet hold weak references that do not prevent garbage collection.

const unique = [...new Set([1, 1, 2, 3, 3])]; // [1, 2, 3]

DOM and Events

41. What is the difference between event bubbling and event capturing?

When an event fires on an element, it travels in two phases. In capturing (top-down), the event goes from the document root down to the target. In bubbling (bottom-up), it travels from the target back up to the root. By default handlers run in the bubbling phase; pass true as the third argument to addEventListener to use capturing.

42. What is event delegation?

Event delegation attaches a single listener to a parent element and uses event.target to handle events from its children, relying on bubbling. It improves performance with many child elements and works for dynamically added elements.

document.getElementById("list").addEventListener("click", e => {
  if (e.target.tagName === "LI") console.log("Clicked:", e.target.textContent);
});

43. What is the difference between event.preventDefault() and event.stopPropagation()?

preventDefault() stops the browser's default action (for example, a form submitting or a link navigating). stopPropagation() stops the event from continuing to bubble or capture to other elements. They are independent and can be used together.

44. What is the difference between debouncing and throttling?

Both limit how often a function runs. Debouncing delays execution until a pause in events (useful for search inputs). Throttling guarantees execution at most once per fixed interval (useful for scroll and resize handlers).

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

45. What is the difference between localStorage, sessionStorage, and cookies?

localStorage persists data with no expiry until cleared. sessionStorage lasts only for the browser tab session. Cookies are smaller (around 4KB), can set expiry, and are sent to the server with every HTTP request, unlike the storage APIs which stay client-side.

Coding and Output Based Questions

46. What will this output and why?

console.log(1 + "2" + 3);   // "123"
console.log(1 + 2 + "3");   // "33"
console.log("5" - 2);       // 3
console.log([] + []);       // "" (empty string)
console.log([] + {});       // "[object Object]"
console.log(typeof NaN);    // "number"

The + operator concatenates when a string is involved and evaluates left to right; - forces numeric coercion. These trip up even experienced developers.

47. What is the output of this closure and setTimeout combination?

for (var i = 1; i <= 3; i++) {
  setTimeout(() => console.log(i), i * 1000);
}
// 4, 4, 4

Because var is function-scoped, all three callbacks share the same i, which is 4 by the time they run. Replacing var with let prints 1, 2, 3.

48. How do you deep clone an object?

For simple data, structuredClone(obj) (modern browsers) or JSON.parse(JSON.stringify(obj)) works, though the JSON approach drops functions, undefined, and Date becomes a string. For robust cloning use structuredClone or a library like Lodash's cloneDeep.

const original = { a: 1, nested: { b: 2 } };
const copy = structuredClone(original);
copy.nested.b = 99;
console.log(original.nested.b); // 2 (unaffected)

49. How do you flatten a nested array?

Use Array.prototype.flat(depth). Pass Infinity to flatten completely regardless of nesting.

console.log([1, [2, [3, [4]]]].flat(Infinity)); // [1, 2, 3, 4]

50. Write a function to check if a string is a palindrome.

function isPalindrome(str) {
  const clean = str.toLowerCase().replace(/[^a-z0-9]/g, "");
  return clean === clean.split("").reverse().join("");
}
console.log(isPalindrome("A man, a plan, a canal: Panama")); // true

How to Prepare for a JavaScript Interview

Reading answers is not the same as being able to explain them under pressure. Here is a practical plan tailored to the Indian hiring cycle.

  1. Master the fundamentals first. Interviewers in fresher rounds almost always start with hoisting, scope, and the var/let/const differences before moving to closures and this. Do not skip them for shiny topics.
  2. Write code by hand. Many companies still use a whiteboard or a shared doc without autocomplete. Practise implementing debounce, curry, Promise.all, and array methods from scratch.
  3. Predict outputs out loud. Output-based questions test whether you truly understand coercion and the event loop. Cover the answer, guess, then verify in the console.
  4. Build one real project. Being able to talk about how you used closures or async/await in an actual app impresses interviewers far more than textbook definitions.
  5. Simulate the pressure. The gap between knowing an answer and saying it clearly in front of a stranger is real. Running a few timed mock rounds with the Goodspace AI Mock Interview helps you rehearse explaining closures and the event loop out loud before the real thing.

For your final week, revisit closures, prototypal inheritance, and the microtask versus macrotask ordering, since these separate strong candidates from average ones. A structured AI Mock Interview practice session that gives instant feedback on your answers is one of the fastest ways to find and fix your weak spots before you face a panel.

Frequently Asked Questions

How many JavaScript interview questions should I prepare for a fresher role?

Focus on quality over quantity. Cover the 45+ questions in this guide thoroughly, especially data types, hoisting, scope, closures, this, promises, and the event loop. Being able to explain 40 concepts deeply beats memorising 200 shallow answers.

Is JavaScript enough to get a frontend job in India?

Strong core JavaScript is the foundation, and interviews weight it heavily. However, most frontend roles also expect a framework (usually React), HTML, CSS, and Git. Solid JavaScript makes learning frameworks far easier and is what interviewers probe first.

What is the most commonly asked JavaScript interview question?

The difference between var, let, and const, along with closures and the behaviour of this, appear in almost every round. Output-based questions on hoisting and the event loop are close behind for slightly more experienced candidates.

How do I answer output-based JavaScript questions?

Reason through them step by step: identify coercion rules, check whether code is synchronous or asynchronous, and remember that microtasks (promises) run before macrotasks (setTimeout). Explain your reasoning aloud, since interviewers grade the thought process as much as the answer.

Should freshers learn ES6 features for interviews?

Yes. Arrow functions, destructuring, spread/rest, template literals, promises, and optional chaining are now standard in interviews and everyday code. Interviewers expect freshers to be comfortable with modern syntax, not just older var and callback patterns.

How long does it take to prepare for a JavaScript interview?

With consistent daily practice, two to four weeks is enough to cover the fundamentals and practise coding and output questions. Add extra time if you also need to prepare a framework, and always leave a few days for mock interviews to sharpen your delivery.

Final Thoughts

JavaScript interview questions reward genuine understanding over rote learning. Once you can explain why this behaves the way it does, how the prototype chain resolves a property, and why a promise callback logs before a setTimeout, you can handle almost any variation an interviewer throws at you. Work through this guide, write the code yourself, and practise saying your answers out loud. Do that, and your next JavaScript round will feel like a conversation rather than an interrogation. All the best.

Like what you read? Share with a friend.

Related articles

A job seeker at a laptop drafting a polite follow-up email, with a calendar showing a one week marker
GoodSpace TeamJul 24 • 2026

How to Follow Up on a Job Application

Learn how to follow up on a job application without being annoying. Get timelines, the right contact, and copy-paste follow-up email samples for India.

A group of young professionals seated around a table in an active group discussion during a hiring round.
GoodSpace TeamJul 24 • 2026

Group Discussion Tips to Clear Any GD Round

Practical group discussion tips for Indian campus and company hiring, covering do's and don'ts, how to lead, 20+ GD topics for 2026, and how to conclude.

A resume on screen with several sections marked in red to show common mistakes and corrections.
GoodSpace TeamJul 24 • 2026

14 Common Resume Mistakes That Get You Rejected

The most common resume mistakes that cost Indian job seekers interviews, from ATS formatting errors to missing keywords, with a clear fix for each one.

A fresher graduate reviewing a resume on a laptop with the career objective section highlighted at the top.
GoodSpace TeamJul 24 • 2026

Career Objective for Freshers: 25+ Examples

A clear guide to writing a career objective for freshers, with a simple formula and 25+ ready examples across engineering, IT, sales, finance, BPO and more.

A candidate mid answer across a table from an interviewer, notepad open, calm and prepared.
GoodSpace TeamJul 24 • 2026

Strengths and Weaknesses in an Interview: Answers

Struggling with strengths and weaknesses in an interview? Here is how to pick a real strength, frame a weakness honestly, and answer both with ready examples.

A resume open on a desk with the skills section highlighted, a job description printed beside it for comparison.
GoodSpace TeamJul 24 • 2026

Skills to Put on a Resume: What Recruiters Look For

Not sure which skills to put on a resume? How to pick skills that match the job, beat the ATS, and land interviews, with role examples for India.