JavaScript

Top 50 JavaScript Interview Questions and Answers

JavaScript interviews tend to test the same handful of ideas in different clothes: how values behave, how functions remember their surroundings, how objects inherit, and how asynchronous code is scheduled. This guide covers 50 questions grouped by theme. Each answer is short enough to say out loud in an interview, with code where code makes the point faster than words.

Read the sections in order the first time. After that, use the headings to revise whichever area feels weakest, and try to explain each answer in your own words before reading ours.

Advertisements

Part 1: Core Language (Questions 1 to 12)

1. What is JavaScript and where does it run?

JavaScript is a high-level, dynamically typed, multi-paradigm language whose standard is called ECMAScript. It began in the browser, but today it also runs on servers (Node.js, Deno, Bun), on edge platforms, and inside desktop and mobile apps.

2. Is JavaScript compiled or interpreted?

Both ideas are partly true. Modern engines such as V8, SpiderMonkey and JavaScriptCore parse your code, run it quickly through an interpreter, and then compile frequently used functions to machine code while the program runs (just-in-time compilation). Calling JavaScript “just interpreted” is an oversimplification.

3. How is JavaScript different from Java?

They are unrelated languages that share part of a name for historical marketing reasons. Java is statically typed, class-based and compiled to bytecode for the JVM. JavaScript is dynamically typed, uses prototypes as its core inheritance model, and is executed by a JavaScript engine.

4. What are the data types in JavaScript?

There are seven primitive types: string, number, bigint, boolean, undefined, null and symbol. Everything else is an object, including arrays, functions, dates and maps. Primitives are immutable and compared by value, while objects are compared by reference.

5. Why does typeof null return “object”?

It is a bug from the first version of the language that was never fixed because too much existing code depends on it. To test for null, use value === null. Note that typeof a function returns “function”, even though functions are objects too.

6. What is the difference between null and undefined?

undefined means a value has not been assigned, such as a declared variable with no value or a missing property. null is a value you assign on purpose to say “nothing here”. They are loosely equal (null == undefined is true) but not strictly equal.

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

The == operator converts operands to a common type before comparing, while === compares type and value with no conversion.

0 == "0" // true
0 === "0" // false
null == undefined // true
null === undefined // false

Most teams default to === to avoid surprises. Object.is() is a third option that treats NaN as equal to itself and tells 0apart from -0.

Advertisements

8. How does type coercion work?

When operators receive values of different types, JavaScript converts them. The + operator prefers strings if either side is a string, while -, * and / convert to numbers.

"5" + 1 // "51"
"5" - 1 // 4
true + 1 // 2

Explicit conversion with Number(), String() and Boolean() makes your intent clear.

Advertisements

9. What are truthy and falsy values?

There are exactly eight falsy values: false, 0, -0, 0n, "", null, undefined and NaN. Every other value is truthy, including "0", "false", [] and {}. This matters in conditions such as if (items.length).

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

var is function-scoped, can be redeclared and is hoisted with the value undefined. let and const are block-scoped and cannot be used before their declaration line. const forbids reassigning the variable but does not make an object or array immutable, since its contents can still change.

11. What is hoisting and the temporal dead zone?

Before running a scope, the engine registers its declarations. Function declarations are available in full, var variables start as undefined, and let and const exist but cannot be touched until their line runs. Accessing them early throws a ReferenceError, and that gap is called the temporal dead zone.

12. Why is NaN not equal to itself, and how do you test for it?

Per the numeric standard, NaN means “not a valid number” and is defined as unequal to everything, including itself. Use Number.isNaN(x), which does not convert its argument. The older global isNaN("hello") converts first and returns true for strings, which is usually not what you want.

Advertisements

Part 2: Functions and Scope (Questions 13 to 24)

13. What are the different ways to define a function?

A function declaration (function add() {}) is hoisted completely. A function expression (const add = function () {}) is only available after that line runs. An arrow function (const add = () => {}) is a shorter expression form with different this behaviour. Methods can also be defined inside objects and classes.

14. How do arrow functions differ from regular functions?

Arrow functions have no this of their own and use the one from the surrounding code. They also have no argumentsobject, cannot be used with new, and have no prototype property. That makes them ideal for callbacks and poor choices for object methods that need their own this.

15. How is the value of this determined?

It depends on how a function is called, not where it is written. In order of priority: with new, this is the new object; with call, apply or bind, it is the object you pass; when called as obj.method(), it is obj; otherwise it is undefined in strict mode or the global object in sloppy mode. Arrow functions skip all of this and inherit this lexically.

16. What do call, apply and bind do?

All three set this explicitly. call(thisArg, a, b) runs the function immediately with separate arguments. apply(thisArg, [a, b]) runs immediately with an array of arguments. bind(thisArg, a) does not run anything and returns a new function with this (and optionally some arguments) fixed in place.

Advertisements

17. What is a closure?

A closure is a function that keeps access to the variables of the scope where it was created, even after that scope has finished running.

function makeCounter() {
let count = 0;
return () => ++count;
}
const next = makeCounter();
next(); // 1
next(); // 2

The count variable cannot be reached from outside, which makes closures a natural way to create private state.

18. Why does a var loop with setTimeout print the same number?

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

There is only one i shared by all callbacks, and it equals 3 when they finally run. Declaring it with let gives each iteration its own binding and prints 0 1 2.

Advertisements

19. What are lexical scope and the scope chain?

Lexical scope means a function can see the variables of the places where it is written. When you use a name, the engine looks in the current scope, then the enclosing one, and so on up to the global scope. The first match wins, and that ordered lookup is the scope chain.

20. What is an IIFE and is it still useful?

An immediately invoked function expression is a function that runs as soon as it is defined: (() => { /* code */ })();. It was the standard way to avoid polluting the global scope. With ES modules and block scoping it is needed less often, but it still appears in older code and in one-off async setups.

21. What is a higher-order function?

A function that takes another function as an argument, returns a function, or both. map, filter, reduce, setTimeout and event listeners all rely on this idea because JavaScript treats functions as ordinary values.

22. What is currying?

Currying turns a function that takes several arguments into a chain of functions that each take one.

const add = a => b => a + b;
const addFive = add(5);
addFive(3); // 8

It is handy for building specialised functions from general ones. Partial application is the related idea of fixing some arguments up front without requiring one-at-a-time calls.

23. What are default, rest and spread parameters?

Default parameters supply a value when an argument is undefined: function greet(name = "guest"). Rest collects extra arguments into a real array: function sum(...nums). Spread expands an iterable into separate elements: Math.max(...numbers) or [...a, ...b]. The same ... syntax does opposite jobs depending on where it appears.

24. What is a pure function?

A pure function always returns the same output for the same input and has no side effects, such as changing outside variables, writing to the DOM or making network calls. Pure functions are easier to test, cache and reason about, which is why state-management libraries encourage them.

Advertisements

Part 3: Objects, Prototypes and Classes (Questions 25 to 32)

25. What are the ways to create an object?

The most common is an object literal: { name: "Asha" }. You can also use a constructor function with new, Object.create(proto) to choose the prototype directly, or a class. Literals are best for plain data, while classes suit objects that share behaviour.

26. What does the new keyword do?

It creates an empty object, links its prototype to the constructor’s prototype property, calls the constructor with thispointing at that object, and returns the object (unless the constructor returns a different object). Forgetting new on a constructor function is a classic bug.

27. What is the prototype chain?

Every object has an internal link to another object called its prototype. When you read a property that is missing, the engine follows the link upward until it finds it or reaches null. This is how arrays get map and plain objects get toStringwithout each instance carrying a copy.

Advertisements

28. Are JavaScript classes real classes?

They are cleaner syntax over the prototype system, not a separate model. A class gives you constructor, methods, extends, static members, getters and setters, and private fields written with a hash sign (#balance) that cannot be accessed from outside the class.

29. What is the difference between shallow and deep copy?

A shallow copy ({ ...obj }, Object.assign, arr.slice()) duplicates only the top level, so nested objects are still shared. A deep copy duplicates everything. The built-in structuredClone(obj) handles nested data, dates, maps, sets and circular references. JSON.parse(JSON.stringify(obj)) is a common shortcut, but it drops functions and undefinedand turns dates into strings.

30. What is the difference between Object.freeze, seal and preventExtensions?

preventExtensions stops new properties from being added. seal does that and also stops properties being removed, but values can still change. freeze locks everything, so values cannot change either. All three are shallow, meaning nested objects stay editable unless you freeze them too.

31. What do optional chaining and nullish coalescing do?

user?.address?.city returns undefined instead of throwing if something in the chain is null or undefined. The ??operator supplies a fallback only for null or undefined, unlike ||, which also replaces 0, "" and false.

const qty = input.quantity ?? 1; // keeps 0 if the user typed 0
Advertisements

32. How are Map, Set and WeakMap different from objects and arrays?

A Map stores key-value pairs with keys of any type and remembers insertion order. A Set stores unique values. A WeakMapaccepts only objects as keys and holds them weakly, so they can be garbage collected when nothing else uses them; it cannot be iterated. Use Map when keys are not simple strings or when you add and remove entries often.

Part 4: Asynchronous JavaScript (Questions 33 to 41)

33. How can JavaScript be single-threaded and still handle async work?

Your code runs on one thread, one task at a time. Slow operations such as timers and network requests are handed to the environment (the browser or Node.js). When they finish, their callbacks are placed in queues, and the event loop moves them onto the call stack whenever it is empty.

34. What is the difference between the microtask and macrotask queues?

Promise callbacks and queueMicrotask go to the microtask queue, while timers, I/O and UI events go to the macrotask queue. After each task, the engine empties the whole microtask queue before the next macrotask.

console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
// A D C B
Advertisements

35. What is callback hell and how do you avoid it?

It is deeply nested callbacks that make the order of operations and error handling hard to follow. Promises and async/await flatten the structure, and breaking work into small named functions helps further.

36. What is a Promise?

An object representing a result that is not available yet. It is pending at first and then either fulfilled with a value or rejected with a reason. You attach handlers with then, catch and finally, and each of those returns a new promise so calls can be chained.

37. How does async/await work and how do you handle errors?

An async function always returns a promise, and await pauses that function until a promise settles while the rest of the program keeps running. Wrap awaited calls in try/catch to handle rejections.

async function load(id) {
try {
const res = await fetch(`/api/items/${id}`);
return await res.json();
} catch (err) {
console.error("Load failed", err);
}
}
Advertisements

38. What are Promise.all, allSettled, race and any?

all resolves when every promise succeeds and rejects as soon as one fails. allSettled waits for all and reports each outcome, never rejecting. race settles with whichever promise settles first. any resolves with the first success and rejects only if all fail, using an AggregateError.

39. How do you run async tasks in parallel instead of one by one?

Awaiting inside a loop runs the tasks sequentially. To run them together, start all the promises first and wait for them as a group.

// sequential: slow
for (const id of ids) await getItem(id);
// parallel: fast
await Promise.all(ids.map(getItem));

Use the sequential form only when each step depends on the previous one or when you must limit load on a server.

40. What are debouncing and throttling?

Debouncing waits until the user stops triggering an event for a set time before running the function, which suits search boxes. Throttling runs the function at most once per interval no matter how often the event fires, which suits scroll and resize handlers.

41. Why does fetch not reject on a 404 or 500 response?

fetch only rejects when the request itself fails, for example a network error. An HTTP error status still counts as a completed response, so check response.ok (or response.status) and throw your own error if it is false.

Advertisements

Part 5: Arrays, Modules, Browser and Modern Features (Questions 42 to 50)

42. How do map, forEach, filter and reduce differ?

forEach runs a function for each item and returns nothing. map returns a new array of the same length with transformed items. filter returns a new array with only items that pass a test. reduce folds the array into a single value, such as a sum or an object. Only forEach is meant for side effects.

43. Which array methods change the original array?

push, pop, shift, unshift, splice, sort, reverse and fill all mutate. Newer non-mutating counterparts return a copy: toSorted, toReversed, toSpliced and with. Preferring the copying versions avoids bugs in code that shares arrays, such as React state.

44. What is the difference between ES modules and CommonJS?

ES modules use import and export, are statically analysable (which helps tree-shaking), run in strict mode and support top-level await. CommonJS uses require and module.exports, loads synchronously and is the older Node.js style. Modern Node.js supports both, with ES modules enabled through the .mjs extension or "type": "module" in package.json.

45. What are event bubbling, capturing and delegation?

When an event fires on an element, it first travels down from the document to the target (capturing) and then back up (bubbling). Listeners run during bubbling by default. Delegation uses this by placing one listener on a parent and checking event.target, which is efficient for long lists and for items added later.

46. How do cookies, localStorage and sessionStorage differ?

Cookies are small (about 4 KB), can expire, are sent to the server with every request and can be marked HttpOnly so scripts cannot read them. localStorage holds a few megabytes per origin and persists until cleared. sessionStorage is similar but lasts only for one tab session. Both storage types are readable by any script on the page, so avoid keeping sensitive tokens in them.

Advertisements

47. How does garbage collection work and what causes memory leaks?

Engines free memory that can no longer be reached from the roots of the program (a mark-and-sweep approach). Leaks happen when something unwanted stays reachable: forgotten timers and event listeners, accidental globals, detached DOM nodes still referenced in variables, and closures holding large data.

48. What does strict mode change?

Adding "use strict" (or using modules and classes, which are strict automatically) turns silent mistakes into errors. Assigning to an undeclared variable throws, duplicate parameter names are not allowed, and this inside a plain function call is undefined instead of the global object.

49. How do you prevent cross-site scripting (XSS) in JavaScript?

Never insert untrusted text as HTML. Use textContent instead of innerHTML, escape or sanitise data before output (a library such as DOMPurify helps when HTML must be allowed), set a Content Security Policy, and keep session cookies HttpOnly so stolen scripts cannot read them.

50. What are iterators and generators?

An iterator is an object with a next() method that returns { value, done }, and anything iterable (arrays, strings, maps, sets) can be used with for...of and spread. A generator function (function*) makes writing iterators easy by pausing at each yield and resuming later.

function* range(start, end) {
for (let i = start; i < end; i++) yield i;
}
[...range(1, 4)]; // [1, 2, 3]
Advertisements

How to Prepare With This List

A simple routine works better than reading everything once. Pick ten questions a day, answer each aloud without looking, and then compare with the text. Mark the ones you stumble on and retry them the next day. For the code questions, type the examples into your browser console and change them to see what breaks, because interviewers often follow up with “what if we change this line?”.

Finally, be honest in interviews. If you do not know an answer, say what you do know, reason through it step by step, and mention how you would check the documentation. Clear thinking out loud usually counts for more than a memorised definition.

Which topic would you like a deeper, code-heavy guide on next: closures, the event loop or promises? Tell us in the comments.

Advertisements
Unknown's avatar

Shaky Byte

Your Saviour on your Coding Days

Leave a Reply