
In this guide
If you are applying for a front-end, full stack or Node.js role, JavaScript is the part of the interview you cannot skip. This guide collects 74 JavaScript interview questions and answers in the order they usually come up: core concepts, functions and closures, objects and ES6, asynchronous code, the DOM, coding exercises and the output-based questions interviewers love. Every answer is short enough to say out loud and comes with code where it helps.
It is written for freshers and students, but the async, event loop and this sections are the same questions asked to developers with 2 to 3 years of experience. Each question is collapsible, so use Expand all to read straight through or open them one at a time as a quiz.
What interviewers actually test
- Fundamentals: scope, hoisting,
this, closures and equality are asked in almost every interview. - Async: promises,
async/awaitand the event loop separate beginners from job-ready developers. - Explaining: a clear one-line definition plus a small example beats a long answer.
New to the language? Start with our JavaScript roadmap for beginners, then come back here. If you are aiming for a React job, keep the React interview questions guide open as well.
Want a mock interview and a roadmap?
Leave your number. A Codeksha counsellor will call you back about syllabus, fees and a free demo class.
Core JavaScript basics 15 questions
1What is JavaScript?
JavaScript is a high-level, interpreted programming language that runs in every web browser and, through Node.js, on servers too. It is what makes a web page interactive: handling clicks, validating forms, updating content without a reload and talking to servers. It is single-threaded, dynamically typed and supports object-oriented, functional and event-driven styles.
2What is the difference between var, let and const?
varis function-scoped, can be redeclared and is hoisted and initialised asundefined.letis block-scoped, cannot be redeclared in the same scope and sits in the temporal dead zone until its line runs.constis block-scoped likeletbut must be assigned when declared and cannot be reassigned.
const does not make a value immutable: an object or array declared with const can still be changed, only the binding is fixed.
const user = { name: "Asha" };
user.name = "Riya"; // allowed, the object is mutated
user = {}; // TypeError: Assignment to constant variable3What are the data types in JavaScript?
There are seven primitive types: string, number, bigint, boolean, undefined, null and symbol. Everything else (objects, arrays, functions, dates) is an object. Primitives are immutable and compared by value; objects are compared by reference.
4What is the difference between == and ===?
== compares after type coercion, === compares value and type with no coercion. Prefer === because the coercion rules of == are easy to get wrong.
5 == "5" // true (string converted to number)
5 === "5" // false (different types)
null == undefined // true
null === undefined // false5What is the difference between null and undefined?
undefined means a variable has been declared but not assigned a value (or a function returned nothing). null is an intentional "no value" that a developer assigns. typeof undefined is "undefined", while typeof null is "object", a long-standing quirk of the language.
6Why does typeof null return "object"?
It is a bug from the first version of JavaScript that was never fixed because changing it would break existing websites. null is a primitive, not an object. To check for null, use value === null.
7What is NaN and how do you check for it?
NaN ("Not a Number") is the result of an invalid numeric operation such as 0 / "abc". It is the only value that is not equal to itself, so NaN === NaN is false. Use Number.isNaN(x), which does not coerce, rather than the global isNaN(x), which converts the argument to a number first.
isNaN("hello") // true (coerces "hello" to NaN)
Number.isNaN("hello") // false (it is a string, not NaN)
Number.isNaN(NaN) // true8What are truthy and falsy values?
In a boolean context every value is either truthy or falsy. There are only eight falsy values: false, 0, -0, 0n, "", null, undefined and NaN. Everything else is truthy, including "0", [], {} and "false".
9What is hoisting?
Hoisting is JavaScript moving declarations to the top of their scope during the compile phase. Function declarations are hoisted with their body, var is hoisted and set to undefined, and let/const are hoisted but not initialised.
console.log(a); // undefined
var a = 5;
sayHi(); // works, the whole function is hoisted
function sayHi() { console.log("hi"); }
console.log(b); // ReferenceError (temporal dead zone)
let b = 5;10What is the temporal dead zone (TDZ)?
The TDZ is the time between entering a scope and the line where a let or const variable is declared. Accessing the variable in that window throws a ReferenceError. It exists to catch use-before-define bugs that var silently allowed.
11What are the different types of scope in JavaScript?
- Global scope: variables declared outside any function or block.
- Function scope: variables declared inside a function are not visible outside it.
- Block scope:
letandconstinside{ }exist only within those braces. - Module scope: top-level variables in an ES module are private to that file unless exported.
Inner scopes can read outer scopes. This lookup is called the scope chain.
12What does "use strict" do?
Strict mode turns silent mistakes into errors. It prevents accidental global variables, disallows duplicate parameter names, makes this undefined in plain functions and throws when you assign to read-only properties. ES modules and classes are strict by default.
13What is type coercion? Give an example.
Type coercion is JavaScript converting a value from one type to another automatically. The + operator prefers strings, while -, * and / prefer numbers.
"5" + 3 // "53" (number becomes a string)
"5" - 3 // 2 (string becomes a number)
true + 1 // 2
[] + {} // "[object Object]"14What is the difference between let in a loop and var in a loop?
let creates a new binding for every iteration, so closures created in the loop capture the value of that iteration. var has one binding shared by the whole function, so all closures see the final value. This is the classic setTimeout in a for loop question (see the output-based section below).
15What is the difference between a statement and an expression?
An expression produces a value (2 + 3, fn(), x ? a : b). A statement performs an action (if, for, let x = 1) and does not produce a value you can use inline. Anywhere JavaScript expects a value you must supply an expression.
Functions, scope and closures 13 questions
Closures, this and higher-order functions are where most candidates lose marks, so spend extra time here.
16What is the difference between a function declaration and a function expression?
A declaration (function add() {}) is fully hoisted, so you can call it before it appears in the file. A function expression (const add = function() {}) is only available after the line runs, because the variable is hoisted but not its value.
17How are arrow functions different from regular functions?
- Shorter syntax and an implicit return for single expressions.
- No
thisof their own: they use thethisof the surrounding code (lexicalthis). - No
argumentsobject (use rest parameters instead). - Cannot be used with
newas constructors and have noprototype.
const double = n => n * 2;
const counter = {
count: 0,
start() {
setInterval(() => { this.count++; }, 1000); // "this" is counter
}
};18What is a closure? Give a practical example.
A closure is a function that remembers the variables of the scope where it was created, even after that outer function has finished running. Closures power private state, memoisation, callbacks and event handlers.
function makeCounter() {
let count = 0; // private variable
return function () {
count++;
return count;
};
}
const next = makeCounter();
next(); // 1
next(); // 2 (count survives between calls)Interview tip: Be ready to name a real use: data hiding, function factories, or why a loop with var and setTimeout misbehaves.
19What is an IIFE and why was it used?
An Immediately Invoked Function Expression runs as soon as it is defined: (function () { ... })();. Before let, const and modules existed, it was the way to create a private scope and avoid polluting the global namespace.
20What is a higher-order function?
A function that takes another function as an argument, returns a function, or both. map, filter, reduce, setTimeout and addEventListener are all higher-order functions.
21What is a callback function?
A function passed into another function to be called later, typically when an operation finishes or an event occurs. Callbacks are the original way to handle asynchronous work in JavaScript, and nesting many of them leads to "callback hell", which promises and async/await solve.
22What is currying?
Currying turns a function that takes several arguments into a chain of functions that each take one argument.
const add = a => b => c => a + b + c;
add(1)(2)(3); // 6
const addTen = add(5)(5); // partially applied, reusable23Explain call, apply and bind.
All three set the value of this for a function. call(thisArg, a, b) runs the function immediately with arguments listed out. apply(thisArg, [a, b]) runs it immediately with an array of arguments. bind(thisArg) does not run it; it returns a new function with this permanently fixed.
function intro(city) { return this.name + " from " + city; }
const user = { name: "Dev" };
intro.call(user, "Rajkot"); // "Dev from Rajkot"
intro.apply(user, ["Rajkot"]); // "Dev from Rajkot"
const bound = intro.bind(user);
bound("Rajkot"); // "Dev from Rajkot"24How does the this keyword work?
- In a regular function call,
thisisundefinedin strict mode (the global object otherwise). - As a method (
obj.fn()),thisis the object before the dot. - With
new,thisis the newly created object. - With
call,applyorbind,thisis whatever you pass in. - In an arrow function,
thiscomes from the enclosing scope. - In a DOM event handler (regular function),
thisis the element that received the event.
Interview tip: Interviewers often show a method pulled off an object (const f = obj.method; f()) to see if you know this is lost.
25What is a pure function?
A pure function always returns the same output for the same input and has no side effects: it does not change external variables, the DOM or files. Pure functions are easier to test and are the basis of how reducers in React/Redux work.
26What is the difference between default, rest and spread parameters?
Default parameters give a fallback value (function greet(name = "friend")). The rest parameter collects extra arguments into an array (function sum(...nums)). Spread does the opposite and expands an array or object into individual items (Math.max(...nums)).
27What is the difference between debouncing and throttling?
Debounce waits until the user has stopped triggering an event for a set time, then runs once (search-as-you-type). Throttle runs at most once every set interval no matter how often the event fires (scroll or resize handlers).
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}28What is recursion? What is its drawback?
Recursion is a function calling itself until a base case stops it. It suits tree walking and divide-and-conquer problems. Each call adds a frame to the call stack, so very deep recursion throws "Maximum call stack size exceeded"; an iterative loop avoids that.
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1);
}
factorial(5); // 120Objects, arrays and ES6+ 15 questions
29What are the different ways to create an object?
- Object literal:
{ name: "Asha" } - Constructor function with
new Object.create(proto)to set the prototype directly- ES6
classwithnew - Factory function that returns an object
30What is the prototype chain?
Every object has an internal link to another object called its prototype. When you read a property, JavaScript looks on the object, then its prototype, then that object's prototype, and so on until it reaches null. This chain is how inheritance works, and it is why arrays can use map (it lives on Array.prototype).
31Are JavaScript classes real classes?
The class keyword is syntax on top of prototypal inheritance. Under the hood a class is still a constructor function and methods live on the prototype. Classes give a cleaner syntax for constructor, extends, super, static and private fields (#field).
32What is the difference between shallow copy and deep copy?
A shallow copy duplicates only the top level; nested objects are still shared by reference. A deep copy duplicates every level. { ...obj } and Object.assign are shallow. Use structuredClone(obj) for a deep copy (the older JSON.parse(JSON.stringify(obj)) trick loses dates, functions and undefined).
const a = { x: 1, nested: { y: 2 } };
const shallow = { ...a };
shallow.nested.y = 99;
console.log(a.nested.y); // 99 (shared)
const deep = structuredClone(a);
deep.nested.y = 5;
console.log(a.nested.y); // 99 (unchanged)33What is the difference between Object.freeze, Object.seal and const?
conststops reassignment of the variable, but the object can still change.Object.freezemakes an object read-only: no adding, deleting or changing properties (shallow only).Object.sealblocks adding and deleting properties but still lets you change existing values.
34What is destructuring?
Destructuring unpacks values from arrays or properties from objects into variables in one line.
const { name, city = "Rajkot" } = user; // object
const [first, , third] = ["a", "b", "c"]; // array, skipping one
const { address: { pin } } = user; // nested35What is the difference between the spread and rest operators?
Both use .... Rest gathers several values into one array or object (in function parameters and destructuring). Spread expands an iterable into separate values (in calls, array literals and object literals).
const nums = [1, 2, 3];
const more = [...nums, 4]; // spread
const { a, ...others } = { a: 1, b: 2, c: 3 }; // rest -> others = { b: 2, c: 3 }36What is the difference between map, filter, reduce and forEach?
forEachruns a function for each item and returns nothing.mapreturns a new array of the same length with each item transformed.filterreturns a new array with only the items for which the callback returned true.reducefolds the array down to a single value (a sum, an object, another array).
const prices = [100, 250, 80];
prices.map(p => p * 1.18); // [118, 295, 94.4]
prices.filter(p => p > 90); // [100, 250]
prices.reduce((sum, p) => sum + p, 0); // 43037What is the difference between slice and splice?
slice(start, end) returns a copy of part of an array and does not change the original. splice(start, deleteCount, ...items) removes and/or inserts items in place and mutates the original array. Newer, non-mutating options are toSpliced, toSorted and toReversed.
38How do you remove duplicates from an array?
const unique = [...new Set([1, 2, 2, 3, 3])]; // [1, 2, 3]A Set stores each value only once, and spreading it back gives an array.
39What is the difference between Map and a plain object? And Set vs array?
Mapaccepts any type as a key (objects, functions), keeps insertion order and has a.size; an object's keys are strings or symbols.Setstores unique values and has fast.has()lookups; an array allows duplicates and is index-based.WeakMap/WeakSethold their keys weakly, so entries can be garbage collected when nothing else references the key.
40What is the difference between for...in and for...of?
for...in loops over the enumerable property names (keys) of an object, including inherited ones. for...of loops over the values of an iterable such as an array, string, Map or Set.
for (const i in ["a", "b"]) console.log(i); // "0", "1"
for (const v of ["a", "b"]) console.log(v); // "a", "b"41What are optional chaining (?.) and nullish coalescing (??)?
Optional chaining stops and returns undefined instead of throwing when something in the chain is null or undefined. The ?? operator returns the right side only when the left is null or undefined, unlike || which also replaces 0 and "".
user?.address?.city; // undefined, no error
const limit = settings.limit ?? 10; // keeps 0 if limit is 042What are ES modules? How are they different from CommonJS?
ES modules use import/export, are loaded statically (so tools can tree-shake unused code) and work in browsers and modern Node.js. CommonJS uses require() and module.exports, loads synchronously and was the original Node.js format.
43What do JSON.stringify and JSON.parse do?
JSON.stringify(value) turns a JavaScript value into a JSON string (for sending to a server or saving to storage). JSON.parse(text) turns a JSON string back into a value. Functions, undefined and symbols are dropped by stringify, and dates become strings.
Asynchronous JavaScript 10 questions
Expect at least one event loop question in every JavaScript interview.
44What is the difference between synchronous and asynchronous code?
Synchronous code runs line by line and each line waits for the previous one. Asynchronous code starts a long task (a network request, a timer) and lets the rest of the program continue; the result is handled later through a callback, promise or await.
45How does the JavaScript event loop work?
JavaScript runs on a single thread with a call stack. Async work such as timers and network calls is handled by the browser (or Node), which puts the finished callbacks into queues. The event loop repeatedly checks: if the call stack is empty, first run all microtasks (promise callbacks, queueMicrotask), then take one task from the macrotask queue (setTimeout, DOM events), and repeat.
Interview tip: The sentence "microtasks run before the next macrotask" answers most event loop output questions.
46What is callback hell and how do you avoid it?
Callback hell is deeply nested callbacks that make code hard to read and handle errors in. You avoid it with promises, async/await, and by splitting logic into small named functions.
47What is a Promise and what are its states?
A Promise represents a value that will be available later. It is always in one of three states: pending, fulfilled (resolved with a value) or rejected (failed with a reason). Once settled it never changes. You consume it with .then(), .catch() and .finally().
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
wait(500).then(() => console.log("done"));48What is the difference between Promise.all, allSettled, race and any?
Promise.all: waits for all to succeed; rejects as soon as one rejects.Promise.allSettled: waits for all to finish and returns each result as fulfilled or rejected.Promise.race: settles as soon as the first promise settles, success or failure.Promise.any: fulfils with the first success; rejects only if all reject.
49What is async/await?
async/await is syntax that lets you write promise-based code in a synchronous-looking way. An async function always returns a promise, and await pauses that function (not the whole program) until the promise settles.
async function loadUser(id) {
const res = await fetch("/api/users/" + id);
return res.json();
}50How do you handle errors in async code?
Wrap await calls in try/catch, or add .catch() to a promise chain. An unhandled rejection can crash a Node process or show up as a console warning in the browser.
try {
const data = await loadUser(7);
} catch (err) {
console.error("Could not load user", err);
} finally {
hideSpinner();
}51Does fetch reject the promise on a 404 or 500 response?
No. fetch only rejects on network failure. A 404 or 500 still resolves, so you must check response.ok (or response.status) yourself and throw if needed. This is one of the most common beginner bugs.
const res = await fetch(url);
if (!res.ok) throw new Error("HTTP " + res.status);
const data = await res.json();52What is the difference between setTimeout and setInterval?
setTimeout(fn, ms) runs a function once after a delay. setInterval(fn, ms) runs it repeatedly until you call clearInterval. The delay is a minimum, not a guarantee, because the callback must wait for the call stack to be free.
53What are generators and when would you use them?
A generator (function*) can pause with yield and resume later, producing values one at a time. They are useful for lazy sequences, custom iterators and, historically, the basis on which async/await was built.
DOM and browser 7 questions
54What is the DOM?
The Document Object Model is the browser's tree representation of an HTML page. JavaScript uses it to read, change, add or remove elements and to react to events. It is not part of the JavaScript language itself; it is an API provided by the browser.
55What is the difference between getElementById, querySelector and querySelectorAll?
getElementById finds one element by its id and is the fastest. querySelector accepts any CSS selector and returns the first match. querySelectorAll returns a static NodeList of all matches.
56What are event bubbling and event capturing?
When an event happens on an element it travels in two phases: capturing (from the window down to the target) and then bubbling (from the target back up through its parents). Listeners run in the bubbling phase by default. event.stopPropagation() stops the event from travelling further.
57What is event delegation?
Instead of adding a listener to every child, you add one listener to a common parent and check event.target. It uses less memory and also works for elements added later.
document.querySelector("#list").addEventListener("click", (e) => {
if (e.target.matches("li")) {
console.log("clicked", e.target.textContent);
}
});58What is the difference between localStorage, sessionStorage and cookies?
- localStorage: about 5 MB, stays until cleared, same-origin only, never sent to the server automatically.
- sessionStorage: same API, but cleared when the tab closes.
- Cookies: about 4 KB each, can expire, and are sent with every request to that domain, so they suit sessions and authentication.
Never store passwords or sensitive tokens in localStorage; any script on the page can read it.
59What is the difference between defer and async on a script tag?
Both download the script without blocking HTML parsing. async runs the script as soon as it is downloaded, in any order. defer waits until the HTML is parsed and runs deferred scripts in the order they appear. Use defer for scripts that depend on the DOM or on each other.
60What is CORS?
Cross-Origin Resource Sharing is a browser security rule that blocks a page from reading responses from a different origin (protocol, domain or port) unless that server allows it with headers such as Access-Control-Allow-Origin. It is enforced by the browser, so the fix is on the server, not in your front-end code.
Coding questions 7 questions
Short exercises you can write on a whiteboard or in a shared editor in a few minutes.
61Reverse a string.
const reverse = (s) => [...s].reverse().join("");
reverse("codeksha"); // "ahskedoc"62Check whether a string is a palindrome.
function isPalindrome(str) {
const clean = str.toLowerCase().replace(/[^a-z0-9]/g, "");
return clean === [...clean].reverse().join("");
}
isPalindrome("A man, a plan, a canal: Panama"); // true63Write FizzBuzz.
for (let i = 1; i <= 15; i++) {
if (i % 15 === 0) console.log("FizzBuzz");
else if (i % 3 === 0) console.log("Fizz");
else if (i % 5 === 0) console.log("Buzz");
else console.log(i);
}64Flatten a nested array.
[1, [2, [3, [4]]]].flat(Infinity); // [1, 2, 3, 4]Without flat, use recursion with reduce and concat.
65Count how many times each word appears in a sentence.
const text = "to be or not to be";
const count = text.split(" ").reduce((acc, w) => {
acc[w] = (acc[w] || 0) + 1;
return acc;
}, {});
// { to: 2, be: 2, or: 1, not: 1 }66Find two numbers in an array that add up to a target (Two Sum).
function twoSum(nums, target) {
const seen = new Map(); // value -> index
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i];
if (seen.has(need)) return [seen.get(need), i];
seen.set(nums[i], i);
}
return [];
}
twoSum([2, 7, 11, 15], 9); // [0, 1]One pass with a Map is O(n) time, compared with O(n²) for two nested loops.
67Implement a simple sleep function with a promise.
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
(async () => { await sleep(1000); console.log("1s later"); })();Output-based questions 7 questions
Try to predict the output before you open the answer. This is the fastest way to find the gaps in your understanding.
68What is the output? (var in a loop)
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}Output: 3 3 3. var has one shared binding and the timeouts run after the loop ends. Change var to let and the output becomes 0 1 2.
69What is the output? (microtask vs macrotask)
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");Output: 1 4 3 2. Synchronous code first, then the promise (microtask), then the timeout (macrotask).
70What is the output? (floating point)
console.log(0.1 + 0.2 === 0.3);
console.log(0.1 + 0.2);Output: false and 0.30000000000000004. Numbers use binary floating point, so some decimals cannot be stored exactly. Compare with a tolerance (Math.abs(a - b) < Number.EPSILON) or work in whole units such as paise.
71What is the output? (coercion)
console.log([] + []);
console.log([] + {});
console.log("5" + 3, "5" - 3);
console.log(typeof NaN);Output: an empty string, [object Object], 53 2 and number.
72What is the output? (comparison chain)
console.log(1 < 2 < 3);
console.log(3 > 2 > 1);Output: true and false. 3 > 2 is true, which becomes 1, and 1 > 1 is false.
73What is the output? (hoisting)
console.log(typeof hello);
var hello = "hi";
function hello() {}Output: function. The function declaration is hoisted above the var, and the assignment "hi" has not run yet when typeof is evaluated.
74What is the output? (this in an object method)
const user = {
name: "Asha",
regular() { return this.name; },
arrow: () => typeof this,
};
const detached = user.regular;
console.log(user.regular(), detached());user.regular() returns "Asha". The detached call loses its object, so this.name is undefined (or a TypeError in strict mode). The arrow function does not get its own this either.
How to Prepare for a JavaScript Interview
- Learn the concept, then write it. After reading each answer, close the page and re-create the example from memory in the browser console.
- Explain out loud. Practise answering in two or three sentences, the way you would to an interviewer. If you cannot explain it simply, you do not know it yet.
- Build something real. Interviewers ask about your own projects. A to-do list with a fetch call and local storage covers closures, events, async code and the DOM in one go (see how to build a portfolio that gets you hired).
- Practise on a timer. Pick 5 questions at random, give yourself a minute each and answer without looking.
- Read your own code. Many questions start with "what is wrong with this snippet?", so get used to spotting
thisand scope bugs. - Move on to a framework. Most job descriptions pair JavaScript with React, Node.js or both. Our JavaScript course and Frontend Development course take you from this list to real projects.
Frequently Asked Questions
What are the most commonly asked JavaScript interview questions for freshers?
The most common ones are the difference between var, let and const, == vs ===, hoisting, closures, the this keyword, promises and async/await, the event loop and event delegation. All of them are covered above.
How many JavaScript questions should I prepare?
You do not need to memorise hundreds. If you can answer the questions in this guide with a short example each, you are ready for most fresher and junior interviews. Depth on closures, async code and the DOM is worth more than breadth.
Is JavaScript enough to get a developer job?
It is the essential skill, but most employers also expect HTML, CSS, Git and one framework such as React. For full stack roles add Node.js and a database. See our full stack developer roadmap for the complete path.
What is the best way to practise JavaScript coding questions?
Write small programs yourself instead of only reading solutions: string manipulation, array methods, a fetch call to a public API, and a small DOM project. Then explain your code out loud as if to an interviewer.
How long does it take to prepare for a JavaScript interview?
If you already know the basics, two to three weeks of daily practice (about an hour a day) is enough to cover this guide properly. If you are starting from zero, plan two to three months to learn the language first.
Ready to Go From Answers to Real Projects?
Codeksha's Full Stack Web Development course in Rajkot teaches JavaScript, React, Node.js and databases with live classes and real projects. Book a free demo class and see a session for yourself.
Book a Free Demo ClassGet Syllabus, Fees & a Free Demo
Tell us your number and a Codeksha counsellor will call you back about the Full Stack Web Development course in Rajkot.


