Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Interview Questions»100 JavaScript Interview Questions and Answers (2026) + Free PDF
    Interview Questions

    100 JavaScript Interview Questions and Answers (2026) + Free PDF

    Anirudh KhuranaBy Anirudh Khurana2 December 2026No Comments124 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    100 JavaScript interview questions by Code and Debug, showing an event loop snippet and its output
    Share
    Facebook Twitter LinkedIn Pinterest Email

    JavaScript runs every web page, most front-end frameworks and a large share of back ends through Node.js, so JavaScript interview questions come up for front-end, full-stack and Node.js roles alike. Freshers get asked about var vs let, == vs ===, hoisting and closures. Experienced developers get the event loop, promises, prototypes, performance and “write debounce or Promise.all from scratch” questions.

    This page has the 100 JavaScript interview questions asked most often, with clear answers, grouped for freshers, intermediate and experienced candidates. 84 answers include code that you can run in your browser with one click, edit and run again, and the output shown under each example comes from that same runner. You also get an event loop visualiser, a “guess the output” game and 20 coding questions that test your code automatically. Prefer to study offline? Download all 100 questions as a free PDF.

    Free PDF
    All 100 JavaScript interview questions with answers
    69 pages, with every code example and its output. No sign-up needed.
    Download PDF

    What you will find on this page

    • 100 questions with answers in three levels: 40 for freshers, 35 intermediate, 25 for experienced candidates.
    • Core JavaScript, ES6+, async code and the DOM: data types, scope, closures, this, prototypes and classes, promises, async/await and the event loop, events and delegation, browser storage, security and performance.
    • 84 runnable examples: press “Run this code” under an example, change it and run it again.
    • Interactive tools: an online JavaScript editor, an event loop visualiser and a “guess the output” game.
    • 20 JavaScript coding questions (debounce, flatten, curry, Promise.all and more) that check your answer automatically.
    • Study tools: filters by level and topic, search, and a “Done” button on every question that remembers your progress.
    • A free 69-page PDF of everything.

    Also useful (each opens our own guide):

    DSA interview cheat sheetFor the coding round that usually follows. OOPs interview questionsClasses, inheritance and polymorphism in general. Computer networks interview questionsHTTP, DNS and TCP, often asked with CORS and caching.
    Study tools

    Study these 100 questions your way

    Filter the JavaScript interview questions by level or topic, or search them. Press “Mark as done” under each question you have finished; your progress is saved in this browser.

    Showing
    100 / 100
    Done
    0 / 100
    Download PDF (69 pages)

    No questions match these filters. Try another topic or clear the search.

    How to prepare for a JavaScript interview

    • Know the classic comparisons: var vs let vs const, == vs ===, null vs undefined, arrow vs regular functions, map vs forEach, call vs apply vs bind, microtasks vs macrotasks, localStorage vs sessionStorage vs cookies.
    • Be able to explain the hard concepts out loud: closures, this, the prototype chain, hoisting and the event loop. Interviewers often give a short snippet and ask what it prints; the game below trains exactly that.
    • Write the common utilities by hand: debounce, throttle, memoize, curry, flatten, deep clone and Promise.all. Many front-end rounds ask for one of these on a shared editor.
    • For 2+ years of experience, revise performance (reflow, Core Web Vitals, code splitting), security (XSS, CSRF, CORS), memory leaks, and the framework you use, usually React.
    • Expect a DSA round as well. Practise arrays, strings, hashing and two pointers in JavaScript; our DSA cheat sheet lists the patterns.

    Practise JavaScript in your browser

    Reading about JavaScript only gets you so far; running code is what makes the rules stick. These three tools run right on this page, with nothing to install.

    Online JavaScript editor

    Type any JavaScript below and press Run (or Ctrl + Enter). The code runs in a separate background thread in your browser, so an endless loop is stopped after a few seconds instead of freezing the page. console.log output appears below, and objects and arrays are printed the way Node.js prints them.

    JavaScript editor

    Run JavaScript online

    Runs in your browser. Nothing is sent to a server.

    Ctrl + Enter runs the code
    Try:

    Event loop visualiser

    “What is the output, and why?” with a mix of setTimeout, promises and async/await is one of the most common JavaScript interview questions. Step through three short programs and watch the call stack, the microtask queue and the macrotask queue change at every step.

    Visualiser

    The event loop, one step at a time

    Code
    Console
    Call stack
    Web APIs (browser)
    Microtask queue
    Macrotask queue
    Running nowMicrotasks: promise callbacks, awaitMacrotasks: timers, events, I/O

    Guess the output: 15 tricky JavaScript snippets

    Interviewers love short snippets with a surprising result: type coercion, hoisting, this and the event loop. Pick an answer for each one and read why. Every answer was checked by running the code.

    Game

    What does this code print?

    15 snippets, about five minutes.

    JavaScript interview questions for freshers

    These 40 basic JavaScript interview questions cover what campus placements and first front-end interviews ask: data types, var, let and const, hoisting, equality, functions and closures, arrays and objects, the basics of async code and the DOM.

    Q1FreshersBasics

    1. What is JavaScript and where is it used?

    JavaScript is a high-level, dynamically typed programming language that every web browser can run. It started in 1995 as a way to make web pages interactive, and today it runs almost everywhere: in browsers, on servers with Node.js, Deno and Bun, in mobile apps with React Native, and in desktop apps with Electron (VS Code and Slack are built this way).

    • Interpreted and JIT compiled: engines like V8 (Chrome, Node.js) compile hot code to machine code while the program runs.
    • Dynamically typed: a variable can hold a number now and a string later.
    • Single-threaded with an event loop: it handles many tasks at once without blocking, using callbacks, promises and async/await.
    • Multi-paradigm: you can write procedural, object-oriented (prototypes and classes) and functional code.
    • First-class functions: functions are values that you can store, pass and return.

    The official specification is called ECMAScript. A new edition comes out every year, so you will hear names like ES6 (2015, the big update with let, const, classes and arrow functions) and ES2024.

    Q2FreshersBasics

    2. What is the difference between Java and JavaScript?

    JavaJavaScript
    TypingStatic: types are checked at compile timeDynamic: types are checked at run time
    Runs onThe JVM, after compiling to bytecodeBrowsers and JavaScript runtimes such as Node.js
    ObjectsClass-basedPrototype-based; the class keyword is syntax on top of prototypes
    ConcurrencyMultiple threadsOne main thread plus an event loop (and workers)
    Main useBack ends, Android, enterprise systemsWeb front ends, Node.js back ends, full-stack apps

    The similar name was a marketing decision in 1995, when Java was popular. Apart from some C-like syntax, the two languages have little in common. Our Java interview questions cover Java itself.

    Q3FreshersBasics

    3. What are the data types in JavaScript?

    JavaScript has seven primitive types and one non-primitive type, Object.

    TypeExampletypeof result
    String"hello""string"
    Number42, 3.14, NaN"number"
    BigInt9007199254740993n"bigint"
    Booleantrue"boolean"
    Undefinedundefined"undefined"
    Nullnull"object" (a historical bug)
    SymbolSymbol("id")"symbol"
    Object{}, [], functions, dates"object" or "function"
    console.log(typeof "hi", typeof 42, typeof 10n);
    console.log(typeof true, typeof undefined, typeof Symbol());
    console.log(typeof null, typeof [], typeof {}, typeof function () {});

    Output:

    string number bigint
    boolean undefined symbol
    object object object function

    Primitives are immutable and are copied by value. Objects are copied by reference, so two variables can point to the same object. Arrays and functions are objects too; use Array.isArray() to test for an array.

    Q4FreshersBasics

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

    varletconst
    ScopeFunctionBlockBlock
    HoistedYes, set to undefinedYes, but not initialised (TDZ)Yes, but not initialised (TDZ)
    Re-declare in same scopeAllowedErrorError
    Re-assignAllowedAllowedError
    Becomes a property of window at top levelYesNoNo
    if (true) {
      var a = 1;
      let b = 2;
      const c = 3;
    }
    console.log(a);         // var ignores the block
    console.log(typeof b);  // b does not exist out here
    
    const user = { name: "Riya" };
    user.name = "Aman";     // allowed: the object can change
    console.log(user.name);
    try {
      user = {};            // not allowed: the binding is constant
    } catch (e) {
      console.log(e.name + ": " + e.message);
    }

    Output:

    1
    undefined
    Aman
    TypeError: Assignment to constant variable.

    Use const by default, let when you need to reassign, and avoid var in new code. const makes the variable constant, not the object it points to. To lock an object, use Object.freeze() (question 45).

    Q5FreshersBasics

    5. What is hoisting?

    Before running a scope, the JavaScript engine registers all its declarations. This is called hoisting. Function declarations are hoisted with their body, so you can call them before the line where they are written. var variables are hoisted and set to undefined. let, const and class are hoisted too, but they stay uninitialised until their line runs.

    console.log(greet("Riya"));   // works: the whole function is hoisted
    console.log(count);           // undefined, not an error
    var count = 5;
    
    function greet(name) {
      return "Hello, " + name;
    }
    
    try {
      console.log(total);
      let total = 10;
    } catch (e) {
      console.log(e.name + ": " + e.message);
    }

    Output:

    Hello, Riya
    undefined
    ReferenceError: Cannot access 'total' before initialization

    The time between the start of the scope and the let line is called the temporal dead zone (TDZ). Touching the variable in the TDZ throws a ReferenceError, which catches bugs that var would hide. Function expressions and arrow functions stored in variables follow the variable’s rules, so they cannot be called early.

    Q6FreshersBasics

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

    === (strict equality) compares value and type and never converts anything. == (loose equality) converts the values to a common type first, following rules that are easy to forget.

    console.log(5 == "5", 5 === "5");
    console.log(0 == false, 0 === false);
    console.log(null == undefined, null === undefined);
    console.log("" == 0, [] == 0, [1] == 1);
    console.log(NaN == NaN, NaN === NaN);

    Output:

    true false
    true false
    true false
    true true true
    false false

    Use === and !== everywhere. The one common exception is x == null, which is true for both null and undefined and nothing else. NaN is not equal to anything, even itself; use Number.isNaN() or Object.is().

    Q7FreshersBasics

    7. What is the difference between null and undefined?

    undefinednull
    MeaningA value was never assignedDeliberately “no value”
    Who sets itUsually the engineUsually the programmer
    typeof"undefined""object"
    In JSONThe key is droppedKept as null
    In arithmeticNaN0
    let a;
    const user = { name: "Riya" };
    function f() {}
    
    console.log(a, user.age, f());   // all undefined
    console.log(JSON.stringify({ x: undefined, y: null }));
    console.log(undefined + 1, null + 1);

    Output:

    undefined undefined undefined
    {"y":null}
    NaN 1

    You get undefined from an uninitialised variable, a missing property, a missing argument and a function with no return. Set a value to null yourself when you want to say “empty on purpose”, for example after clearing a selection.

    Q8FreshersBasics

    8. What are truthy and falsy values?

    When a value is used where a boolean is expected (an if, &&, ||, !), JavaScript converts it to true or false. Only eight values are falsy: false, 0, -0, 0n, "", null, undefined and NaN. Everything else is truthy, including "0", "false", [] and {}.

    const values = [0, "", "0", " ", [], {}, null, "false", -1];
    for (const v of values) {
      console.log(JSON.stringify(v), "->", Boolean(v));
    }
    console.log("NaN ->", Boolean(NaN), "| undefined ->", Boolean(undefined));

    Output:

    0 -> false
    "" -> false
    "0" -> true
    " " -> true
    [] -> true
    {} -> true
    null -> false
    "false" -> true
    -1 -> true
    NaN -> false | undefined -> false

    A common bug: if (items.length) is fine, but if (count) treats a real value of 0 as “missing”. When 0 or an empty string is valid, compare with null explicitly or use ?? (question 61).

    Q9FreshersBasics

    9. What is type coercion in JavaScript?

    Type coercion is the automatic conversion of a value from one type to another. The + operator prefers strings: if either side is a string, it joins them. The other arithmetic operators (-, *, /) convert both sides to numbers.

    console.log("5" + 3);     // string wins with +
    console.log("5" - 3);     // - converts to numbers
    console.log("5" * "2");
    console.log(true + 1);
    console.log([] + []);     // both become ""
    console.log([] + {});
    console.log(1 + 2 + "3", "1" + 2 + 3);

    Output:

    53
    2
    10
    2
    
    [object Object]
    33 123

    To convert on purpose (explicit conversion), use Number("42"), String(42), Boolean(x) or parseInt("42px", 10). Explicit conversion makes the code easier to read and avoids surprises like "1" + 2 + 3 giving “123”.

    Q10FreshersBasics

    10. What are template literals?

    Template literals are strings written with backticks. They support interpolation with ${expression} and can span several lines without \n.

    const name = "Riya", marks = 92;
    const msg = `Hi ${name}, you scored ${marks}%.
    Result: ${marks >= 40 ? "Pass" : "Fail"}`;
    console.log(msg);

    Output:

    Hi Riya, you scored 92%.
    Result: Pass

    Any expression works inside ${}, including function calls and ternaries. A function placed before the backtick turns it into a tagged template, which libraries use for safe HTML, SQL or CSS (question 94).

    Q11FreshersFunctions

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

    // 1. Function declaration (hoisted)
    function add(a, b) { return a + b; }
    
    // 2. Function expression
    const sub = function (a, b) { return a - b; };
    
    // 3. Arrow function
    const mul = (a, b) => a * b;
    
    // 4. Method in an object
    const calc = { div(a, b) { return a / b; } };
    
    console.log(add(6, 3), sub(6, 3), mul(6, 3), calc.div(6, 3));

    Output:

    9 3 18 2

    A declaration is hoisted with its body. An expression or arrow function is just a value stored in a variable, so it exists only after that line runs. There is also the Function constructor, which builds a function from a string; avoid it for the same reasons as eval.

    Q12FreshersFunctions

    12. What is the difference between arrow functions and regular functions?

    Regular functionArrow function
    thisSet by how the function is calledTaken from the surrounding scope
    argumentsAvailableNot available; use …rest
    Can be used with newYesNo
    Hoisted (as a declaration)YesNo
    Short syntaxNoYes, with an implicit return
    "use strict";
    const team = {
      name: "Code and Debug",
      members: ["Riya", "Aman"],
      showArrow() {
        this.members.forEach(m => console.log(m + " is in " + this.name));
      },
      showRegular() {
        this.members.forEach(function (m) {
          console.log(m + " is in " + (this && this.name));
        });
      }
    };
    team.showArrow();
    team.showRegular();

    Output:

    Riya is in Code and Debug
    Aman is in Code and Debug
    Riya is in undefined
    Aman is in undefined

    The arrow callback sees the this of showArrow, which is team. The regular callback is called by forEach as a plain function, so its this is undefined in strict mode (or the global object otherwise). So arrows are the usual choice for callbacks, and regular functions or method shorthand for object methods.

    Q13FreshersFunctions

    13. What are default parameters, rest parameters and the spread operator?

    function greet(name = "Guest", greeting = "Hello") {
      return `${greeting}, ${name}!`;
    }
    console.log(greet(), greet("Riya"));
    
    function sum(...nums) {          // rest: collects arguments into an array
      return nums.reduce((a, b) => a + b, 0);
    }
    console.log(sum(1, 2, 3, 4));
    
    const a = [1, 2], b = [3, 4];
    console.log([...a, ...b]);        // spread: expands an array
    console.log(Math.max(...b));
    const base = { theme: "dark", size: 14 };
    console.log({ ...base, size: 16 });

    Output:

    Hello, Guest! Hello, Riya!
    10
    [ 1, 2, 3, 4 ]
    4
    { theme: 'dark', size: 16 }

    Rest and spread use the same ... syntax. Rest gathers many values into one array (in a parameter list or destructuring). Spread does the opposite and expands an array or object into separate values. A default value is used only when the argument is undefined, not when it is null.

    Q14FreshersFunctions

    14. What is a callback function?

    A callback is a function passed to another function, which calls it later. Array methods use callbacks synchronously; timers, events and older Node.js APIs use them asynchronously.

    function processOrder(id, onDone) {
      console.log("Processing order " + id);
      setTimeout(() => onDone("Order " + id + " shipped"), 100);
    }
    
    processOrder(42, message => console.log(message));
    console.log("This line runs before the callback");

    Output:

    Processing order 42
    This line runs before the callback
    Order 42 shipped

    Deeply nested callbacks become hard to read and to handle errors in, which is known as “callback hell” (question 51). Promises and async/await were added to solve that.

    Q15FreshersFunctions

    15. What are higher-order functions?

    A higher-order function takes a function as an argument, returns a function, or both. They are possible because functions are first-class values in JavaScript. map, filter, reduce, setTimeout and addEventListener are all higher-order functions.

    function multiplier(factor) {        // returns a function
      return n => n * factor;
    }
    const double = multiplier(2), triple = multiplier(3);
    
    function applyTwice(fn, x) {         // takes a function
      return fn(fn(x));
    }
    console.log(double(5), triple(5), applyTwice(double, 5));

    Output:

    10 15 20
    Q16FreshersFunctions

    16. What is scope in JavaScript?

    Scope decides where a variable can be used. JavaScript has global scope, function scope, block scope (for let and const inside { }) and module scope. Scopes nest: code can read variables from its own scope and every scope around it, but not from inner scopes. This lookup chain is the scope chain, and it is fixed by where the code is written (lexical scope), not where it is called from.

    const app = "global";
    function outer() {
      const x = "outer";
      function inner() {
        const y = "inner";
        console.log(app, x, y);   // inner can see all three
      }
      inner();
      console.log(typeof y);      // outer cannot see y
    }
    outer();

    Output:

    global outer inner
    undefined
    Q17FreshersFunctions

    17. What is a closure? Give an example.

    A closure is a function together with the variables from the scope where it was created. The function keeps access to those variables even after the outer function has returned. Closures are how JavaScript gives you private state.

    function makeCounter() {
      let count = 0;                // private: nothing outside can touch it
      return {
        increment: () => ++count,
        get: () => count
      };
    }
    
    const c1 = makeCounter();
    const c2 = makeCounter();
    c1.increment(); c1.increment();
    c2.increment();
    console.log(c1.get(), c2.get(), c1.count);

    Output:

    2 1 undefined

    Each call to makeCounter creates a new count, so c1 and c2 do not share state, and there is no count property to read from outside. Closures are also behind debounce, memoization, once(), module patterns and React hooks. The classic follow-up is the loop with var and setTimeout (question 52).

    Q18FreshersFunctions

    18. What is an IIFE?

    An IIFE (Immediately Invoked Function Expression) is a function that runs as soon as it is defined. Before ES modules and let, it was the standard way to create a private scope so that variables did not leak into the global scope.

    const counter = (function () {
      let value = 0;
      return { next: () => ++value };
    })();
    
    console.log(counter.next(), counter.next());
    console.log(typeof value);   // value stayed private

    Output:

    1 2
    undefined

    The brackets around the function turn it into an expression, and the () at the end calls it. Today modules and block scope cover most uses, but you still see IIFEs in older code and in an async form, (async () => { ... })(), for using await at the top level of a script.

    Q19FreshersObjects and arrays

    19. What are the different ways to create an object?

    // 1. Object literal (most common)
    const a = { name: "Riya" };
    
    // 2. Constructor function with new
    function Person(name) { this.name = name; }
    const b = new Person("Aman");
    
    // 3. ES6 class
    class Student { constructor(name) { this.name = name; } }
    const c = new Student("Neha");
    
    // 4. Object.create with a chosen prototype
    const proto = { hello() { return "Hi " + this.name; } };
    const d = Object.create(proto);
    d.name = "Karan";
    
    console.log(a.name, b.name, c.name, d.hello());
    console.log(b instanceof Person, c instanceof Student);

    Output:

    Riya Aman Neha Hi Karan
    true true

    You can also use new Object() (rarely needed) and Object.fromEntries() to build an object from key-value pairs. Object.create(null) makes an object with no prototype at all, which is a safe dictionary with no inherited keys such as toString.

    Q20FreshersObjects and arrays

    20. What is destructuring?

    Destructuring unpacks values from arrays or properties from objects into separate variables in one statement.

    const user = { name: "Riya", age: 22, city: "Surat" };
    const { name, age: years, country = "India" } = user;   // rename and default
    console.log(name, years, country);
    
    const [first, , third, ...rest] = [10, 20, 30, 40, 50];
    console.log(first, third, rest);
    
    let x = 1, y = 2;
    [x, y] = [y, x];                     // swap without a temp variable
    console.log(x, y);
    
    function show({ name, city }) {      // destructure a parameter
      return `${name} from ${city}`;
    }
    console.log(show(user));

    Output:

    Riya 22 India
    10 30 [ 40, 50 ]
    2 1
    Riya from Surat

    Nested destructuring also works, for example const { address: { pin } } = user. Destructuring a property of undefined throws a TypeError, so give a default such as = {} when the object may be missing.

    Q21FreshersObjects and arrays

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

    All three loop over an array without changing it. map transforms every element and returns a new array of the same length. filter keeps the elements for which the callback returns true. reduce combines all elements into one value, such as a sum, an object or a grouped result.

    const orders = [
      { item: "Book", price: 300, qty: 2 },
      { item: "Pen", price: 20, qty: 10 },
      { item: "Bag", price: 900, qty: 1 }
    ];
    const totals = orders.map(o => o.price * o.qty);
    const big = orders.filter(o => o.price * o.qty >= 500).map(o => o.item);
    const grand = orders.reduce((sum, o) => sum + o.price * o.qty, 0);
    console.log(totals);
    console.log(big);
    console.log(grand);

    Output:

    [ 600, 200, 900 ]
    [ 'Book', 'Bag' ]
    1700

    Always pass the initial value to reduce (the 0 above). Without it, reduce uses the first element as the start value and throws a TypeError on an empty array.

    Q22FreshersObjects and arrays

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

    forEach()map()
    ReturnsundefinedA new array
    PurposeSide effects: logging, updating the DOM, pushing to another arrayTransforming data
    ChainableNoYes, e.g. .map().filter()
    Can you break out early?No (use for…of, some() or find())No
    const nums = [1, 2, 3];
    const a = nums.forEach(n => n * 2);
    const b = nums.map(n => n * 2);
    console.log(a, b, nums);

    Output:

    undefined [ 2, 4, 6 ] [ 1, 2, 3 ]

    Neither method waits for async callbacks. arr.forEach(async x => await save(x)) starts all saves and moves on immediately. Use for...of with await to go one by one, or Promise.all(arr.map(...)) to run them in parallel.

    Q23FreshersObjects and arrays

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

    const a = ["a", "b", "c", "d", "e"];
    console.log(a.slice(1, 3));      // copy of index 1 and 2
    console.log(a.slice(-2));        // last two
    console.log(a);                  // unchanged
    
    const b = ["a", "b", "c", "d", "e"];
    const removed = b.splice(1, 2, "X", "Y");  // at index 1: remove 2, insert X, Y
    console.log(removed);
    console.log(b);                  // changed in place

    Output:

    [ 'b', 'c' ]
    [ 'd', 'e' ]
    [ 'a', 'b', 'c', 'd', 'e' ]
    [ 'b', 'c' ]
    [ 'a', 'X', 'Y', 'd', 'e' ]

    slice(start, end) returns a copy of part of the array and never changes the original; the end index is not included. splice(start, deleteCount, ...items) changes the array in place and returns the removed elements. ES2023 added toSpliced(), which works like splice but returns a new array.

    Q24FreshersObjects and arrays

    24. What is the difference between a shallow copy and a deep copy?

    A shallow copy copies only the top level; nested objects are still shared. A deep copy copies every level, so the copy is fully independent.

    const user = { name: "Riya", address: { city: "Surat" } };
    
    const shallow = { ...user };
    const deep = structuredClone(user);
    
    shallow.name = "Aman";
    shallow.address.city = "Pune";     // changes user too!
    console.log(user.name, user.address.city);
    console.log(deep.address.city);

    Output:

    Riya Pune
    Surat

    Spread, Object.assign(), Array.from() and slice() all make shallow copies. For deep copies use structuredClone(), which is built into browsers and Node.js 17+. The old JSON.parse(JSON.stringify(obj)) trick loses functions, undefined, Dates (they become strings), Map, Set and fails on circular references. Question 81 shows how to write a deep clone yourself.

    Q25FreshersObjects and arrays

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

    const arr = ["x", "y", "z"];
    for (const i in arr) console.log("in:", i);      // keys (strings)
    for (const v of arr) console.log("of:", v);      // values
    
    const user = { name: "Riya", age: 22 };
    for (const key in user) console.log(key, user[key]);
    for (const [key, value] of Object.entries(user)) console.log(key, "=", value);

    Output:

    in: 0
    in: 1
    in: 2
    of: x
    of: y
    of: z
    name Riya
    age 22
    name = Riya
    age = 22

    for...in loops over the enumerable property keys of an object, including inherited ones, so it is meant for plain objects. for...of loops over the values of any iterable: arrays, strings, Maps, Sets and generators. A plain object is not iterable, so use Object.keys(), Object.values() or Object.entries() with for…of.

    Q26FreshersObjects and arrays

    26. How do you remove duplicates from an array?

    const nums = [3, 1, 3, 2, 1, 4];
    console.log([...new Set(nums)]);
    
    console.log(nums.filter((n, i) => nums.indexOf(n) === i));   // keeps first occurrence
    
    const users = [{ id: 1, name: "Riya" }, { id: 2, name: "Aman" }, { id: 1, name: "Riya" }];
    const unique = [...new Map(users.map(u => [u.id, u])).values()];
    console.log(unique);

    Output:

    [ 3, 1, 2, 4 ]
    [ 3, 1, 2, 4 ]
    [ { id: 1, name: 'Riya' }, { id: 2, name: 'Aman' } ]

    A Set keeps only unique values and remembers insertion order, so [...new Set(arr)] is the usual answer and runs in O(n). The filter with indexOf version is O(n²). For objects, two objects with the same contents are still different references, so remove duplicates by a key, as the Map example does.

    Q27FreshersObjects and arrays

    27. What do JSON.stringify() and JSON.parse() do?

    JSON.stringify() converts a value to a JSON string, for example to send it to a server or save it in localStorage. JSON.parse() converts a JSON string back to a value.

    const user = { name: "Riya", skills: ["JS", "SQL"], active: true, login: undefined };
    const text = JSON.stringify(user);
    console.log(text);
    console.log(JSON.stringify(user, null, 2));
    
    const back = JSON.parse(text);
    console.log(back.skills[0], typeof back);
    
    try {
      JSON.parse("{name: 'Riya'}");   // not valid JSON
    } catch (e) {
      console.log(e.name);
    }

    Output:

    {"name":"Riya","skills":["JS","SQL"],"active":true}
    {
      "name": "Riya",
      "skills": [
        "JS",
        "SQL"
      ],
      "active": true
    }
    JS object
    SyntaxError

    JSON needs double quotes around keys and strings. undefined, functions and Symbols are dropped from objects, NaN and Infinity become null, and Dates become ISO strings. Both methods accept an extra function (replacer and reviver) to customise the conversion. Always wrap JSON.parse of outside data in try/catch.

    Q28FreshersBasics

    28. What are the most used string methods?

    const s = "  JavaScript Interview  ";
    const t = s.trim();
    console.log(t.length, t.toUpperCase(), t.toLowerCase());
    console.log(t.includes("Script"), t.startsWith("Java"), t.indexOf("I"));
    console.log(t.slice(0, 4), t.slice(-9), t.split(" "));
    console.log(t.replace("a", "@"), t.replaceAll("a", "@"));
    console.log("5".padStart(3, "0"), "ab".repeat(3), t.at(-1));

    Output:

    20 JAVASCRIPT INTERVIEW javascript interview
    true true 11
    Java Interview [ 'JavaScript', 'Interview' ]
    J@vaScript Interview J@v@Script Interview
    005 ababab w

    Strings are immutable: every method returns a new string and leaves the original unchanged. Common interview tasks built from these methods: reverse a string ([...s].reverse().join("")), check a palindrome, count vowels, capitalise words and check anagrams. Several of them are in the practice section below.

    Q29FreshersBasics

    29. What is strict mode?

    Strict mode is a safer version of JavaScript that you switch on with "use strict"; at the top of a file or function. ES modules and class bodies are always strict.

    • Assigning to an undeclared variable throws a ReferenceError instead of creating a global.
    • this is undefined in a plain function call instead of the global object.
    • Duplicate parameter names, with and octal literals like 010 are syntax errors.
    • Writing to a read-only or frozen property throws instead of failing silently.
    "use strict";
    try {
      total = 100;          // forgot let
    } catch (e) {
      console.log(e.name + ": " + e.message);
    }
    function who() { return this; }
    console.log(who());

    Output:

    ReferenceError: total is not defined
    undefined
    Q30FreshersBasics

    30. What is NaN? How do you check for it?

    NaN (“Not a Number”) is the result of a failed numeric operation, such as Number("abc") or 0 / 0. Its type is still “number”, and it is the only value that is not equal to itself.

    console.log(typeof NaN, NaN === NaN);
    console.log(isNaN("hello"), Number.isNaN("hello"));
    console.log(Number.isNaN(Number("hello")), Object.is(NaN, NaN));
    console.log([NaN].includes(NaN), [NaN].indexOf(NaN));

    Output:

    number false
    true false
    true true
    true -1

    The global isNaN() converts its argument to a number first, so isNaN("hello") is true even though “hello” is a string. Number.isNaN() does not convert, so use it. includes() finds NaN, but indexOf() does not, because it uses ===.

    Q31FreshersAsync

    31. Is JavaScript synchronous or asynchronous? What does single-threaded mean?

    JavaScript runs your code on one main thread, one statement at a time, so the language itself is synchronous. It can still handle slow work asynchronously: timers, network requests and file reads are done by the browser or Node.js, and when they finish, a callback is put in a queue. The event loop runs those callbacks when the call stack is empty (question 46).

    console.log("1. Order placed");
    setTimeout(() => console.log("3. Payment confirmed (after 0 ms)"), 0);
    console.log("2. Showing the receipt page");

    Output:

    1. Order placed
    2. Showing the receipt page
    3. Payment confirmed (after 0 ms)

    Even with a 0 ms delay, the timer callback waits until the current code finishes. Because there is one thread, a long loop blocks everything, including clicks and page rendering. Heavy CPU work should be split up or moved to a Web Worker (question 88).

    Q32FreshersAsync

    32. What are setTimeout() and setInterval()?

    setTimeout(fn, ms) runs a function once after at least ms milliseconds. setInterval(fn, ms) runs it again and again every ms milliseconds. Both return an id that you pass to clearTimeout or clearInterval to cancel them.

    let ticks = 0;
    const id = setInterval(() => {
      ticks++;
      console.log("tick", ticks);
      if (ticks === 3) {
        clearInterval(id);
        console.log("stopped");
      }
    }, 100);
    
    const t = setTimeout(() => console.log("never runs"), 50);
    clearTimeout(t);

    Output:

    tick 1
    tick 2
    tick 3
    stopped

    The delay is a minimum, not a promise: the callback still waits for the call stack to be free. Browsers also slow timers down in background tabs. Forgetting to clear an interval is a common source of memory leaks, for example in a React component that unmounts.

    Q33FreshersAsync

    33. What is a Promise?

    A Promise is an object that represents a value that will be available later, for example the result of a network request. It is in one of three states: pending, fulfilled (with a value) or rejected (with an error). Once settled, it never changes.

    function checkMarks(marks) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          if (marks >= 40) resolve("Passed with " + marks);
          else reject(new Error("Failed with " + marks));
        }, 100);
      });
    }
    
    checkMarks(72)
      .then(result => console.log(result))
      .catch(err => console.log(err.message))
      .finally(() => console.log("Result checked"));
    
    checkMarks(25).then(console.log).catch(err => console.log(err.message));

    Output:

    Passed with 72
    Result checked
    Failed with 25

    then handles success, catch handles errors, and finally runs either way. Each of them returns a new promise, which is what makes chaining possible (question 49).

    Q34FreshersAsync

    34. What are async and await?

    An async function always returns a promise. Inside it, await pauses that function until a promise settles, then gives you its value, or throws its error. The result is asynchronous code that reads like normal top-to-bottom code.

    const wait = (ms, value) => new Promise(r => setTimeout(() => r(value), ms));
    
    async function loadProfile() {
      try {
        const user = await wait(100, { id: 7, name: "Riya" });
        console.log("Got user", user.name);
        const courses = await wait(100, ["DSA", "SQL"]);
        console.log("Courses:", courses.join(", "));
        return courses.length;
      } catch (err) {
        console.log("Failed:", err.message);
      }
    }
    
    loadProfile().then(n => console.log("Total courses:", n));
    console.log("loadProfile started");

    Output:

    loadProfile started
    Got user Riya
    Courses: DSA, SQL
    Total courses: 2

    Only the async function pauses; the rest of the program keeps going, which is why “loadProfile started” prints first. Use try/catch for errors. When two awaits do not depend on each other, start both and use await Promise.all([...]) so they run in parallel.

    Q35FreshersDOM and browser

    35. What is the DOM?

    The DOM (Document Object Model) is the tree of objects that the browser builds from an HTML page. Every element, attribute and piece of text becomes a node that JavaScript can read and change. When you change the DOM, the browser updates the page.

    document.body.innerHTML = "<ul id='list'><li>HTML</li><li>CSS</li></ul>";
    const list = document.getElementById("list");
    console.log(list.children.length, list.firstElementChild.textContent);
    
    const li = document.createElement("li");
    li.textContent = "JavaScript";
    list.appendChild(li);
    console.log(list.children.length, list.lastElementChild.textContent);
    console.log(list.parentNode.nodeName);

    Output:

    2 HTML
    3 JavaScript
    BODY

    The DOM is not part of the JavaScript language; it is a Web API that the browser provides, which is why document does not exist in Node.js. Libraries like React keep a virtual copy of the tree and update the real DOM in batches, because DOM changes can trigger expensive layout work (question 93).

    Q36FreshersDOM and browser

    36. How do you select elements in the DOM?

    MethodReturnsLive?
    getElementById("id")One element or null
    querySelector(".css selector")The first match or null
    querySelectorAll("li.item")A static NodeListNo
    getElementsByClassName("x")An HTMLCollectionYes
    getElementsByTagName("li")An HTMLCollectionYes
    document.body.innerHTML = `<div id="app"><p class="msg">One</p><p class="msg">Two</p></div>`;
    const live = document.getElementsByClassName("msg");
    const fixed = document.querySelectorAll(".msg");
    
    const p = document.createElement("p");
    p.className = "msg";
    document.getElementById("app").appendChild(p);
    
    console.log(live.length, fixed.length);
    console.log(document.querySelector("#app .msg").textContent);

    Output:

    3 2
    One

    A live collection updates itself when the DOM changes; a static NodeList is a snapshot. querySelectorAll returns a NodeList with forEach, but not map or filter; convert it with [...list] or Array.from(list).

    Q37FreshersDOM and browser

    37. How do you handle events in JavaScript?

    Use element.addEventListener(type, handler, options). The handler receives an event object with details such as event.target (the element that was clicked), event.type and, for keyboard events, event.key.

    document.body.innerHTML = '<button id="buy">Buy</button>';
    const btn = document.getElementById("buy");
    
    function onBuy(event) {
      console.log(event.type, "on", event.target.id);
    }
    btn.addEventListener("click", onBuy);
    btn.addEventListener("click", () => console.log("runs once only"), { once: true });
    
    btn.click();
    btn.click();
    btn.removeEventListener("click", onBuy);
    btn.click();
    console.log("done");

    Output:

    click on buy
    runs once only
    click on buy
    done

    Unlike the old onclick = ... property, addEventListener lets you attach several handlers to the same event. To remove a handler you must pass the same function reference, so an anonymous arrow function cannot be removed later. Useful options: { once: true }, { passive: true } for scroll and touch handlers, and { capture: true }.

    Q38FreshersObjects and arrays

    38. What are the common array methods for adding, removing and finding items?

    const a = [2, 4, 6];
    a.push(8);          // add to the end
    a.unshift(0);       // add to the start
    console.log(a);
    console.log(a.pop(), a.shift(), a);   // remove from the end and start
    
    const users = [{ id: 1, name: "Riya" }, { id: 2, name: "Aman" }];
    console.log(a.includes(4), a.indexOf(6));
    console.log(users.find(u => u.id === 2).name, users.findIndex(u => u.id === 9));
    console.log(a.some(n => n > 5), a.every(n => n % 2 === 0));
    console.log([3, [4, [5]]].flat(Infinity), a.join("-"));

    Output:

    [ 0, 2, 4, 6, 8 ]
    8 0 [ 2, 4, 6 ]
    true 2
    Aman -1
    true true
    [ 3, 4, 5 ] 2-4-6

    push, pop, shift, unshift, splice, sort and reverse change the array in place. map, filter, slice, concat and flat return a new array. shift and unshift are O(n) because every other element has to move. find returns the first match or undefined; filter returns all matches as an array.

    Q39FreshersObjects and arrays

    39. How do you check if a property exists in an object?

    const user = { name: "Riya", age: 0, email: undefined };
    console.log("age" in user, "toString" in user);              // includes inherited keys
    console.log(Object.hasOwn(user, "age"), Object.hasOwn(user, "toString"));
    console.log(user.email !== undefined, "email" in user);      // value undefined, key exists
    console.log(user.age ? "has age" : "no age");               // wrong check: 0 is falsy
    console.log(Object.keys(user));

    Output:

    true true
    true false
    false true
    no age
    [ 'name', 'age', 'email' ]

    Use Object.hasOwn(obj, key) (or the older obj.hasOwnProperty(key)) for own properties, and the in operator when inherited properties should count too. Checking obj.key for truthiness fails for values like 0, “” and false, and comparing with undefined cannot tell a missing key from a key set to undefined.

    Q40FreshersDOM and browser

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

    localStoragesessionStorageCookies
    LifetimeUntil clearedUntil the tab is closedUntil the expiry date, or the session
    SizeAbout 5 MB per originAbout 5 MB per originAbout 4 KB per cookie
    Sent to the serverNoNoYes, with every request to that domain
    Shared between tabsYesNoYes
    Readable by JavaScriptYesYesYes, unless the cookie is HttpOnly
    // Values are always stored as strings
    localStorage.setItem("theme", "dark");
    localStorage.setItem("cart", JSON.stringify([{ id: 1, qty: 2 }]));
    
    const cart = JSON.parse(localStorage.getItem("cart") || "[]");
    localStorage.removeItem("theme");
    
    sessionStorage.setItem("step", "2");
    document.cookie = "lang=en; max-age=86400; path=/; SameSite=Lax";

    Store objects with JSON.stringify and read them back with JSON.parse. Never keep secrets such as auth tokens in localStorage: any script on the page, including one injected by an XSS attack, can read it. Session tokens are safer in an HttpOnly, Secure, SameSite cookie, which JavaScript cannot read at all (question 91).

    Intermediate JavaScript interview questions

    These 35 questions are for candidates with one to three years of experience: this, prototypes and classes, the event loop, promises and error handling, closures in practice (currying, memoization, debounce, throttle), ES6+ features and DOM events.

    Q41IntermediateObjects and this

    41. How does the this keyword work?

    For regular functions, this is decided by how the function is called, not where it is written. Arrow functions have no this of their own and use the one from the surrounding code.

    How it is calledValue of this
    obj.method()obj
    A plain call, fn()undefined in strict mode, the global object otherwise
    new Fn()The new object being created
    fn.call(x), fn.apply(x), fn.bind(x)x
    An event handler set with addEventListenerThe element (event.currentTarget)
    An arrow functionWhatever this is in the enclosing scope
    "use strict";
    const user = {
      name: "Riya",
      hi() { return "Hi " + (this ? this.name : "nobody"); }
    };
    console.log(user.hi());
    
    const hi = user.hi;          // the method loses its object
    console.log(hi());
    
    const bound = user.hi.bind({ name: "Aman" });
    console.log(bound());

    Output:

    Hi Riya
    Hi nobody
    Hi Aman

    Losing this when a method is passed as a callback is a classic bug. Fix it with an arrow wrapper, with bind, or by using arrow functions as class fields.

    Q42IntermediateObjects and this

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

    All three set this explicitly. call and apply run the function immediately; call takes arguments one by one and apply takes them as an array. bind does not run the function; it returns a new function with this (and optionally some arguments) fixed.

    function introduce(greeting, punct) {
      return `${greeting}, I am ${this.name}${punct}`;
    }
    const riya = { name: "Riya" };
    
    console.log(introduce.call(riya, "Hello", "!"));
    console.log(introduce.apply(riya, ["Hi", "."]));
    
    const hey = introduce.bind(riya, "Hey");   // partial application
    console.log(hey("?"));
    
    console.log(Math.max.apply(null, [4, 9, 2]), Math.max(...[4, 9, 2]));

    Output:

    Hello, I am Riya!
    Hi, I am Riya.
    Hey, I am Riya?
    9 9

    A bound function cannot be re-bound: calling bind again or call on it does not change its this. Arrow functions ignore the this argument of all three. Question 80 shows how to write bind yourself.

    Q43IntermediateObjects and this

    43. What is a prototype and the prototype chain?

    Every object has a hidden link to another object, its prototype. When you read a property that the object does not have, JavaScript looks it up on the prototype, then on the prototype’s prototype, and so on until it reaches null. That lookup path is the prototype chain, and it is how JavaScript does inheritance.

    function Animal(name) { this.name = name; }
    Animal.prototype.speak = function () { return this.name + " makes a sound"; };
    
    const dog = new Animal("Bruno");
    console.log(dog.speak());                                   // found on the prototype
    console.log(Object.hasOwn(dog, "speak"));
    console.log(Object.getPrototypeOf(dog) === Animal.prototype);
    console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype);
    console.log(Object.getPrototypeOf(Object.prototype));
    
    const arr = [1, 2];
    console.log(Object.getPrototypeOf(arr) === Array.prototype, typeof arr.map);

    Output:

    Bruno makes a sound
    false
    true
    true
    null
    true function

    Methods live once on the prototype and are shared by all instances, which saves memory. obj.__proto__ is the old way to reach the prototype; use Object.getPrototypeOf() and Object.create() instead. Fn.prototype is the object that becomes the prototype of everything created with new Fn().

    Q44IntermediateObjects and this

    44. How do classes and inheritance work in JavaScript?

    ES6 classes are cleaner syntax over prototypes. extends sets up the prototype chain, and super calls the parent constructor or a parent method.

    class Employee {
      static count = 0;
      constructor(name, salary) {
        this.name = name;
        this.salary = salary;
        Employee.count++;
      }
      describe() { return `${this.name} earns ${this.salary}`; }
    }
    
    class Manager extends Employee {
      constructor(name, salary, team) {
        super(name, salary);          // must come before using this
        this.team = team;
      }
      describe() { return super.describe() + ` and leads ${this.team.length} people`; }
    }
    
    const m = new Manager("Riya", 90000, ["Aman", "Neha"]);
    console.log(m.describe());
    console.log(m instanceof Employee, Employee.count, typeof Manager);

    Output:

    Riya earns 90000 and leads 2 people
    true 1 function

    Differences from functions: class declarations are in the TDZ until defined, class bodies are always strict mode, and calling a class without new throws. typeof a class is still “function”. Private fields with # are covered in question 95.

    Q45IntermediateObjects and this

    45. What is the difference between Object.freeze(), Object.seal() and const?

    Add propertiesDelete propertiesChange values
    const variableYesYesYes (only the variable cannot be reassigned)
    Object.preventExtensions()NoYesYes
    Object.seal()NoNoYes
    Object.freeze()NoNoNo
    "use strict";
    const config = Object.freeze({ api: "/v1", retry: { times: 3 } });
    try { config.api = "/v2"; } catch (e) { console.log(e.constructor.name); }
    config.retry.times = 10;            // freeze is shallow
    console.log(config.api, config.retry.times, Object.isFrozen(config));
    
    const user = Object.seal({ name: "Riya" });
    user.name = "Aman";
    try { user.age = 22; } catch (e) { console.log("cannot add:", e.constructor.name); }
    console.log(user);

    Output:

    TypeError
    /v1 10 true
    cannot add: TypeError
    { name: 'Aman' }

    Outside strict mode these changes fail silently instead of throwing. Freeze is shallow, so nested objects stay mutable unless you freeze them too (a recursive “deep freeze”).

    Q46IntermediateAsync

    46. What is the event loop?

    The event loop lets single-threaded JavaScript handle asynchronous work. The engine runs code on the call stack. Slow work such as timers and network requests is handed to the browser or Node.js. When that work finishes, its callback is queued. Whenever the call stack is empty, the event loop:

    1. Runs all queued microtasks (promise callbacks, queueMicrotask, await continuations), including any that are added while it runs.
    2. Lets the browser render if needed.
    3. Takes one macrotask (a timer, an I/O callback or a UI event) from the task queue, runs it, and goes back to step 1.
    console.log("1 script start");
    setTimeout(() => console.log("5 timeout"), 0);
    Promise.resolve()
      .then(() => console.log("3 promise 1"))
      .then(() => console.log("4 promise 2"));
    queueMicrotask(() => console.log("3b microtask"));
    console.log("2 script end");

    Output:

    1 script start
    2 script end
    3 promise 1
    3b microtask
    4 promise 2
    5 timeout

    All synchronous code runs first, then every microtask, and only then the timer, even with a delay of 0. Step through this exact flow in the event loop visualiser above.

    Q47IntermediateAsync

    47. What is the difference between microtasks and macrotasks?

    MicrotasksMacrotasks (tasks)
    ExamplesPromise then/catch/finally, await, queueMicrotask, MutationObserversetTimeout, setInterval, I/O, UI events, MessageChannel
    When they runRight after the current script or task, before renderingOne per loop iteration
    How many per turnThe queue is drained completelyOne, then microtasks run again
    setTimeout(() => console.log("timeout 1"), 0);
    setTimeout(() => {
      console.log("timeout 2");
      Promise.resolve().then(() => console.log("micro inside timeout 2"));
    }, 0);
    setTimeout(() => console.log("timeout 3"), 0);
    Promise.resolve().then(() => console.log("micro 1"));

    Output:

    micro 1
    timeout 1
    timeout 2
    micro inside timeout 2
    timeout 3

    The microtask scheduled inside “timeout 2” runs before “timeout 3”, because microtasks are drained after every macrotask. A microtask that keeps scheduling new microtasks can freeze the page, since the loop never gets to rendering or the next task.

    Q48IntermediateAsync

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

    MethodResolves whenRejects when
    Promise.allAll fulfil (array of values, in input order)Any one rejects (fail fast)
    Promise.allSettledAll settle (array of {status, value or reason})Never
    Promise.raceThe first one settles, if it fulfilsThe first one settles, if it rejects
    Promise.anyThe first one fulfilsAll reject (AggregateError)
    const ok = (ms, v) => new Promise(r => setTimeout(() => r(v), ms));
    const fail = (ms, msg) => new Promise((_, j) => setTimeout(() => j(new Error(msg)), ms));
    
    async function main() {
      console.log(await Promise.all([ok(30, "A"), ok(10, "B")]));
      try { await Promise.all([ok(30, "A"), fail(10, "B broke")]); }
      catch (e) { console.log("all:", e.message); }
      const s = await Promise.allSettled([ok(10, "A"), fail(20, "B broke")]);
      console.log(s.map(r => r.status));
      console.log("race:", await Promise.race([ok(30, "slow"), ok(10, "fast")]));
      console.log("any:", await Promise.any([fail(10, "x"), ok(20, "first success")]));
    }
    main();

    Output:

    [ 'A', 'B' ]
    all: B broke
    [ 'fulfilled', 'rejected' ]
    race: fast
    any: first success

    Use all for requests that must all succeed, allSettled when you want every result even if some fail (a dashboard with independent widgets), race for timeouts, and any for “use whichever mirror answers first”. Question 79 asks you to implement Promise.all.

    Q49IntermediateAsync

    49. How does promise chaining work?

    Every then returns a new promise. If the callback returns a value, the next then receives it. If it returns a promise, the chain waits for it. If it throws, control jumps to the next catch.

    const delay = (ms, v) => new Promise(r => setTimeout(() => r(v), ms));
    
    delay(50, 2)
      .then(n => n * 10)                    // plain value
      .then(n => delay(50, n + 1))          // promise: the chain waits
      .then(n => {
        console.log("value:", n);
        throw new Error("bad data");
      })
      .then(() => console.log("skipped"))
      .catch(e => { console.log("caught:", e.message); return "recovered"; })
      .then(v => console.log("after catch:", v));

    Output:

    value: 21
    caught: bad data
    after catch: recovered

    A common mistake is forgetting to return the inner promise inside then, which breaks the chain: the next step runs too early and errors are not caught. A catch in the middle handles errors from above it, and the chain continues after it.

    Q50IntermediateAsync

    50. How do you handle errors in async code?

    const getUser = id => id > 0
      ? Promise.resolve({ id, name: "Riya" })
      : Promise.reject(new Error("Invalid id " + id));
    
    async function load(id) {
      try {
        const user = await getUser(id);
        console.log("loaded", user.name);
      } catch (err) {
        console.log("error:", err.message);
      } finally {
        console.log("hide spinner for", id);
      }
    }
    
    async function main() {
      await load(1);
      await load(-1);
      getUser(-2);   // nobody handles this rejection
    }
    main();

    Output:

    loaded Riya
    hide spinner for 1
    error: Invalid id -1
    hide spinner for -1
    Uncaught (in promise) Error: Invalid id -2

    With async/await, wrap awaits in try/catch/finally. With plain promises, end every chain with .catch(). A rejection that nobody handles triggers the unhandledrejection event in browsers and, since Node.js 15, crashes the Node.js process. A try/catch around code that does not await the promise will not catch its rejection.

    Q51IntermediateAsync

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

    Callback hell (the “pyramid of doom”) is what happens when each async step needs the result of the previous one and you nest callbacks inside callbacks. The code drifts to the right, error handling is repeated at every level, and it becomes hard to follow.

    // Callback hell
    getUser(id, (err, user) => {
      if (err) return handle(err);
      getOrders(user.id, (err, orders) => {
        if (err) return handle(err);
        getInvoice(orders[0].id, (err, invoice) => {
          if (err) return handle(err);
          send(invoice, err => { if (err) handle(err); });
        });
      });
    });
    
    // The same flow with async/await
    async function sendFirstInvoice(id) {
      try {
        const user = await getUser(id);
        const orders = await getOrders(user.id);
        const invoice = await getInvoice(orders[0].id);
        await send(invoice);
      } catch (err) {
        handle(err);
      }
    }

    Ways out: promises and async/await, named functions instead of anonymous nested ones, and util.promisify in Node.js to turn callback APIs into promise APIs.

    Q52IntermediateFunctions

    52. Why does a for loop with var and setTimeout print the same number?

    for (var i = 1; i <= 3; i++) {
      setTimeout(() => console.log("var:", i), 10);
    }
    for (let j = 1; j <= 3; j++) {
      setTimeout(() => console.log("let:", j), 20);
    }
    for (var k = 1; k <= 3; k++) {
      ((n) => setTimeout(() => console.log("IIFE:", n), 30))(k);
    }

    Output:

    var: 4
    var: 4
    var: 4
    let: 1
    let: 2
    let: 3
    IIFE: 1
    IIFE: 2
    IIFE: 3

    var is function scoped, so there is only one i for the whole loop. All three callbacks close over that same variable, and by the time they run, the loop has finished and i is 4. let creates a new binding for every iteration, so each callback gets its own j. Before ES6 the fix was an IIFE that copies the value into a parameter.

    Q53IntermediateFunctions

    53. What is currying?

    Currying turns a function that takes several arguments into a chain of functions that take one argument each: f(a, b, c) becomes f(a)(b)(c). It lets you build specialised functions from general ones.

    function curry(fn) {
      return function curried(...args) {
        if (args.length >= fn.length) return fn.apply(this, args);
        return (...more) => curried.apply(this, [...args, ...more]);
      };
    }
    
    const price = (tax, discount, amount) => Math.round(amount * (1 + tax) - discount);
    const withGst = curry(price)(0.18);
    const festive = withGst(100);
    
    console.log(festive(1000), festive(500));
    console.log(curry(price)(0.18, 0, 1000), curry(price)(0.18)(0)(1000));

    Output:

    1080 490
    1180 1180

    The generic curry checks fn.length (the number of declared parameters) and keeps collecting arguments until it has enough. A frequent follow-up asks for an infinite sum, sum(1)(2)(3)(), which you solve the same way by returning a function until it is called with no argument.

    Q54IntermediateFunctions

    54. What is memoization?

    Memoization caches the result of a function call by its arguments, so a repeated call returns the saved result instead of computing it again. It works for pure functions, where the same input always gives the same output.

    function memoize(fn) {
      const cache = new Map();
      return function (...args) {
        const key = JSON.stringify(args);
        if (!cache.has(key)) cache.set(key, fn.apply(this, args));
        return cache.get(key);
      };
    }
    
    let calls = 0;
    const fib = memoize(n => { calls++; return n < 2 ? n : fib(n - 1) + fib(n - 2); });
    console.log(fib(50), "computed in", calls, "calls");
    console.log(fib(50), "second time, still", calls, "calls");

    Output:

    12586269025 computed in 51 calls
    12586269025 second time, still 51 calls

    Without the cache, fib(50) would take about 40 billion calls. The cache key here is JSON.stringify(args), which is fine for numbers and strings; for object arguments, use a WeakMap keyed by the object. In React, useMemo and React.memo apply the same idea to rendering. Our Fibonacci and dynamic programming guide explains the algorithm side.

    Q55IntermediateFunctions

    55. What is debouncing? Implement debounce.

    Debouncing delays a function until the calls stop for a given time. If it is called again before the time is up, the timer restarts. Typical uses: a search box that calls the API only after the user stops typing, and saving a form draft.

    function debounce(fn, wait) {
      let timer;
      return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => fn.apply(this, args), wait);
      };
    }
    
    const search = debounce(q => console.log("API call for:", q), 100);
    // Simulate typing "java" quickly, then "js" after a pause
    search("j"); search("ja"); search("jav"); search("java");
    setTimeout(() => search("js"), 250);

    Output:

    API call for: java
    API call for: js

    Only two API calls are made instead of five. Many interviewers then ask for a “leading” option (fire on the first call, then ignore the rest) and a cancel() method. Lodash’s debounce has both.

    Q56IntermediateFunctions

    56. What is throttling? How is it different from debouncing?

    Throttling lets a function run at most once in every time window, however often it is called. Use it for scroll, resize and mousemove handlers, where you want regular updates but not hundreds per second. Debounce waits for a pause; throttle runs at a steady rate during continuous activity.

    function throttle(fn, limit) {
      let last = 0;
      return function (...args) {
        const now = Date.now();
        if (now - last >= limit) {
          last = now;
          fn.apply(this, args);
        }
      };
    }
    
    const log = throttle(n => console.log("handled event", n), 100);
    let n = 0;
    const id = setInterval(() => {
      n++;
      log(n);                       // called every 20 ms
      if (n === 12) clearInterval(id);
    }, 20);

    Output:

    handled event 1
    handled event 6
    handled event 11

    Twelve events arrive over about 240 ms, but only a few get through. Which ones exactly depends on timer accuracy, so you may see slightly different numbers. This simple version drops the last call; production versions such as Lodash’s also schedule a trailing call so the final state is never lost.

    Q57IntermediateFunctions

    57. What are generator functions?

    A generator (function*) can pause with yield and resume later. Calling it returns an iterator; each next() runs the body until the next yield and returns { value, done }. Generators produce values lazily, so they can even represent infinite sequences.

    function* idGenerator(prefix) {
      let n = 1;
      while (true) yield `${prefix}-${n++}`;
    }
    const ids = idGenerator("ORD");
    console.log(ids.next().value, ids.next().value, ids.next().value);
    
    function* range(start, end, step = 1) {
      for (let i = start; i < end; i += step) yield i;
    }
    console.log([...range(0, 10, 3)]);
    
    const it = range(1, 3);
    console.log(it.next(), it.next(), it.next());

    Output:

    ORD-1 ORD-2 ORD-3
    [ 0, 3, 6, 9 ]
    { value: 1, done: false } { value: 2, done: false } { value: undefined, done: true }

    Generators are iterable, so they work with for…of and spread. Libraries such as Redux-Saga use them to describe async flows, and async generators (question 85) combine yield with await.

    Q58IntermediateES6+

    58. What is the difference between Map and a plain object? What is a Set?

    ObjectMap
    Key typesStrings and Symbols onlyAny value, including objects
    OrderMostly insertion order (integer keys first)Always insertion order
    SizeObject.keys(o).lengthmap.size
    Iterable directlyNoYes
    Inherited keysYes, unless created with Object.create(null)No
    Frequent adds and deletesSlowerOptimised for it
    const visits = new Map();
    const page = { url: "/home" };
    visits.set(page, 3).set("about", 1);
    console.log(visits.get(page), visits.size, visits.has("about"));
    
    const o = {};
    o[1] = "a"; o.b = "b"; o[0] = "c";
    console.log(Object.keys(o));          // integer keys come first
    
    const tags = new Set(["js", "css", "js"]);
    tags.add("html");
    console.log(tags.size, tags.has("css"), [...tags]);

    Output:

    3 2 true
    [ '0', '1', 'b' ]
    3 true [ 'js', 'css', 'html' ]

    A Set stores unique values of any type with fast add, delete and has. Use a Map for dictionaries whose keys are not fixed strings, or that change often; use a plain object for fixed-shape records and JSON data.

    Q59IntermediateES6+

    59. What are WeakMap and WeakSet?

    A WeakMap takes only objects (or non-registered Symbols) as keys and holds them weakly: if nothing else refers to a key object, it can be garbage collected, and its entry disappears. For that reason a WeakMap is not iterable and has no size. A WeakSet is the same idea for a set of objects.

    const meta = new WeakMap();
    
    function track(el) {
      meta.set(el, { clicks: 0 });
    }
    function click(el) {
      meta.get(el).clicks++;
    }
    
    let button = { id: "buy" };     // stands in for a DOM element
    track(button);
    click(button); click(button);
    console.log(meta.get(button).clicks, meta.has(button));
    button = null;                  // the entry can now be garbage collected
    
    const seen = new WeakSet();
    const a = {};
    seen.add(a);
    console.log(seen.has(a), seen.has({}));

    Output:

    2 true
    true false

    Uses: attaching data to DOM nodes or objects you do not own without leaking memory, caching results per object, and marking objects as “already processed” (for example to detect cycles when deep cloning).

    Q60IntermediateES6+

    60. What is a Symbol?

    A Symbol is a primitive value that is always unique, even when two symbols have the same description. Symbols make good property keys that can never clash with other keys, and they are skipped by for…in, Object.keys and JSON.stringify.

    const id = Symbol("id");
    const user = { name: "Riya", [id]: 101 };
    console.log(user[id], Symbol("id") === Symbol("id"));
    console.log(Object.keys(user), JSON.stringify(user));
    
    const shared = Symbol.for("app.version");     // global symbol registry
    console.log(shared === Symbol.for("app.version"));
    
    class Temperature {
      constructor(c) { this.c = c; }
      [Symbol.toPrimitive](hint) { return hint === "string" ? this.c + "°C" : this.c; }
    }
    const t = new Temperature(30);
    console.log(`${t}`, t + 5);

    Output:

    101 false
    [ 'name' ] {"name":"Riya"}
    true
    30°C 35

    The language uses “well-known symbols” to let objects customise built-in behaviour: Symbol.iterator (makes an object iterable), Symbol.toPrimitive, Symbol.asyncIterator and Symbol.hasInstance.

    Q61IntermediateES6+

    61. What are optional chaining (?.) and nullish coalescing (??)?

    ?. stops and returns undefined if the value on its left is null or undefined, instead of throwing a TypeError. ?? returns the right side only when the left side is null or undefined, unlike ||, which also replaces 0, “” and false.

    const user = { name: "Riya", address: null, settings: { volume: 0 }, greet() { return "hi"; } };
    
    console.log(user.address?.city);              // no TypeError
    console.log(user.greet?.(), user.logout?.());
    console.log(user.orders?.[0]?.id);
    
    console.log(user.settings.volume || 50);      // 0 is lost
    console.log(user.settings.volume ?? 50);      // 0 is kept
    let title = null;
    title ??= "Untitled";
    console.log(title);

    Output:

    undefined
    hi undefined
    undefined
    50
    0
    Untitled

    Both arrived in ES2020, and the assignment operators ??=, ||= and &&= in ES2021. Do not overuse ?.; if a value should always exist, a loud error is better than silently carrying on with undefined.

    Q62IntermediateES6+

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

    CommonJSES modules
    Syntaxrequire(), module.exportsimport, export
    LoadingSynchronous, at run timeStatic, analysed before running; can load asynchronously
    WhereNode.js (the original system)Browsers and modern Node.js
    Tree shakingHardYes, because imports are static
    Top-level awaitNoYes
    this at top levelmodule.exportsundefined
    // math.mjs (ES module)
    export const PI = 3.14159;
    export default function area(r) { return PI * r * r; }
    
    // app.mjs
    import area, { PI } from "./math.mjs";
    const { format } = await import("./format.mjs");   // dynamic import
    
    // CommonJS version
    const { PI } = require("./math.js");
    module.exports = { area };

    ES module imports are live bindings: if the exporting module changes a value, importers see the change. In Node.js, a file is treated as an ES module when it ends in .mjs or when package.json has "type": "module".

    Q63IntermediateDOM and browser

    63. What is event bubbling and capturing?

    A DOM event travels in three phases. In the capturing phase it goes down from the window to the target, then it reaches the target, and in the bubbling phase it goes back up through every ancestor. Listeners run in the bubbling phase by default; pass { capture: true } (or true) to listen during capturing.

    document.body.innerHTML = '<div id="outer"><div id="inner"><button id="btn">Click</button></div></div>';
    const log = label => e => console.log(label, "| target:", e.target.id, "| current:", e.currentTarget.id);
    
    for (const id of ["outer", "inner", "btn"]) {
      const el = document.getElementById(id);
      el.addEventListener("click", log("bubble  " + id));
      el.addEventListener("click", log("capture " + id), { capture: true });
    }
    document.getElementById("btn").click();

    Output:

    capture outer | target: btn | current: outer
    capture inner | target: btn | current: inner
    capture btn | target: btn | current: btn
    bubble  btn | target: btn | current: btn
    bubble  inner | target: btn | current: inner
    bubble  outer | target: btn | current: outer

    event.target is the element where the event started; event.currentTarget is the element whose listener is running now. Most events bubble, but a few do not, such as focus, blur, mouseenter and load (use focusin and focusout if you need bubbling).

    Q64IntermediateDOM and browser

    64. What is event delegation?

    Event delegation means putting one listener on a parent element instead of one on every child. Because events bubble, the parent hears clicks on all its children, and event.target.closest() tells you which child was clicked. It works for children added later too, and uses less memory.

    document.body.innerHTML = `<ul id="todos">
      <li data-id="1">Learn closures <button class="del">x</button></li>
      <li data-id="2">Practise DSA <button class="del">x</button></li>
    </ul>`;
    const list = document.getElementById("todos");
    
    list.addEventListener("click", e => {
      const btn = e.target.closest(".del");
      if (!btn || !list.contains(btn)) return;
      const li = btn.closest("li");
      console.log("deleting todo", li.dataset.id);
      li.remove();
    });
    
    list.insertAdjacentHTML("beforeend", '<li data-id="3">Revise SQL <button class="del">x</button></li>');
    list.querySelector('[data-id="3"] .del').click();   // works for the new item too
    list.querySelector('[data-id="1"] .del').click();
    console.log("left:", list.children.length);

    Output:

    deleting todo 3
    deleting todo 1
    left: 1
    Q65IntermediateDOM and browser

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

    event.preventDefault() stops the browser’s default action, such as submitting a form, following a link or checking a checkbox. The event still bubbles. event.stopPropagation() stops the event from travelling to other elements, but the default action still happens. stopImmediatePropagation() also stops other listeners on the same element.

    document.body.innerHTML = '<div id="card"><a id="link" href="https://example.com">Open</a></div>';
    const link = document.getElementById("link");
    
    document.getElementById("card").addEventListener("click", () => console.log("card heard the click"));
    link.addEventListener("click", e => {
      e.preventDefault();
      console.log("navigation blocked, defaultPrevented =", e.defaultPrevented);
    });
    link.click();
    
    link.addEventListener("click", e => e.stopPropagation());
    link.click();
    console.log("second click did not reach the card");

    Output:

    navigation blocked, defaultPrevented = true
    card heard the click
    navigation blocked, defaultPrevented = true
    second click did not reach the card

    Use stopPropagation sparingly: it can break analytics, dropdowns that close on outside clicks, and event delegation further up the tree.

    Q66IntermediateDOM and browser

    66. How do you make an API call with fetch()?

    fetch(url, options) returns a promise for a Response. It only rejects on a network failure; an HTTP error such as 404 or 500 still resolves, so you must check response.ok yourself.

    async function getCourses() {
      const controller = new AbortController();
      const timer = setTimeout(() => controller.abort(), 5000);   // 5 s timeout
      try {
        const res = await fetch("/api/courses?level=beginner", { signal: controller.signal });
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return await res.json();
      } finally {
        clearTimeout(timer);
      }
    }
    
    async function createCourse(course) {
      const res = await fetch("/api/courses", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(course)
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      return res.json();
    }

    fetch does not send cookies to other origins unless you set credentials: "include", has no built-in timeout (use AbortController, question 96), and the body can be read only once. Libraries like Axios add interceptors, automatic JSON and HTTP errors that reject.

    Q67IntermediateDOM and browser

    67. What is the difference between async and defer on a script tag?

    DownloadsRunsOrder kept
    Plain <script>Blocks HTML parsingImmediately, parsing waitsYes
    asyncIn parallel with parsingAs soon as it is downloadedNo
    deferIn parallel with parsingAfter the HTML is parsed, before DOMContentLoadedYes
    type="module"In parallel with parsingLike defer by defaultYes

    Use defer for your own scripts that need the DOM or depend on each other. Use async for independent third-party scripts such as analytics. A plain script in the head without either attribute delays the first paint, so put it at the end of the body if you cannot add an attribute.

    Q68IntermediateObjects and arrays

    68. Why does [10, 1, 5, 100].sort() give the wrong order?

    console.log([10, 1, 5, 100].sort());                 // compared as strings
    console.log([10, 1, 5, 100].sort((a, b) => a - b));  // numeric ascending
    console.log([10, 1, 5, 100].sort((a, b) => b - a));  // descending
    
    const people = [{ name: "Riya", age: 25 }, { name: "aman", age: 22 }, { name: "Karan", age: 25 }];
    people.sort((a, b) => a.age - b.age || a.name.localeCompare(b.name));
    console.log(people.map(p => p.name));
    
    const nums = [3, 1, 2];
    const sorted = nums.toSorted();     // ES2023: does not change nums
    console.log(nums, sorted);

    Output:

    [ 1, 10, 100, 5 ]
    [ 1, 5, 10, 100 ]
    [ 100, 10, 5, 1 ]
    [ 'aman', 'Karan', 'Riya' ]
    [ 3, 1, 2 ] [ 1, 2, 3 ]

    Without a compare function, sort converts the elements to strings and compares them by UTF-16 code units, so “100” comes before “5”. The compare function returns a negative number to put a first, positive to put b first, and 0 to keep the order. sort works in place and is stable since ES2019. Use localeCompare for text so that case and accents are handled properly.

    Q69IntermediateBasics

    69. Why is 0.1 + 0.2 not equal to 0.3?

    console.log(0.1 + 0.2, 0.1 + 0.2 === 0.3);
    console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);
    console.log((0.1 + 0.2).toFixed(2), Math.round((0.1 + 0.2) * 100) / 100);
    console.log(Number.MAX_SAFE_INTEGER, 9007199254740992 === 9007199254740993);
    console.log(9007199254740992n + 1n);

    Output:

    0.30000000000000004 false
    true
    0.30 0.3
    9007199254740991 true
    9007199254740993n

    All JavaScript numbers are 64-bit binary floating point (IEEE 754). Fractions like 0.1 cannot be stored exactly in binary, so tiny rounding errors appear. Compare with a tolerance, format results with toFixed, and for money store whole paise or cents as integers. Integers are exact only up to Number.MAX_SAFE_INTEGER (2 ** 53 - 1); beyond that, use BigInt.

    Q70IntermediateBasics

    70. What are the built-in error types? How do you create a custom error?

    ErrorWhen you see it
    ReferenceErrorA variable that does not exist, or a let/const used in its TDZ
    TypeErrorCalling something that is not a function, reading a property of undefined, writing to a const
    SyntaxErrorInvalid code, or invalid JSON in JSON.parse
    RangeErrorA number out of range, e.g. new Array(-1) or too much recursion
    URIError, EvalError, AggregateErrorBad URI functions, legacy eval errors, and several errors at once (Promise.any)
    class ValidationError extends Error {
      constructor(field, message) {
        super(message);
        this.name = "ValidationError";
        this.field = field;
      }
    }
    
    function register(user) {
      if (!user.email?.includes("@")) throw new ValidationError("email", "Enter a valid email");
      return "registered";
    }
    
    try {
      register({ email: "riya.gmail.com" });
    } catch (e) {
      if (e instanceof ValidationError) console.log(e.name, e.field, "-", e.message);
      else throw e;
    }
    
    try { null.length; } catch (e) { console.log(e instanceof TypeError, e.name); }
    try { (function f() { f(); })(); } catch (e) { console.log(e.name); }

    Output:

    ValidationError email - Enter a valid email
    true TypeError
    RangeError

    Custom errors let calling code react to the kind of failure with instanceof and rethrow everything else. new Error(message, { cause: err }) (ES2022) keeps the original error attached when you wrap it.

    Q71IntermediateFunctions

    71. What is a pure function? Why does immutability matter?

    A pure function always returns the same output for the same input and has no side effects: it does not change its arguments, global variables, the DOM or anything else outside itself. Pure functions are easy to test, cache and reason about.

    const cart = [{ item: "Pen", qty: 1 }];
    
    function addItemImpure(list, item) {   // changes the caller's array
      list.push(item);
      return list;
    }
    function addItemPure(list, item) {     // returns a new array
      return [...list, item];
    }
    
    const next = addItemPure(cart, { item: "Book", qty: 2 });
    console.log(cart.length, next.length, cart === next);
    addItemImpure(cart, { item: "Bag", qty: 1 });
    console.log(cart.length);

    Output:

    1 2 false
    2

    Immutability means creating new objects instead of changing existing ones. React and Redux depend on it: they detect changes by comparing references (prev !== next), so mutating state in place means the UI does not update. Spread syntax, map, filter, structuredClone and the ES2023 methods toSorted, toReversed and with help.

    Q72IntermediateObjects and this

    72. What are getters and setters?

    Getters and setters are methods that look like normal properties. A getter (get) runs when the property is read, and a setter (set) runs when it is assigned. They are useful for computed values and for validation.

    class Account {
      #balance = 0;
      constructor(owner) { this.owner = owner; }
      get balance() { return "Rs " + this.#balance.toLocaleString("en-IN"); }
      set deposit(amount) {
        if (amount <= 0) throw new RangeError("Deposit must be positive");
        this.#balance += amount;
      }
    }
    const acc = new Account("Riya");
    acc.deposit = 150000;
    console.log(acc.balance);
    try { acc.deposit = -5; } catch (e) { console.log(e.message); }
    
    const temp = { c: 25, get f() { return this.c * 9 / 5 + 32; } };
    console.log(temp.f);

    Output:

    Rs 1,50,000
    Deposit must be positive
    77
    Q73IntermediateObjects and arrays

    73. How do you compare two objects or arrays?

    == and === compare objects by reference: they are equal only if both variables point to the same object. To compare contents, you need a deep comparison.

    function deepEqual(a, b) {
      if (Object.is(a, b)) return true;
      if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
      if (Array.isArray(a) !== Array.isArray(b)) return false;
      const ka = Object.keys(a), kb = Object.keys(b);
      if (ka.length !== kb.length) return false;
      return ka.every(k => Object.hasOwn(b, k) && deepEqual(a[k], b[k]));
    }
    
    const x = { id: 1, tags: ["js", "dom"] };
    const y = { id: 1, tags: ["js", "dom"] };
    console.log(x === y, deepEqual(x, y));
    console.log(deepEqual([1, [2, 3]], [1, [2, 4]]));
    console.log(JSON.stringify({ a: 1, b: 2 }) === JSON.stringify({ b: 2, a: 1 }));

    Output:

    false true
    false
    false

    Comparing JSON strings is a quick hack but fails when keys are in a different order, and it ignores undefined values. In tests, use the library’s deep equality (expect(a).toEqual(b) in Jest).

    Q74IntermediateFunctions

    74. What is the arguments object? What are array-like objects?

    Inside a regular function, arguments holds all the values passed to it. It is array-like: it has numbered indexes and a length, but not array methods like map. NodeLists, HTMLCollections and strings are array-like too. Convert them with Array.from() or spread.

    function oldSum() {
      console.log(arguments.length, Array.isArray(arguments));
      return Array.from(arguments).reduce((a, b) => a + b, 0);
    }
    console.log(oldSum(1, 2, 3));
    
    const modernSum = (...nums) => nums.reduce((a, b) => a + b, 0);
    console.log(modernSum(1, 2, 3));
    
    const arrayLike = { 0: "a", 1: "b", length: 2 };
    console.log(Array.from(arrayLike), Array.from({ length: 3 }, (_, i) => i * i));

    Output:

    3 false
    6
    6
    [ 'a', 'b' ] [ 0, 1, 4 ]

    Arrow functions have no arguments object of their own, so prefer rest parameters in new code.

    Q75IntermediateDOM and browser

    75. How do you create and dispatch a custom event?

    Create the event with new CustomEvent(name, { detail, bubbles }) and fire it with element.dispatchEvent(event). Listeners receive your data in event.detail. Custom events let separate parts of a page talk to each other without calling each other directly.

    document.body.innerHTML = '<div id="app"><button id="add">Add to cart</button></div>';
    const app = document.getElementById("app");
    
    app.addEventListener("cart:add", e => {
      console.log("cart updated:", e.detail.item, "x", e.detail.qty);
    });
    
    document.getElementById("add").addEventListener("click", e => {
      e.target.dispatchEvent(new CustomEvent("cart:add", {
        detail: { item: "DSA course", qty: 1 },
        bubbles: true            // needed so the parent can hear it
      }));
    });
    document.getElementById("add").click();
    
    const bus = new EventTarget();   // works outside the DOM too
    bus.addEventListener("ping", () => console.log("pong"));
    bus.dispatchEvent(new Event("ping"));

    Output:

    cart updated: DSA course x 1
    pong

    Custom events do not bubble unless you set bubbles: true. dispatchEvent is synchronous: the listeners run before it returns. EventTarget can also be used on its own as a small event bus.

    JavaScript interview questions for experienced developers

    These 25 questions are for senior front-end and full-stack developers: rendering and the event loop, memory and garbage collection, polyfills you may be asked to write, Proxy and iterators, design patterns, workers, security, performance and the newest language features.

    Q76ExperiencedAsync

    76. How does the event loop work with rendering and requestAnimationFrame?

    In a browser, one turn of the event loop is: run one macrotask, drain the microtask queue, and then, if it is time for a new frame (about every 16.7 ms on a 60 Hz screen), run requestAnimationFrame callbacks, recalculate styles and layout, and paint. Rendering can only happen between tasks, never in the middle of your code.

    • A long task (anything over 50 ms) blocks input and painting, which shows up as poor INP (Interaction to Next Paint) in Core Web Vitals.
    • Microtasks run before rendering, so an endless chain of promises freezes the page just like a while(true) loop.
    • Use requestAnimationFrame for visual updates, so they happen once per frame, right before paint. setTimeout(fn, 16) drifts and can run twice in one frame or skip frames.
    • Split long work into chunks and yield in between with await scheduler.yield() (where supported), setTimeout(..., 0) or a MessageChannel, or move it to a Web Worker.
    // Yielding to the browser while processing a large list
    async function processAll(items) {
      let lastYield = performance.now();
      for (const item of items) {
        process(item);
        if (performance.now() - lastYield > 40) {        // keep each task short
          await new Promise(r => setTimeout(r, 0));     // let the browser paint and handle input
          lastYield = performance.now();
        }
      }
    }
    
    // Smooth animation: one update per frame
    function animate(el, start = performance.now()) {
      requestAnimationFrame(now => {
        const t = Math.min((now - start) / 500, 1);
        el.style.transform = `translateX(${t * 300}px)`;
        if (t < 1) animate(el, start);
      });
    }
    Q77ExperiencedPerformance

    77. What causes memory leaks in JavaScript and how do you find them?

    JavaScript frees memory automatically, but only for objects that are no longer reachable. A leak happens when your code keeps a reference to something it no longer needs. Common causes:

    • Forgotten timers and listeners: a setInterval or a window/document listener that is never cleared keeps its callback and everything the callback closes over.
    • Detached DOM nodes: elements removed from the page but still referenced from an array, a Map or a closure.
    • Ever-growing caches: a Map or object used as a cache with no limit or expiry.
    • Closures holding large data: a small callback that keeps a big array alive.
    • Accidental globals: assigning to an undeclared variable outside strict mode.
    • Subscriptions: WebSockets, observers and store subscriptions that are not unsubscribed when a component unmounts.
    // React: always clean up in the effect's return function
    useEffect(() => {
      const id = setInterval(refresh, 5000);
      const onResize = () => setWidth(window.innerWidth);
      window.addEventListener("resize", onResize);
      const controller = new AbortController();
      fetch("/api/stats", { signal: controller.signal }).then(r => r.json()).then(setStats);
    
      return () => {
        clearInterval(id);
        window.removeEventListener("resize", onResize);
        controller.abort();
      };
    }, []);

    To find a leak, use the Chrome DevTools Memory panel: take a heap snapshot, repeat the suspicious action several times, take another snapshot and compare them. Look for counts that only grow, and search for “Detached” to find DOM nodes that are no longer on the page. The Performance panel’s memory graph shows a staircase pattern when memory is never released.

    Q78ExperiencedPerformance

    78. How does garbage collection work in JavaScript?

    Modern engines use mark-and-sweep. Starting from the roots (global objects, the current call stack, active closures), the collector marks every object it can reach by following references. Anything not marked is unreachable and is freed. Because it is based on reachability, circular references are not a problem: two objects that point to each other but nothing else are collected.

    V8 makes this fast with a generational design. New objects go into a small young generation that is collected often and cheaply (most objects die young), and objects that survive a couple of collections move to the old generation, which is collected less often. Much of the work runs incrementally and on background threads to keep pauses short.

    let user = { name: "Riya" };
    let admin = user;          // two references to one object
    user = null;
    console.log(admin.name);   // still reachable through admin
    admin = null;              // now unreachable: can be collected
    
    function makeCycle() {
      const a = {}, b = {};
      a.other = b;
      b.other = a;             // a cycle, but unreachable after return
      return "cycle created";
    }
    console.log(makeCycle());

    Output:

    Riya
    cycle created

    You cannot force or time garbage collection from normal code. WeakMap, WeakSet and WeakRef let you hold references that do not keep objects alive.

    Q79ExperiencedAsync

    79. Implement Promise.all from scratch.

    function promiseAll(items) {
      return new Promise((resolve, reject) => {
        const list = Array.from(items);
        const results = new Array(list.length);
        let remaining = list.length;
        if (remaining === 0) return resolve(results);
    
        list.forEach((item, i) => {
          Promise.resolve(item).then(value => {   // also accepts plain values
            results[i] = value;                   // keep input order
            if (--remaining === 0) resolve(results);
          }, reject);                              // first rejection wins
        });
      });
    }
    
    const wait = (ms, v) => new Promise(r => setTimeout(() => r(v), ms));
    promiseAll([wait(30, "slow"), 42, wait(10, "fast")]).then(r => console.log(r));
    promiseAll([wait(10, 1), Promise.reject(new Error("boom"))]).catch(e => console.log("rejected:", e.message));
    promiseAll([]).then(r => console.log("empty:", r));

    Output:

    empty: []
    rejected: boom
    [ 'slow', 42, 'fast' ]

    The points interviewers check: results stay in input order even if promises settle in a different order, plain values are wrapped with Promise.resolve, an empty input resolves immediately, and the first rejection rejects the whole thing. A follow-up is allSettled, where you push { status, value } or { status, reason } objects and never reject.

    Q80ExperiencedObjects and this

    80. Implement Function.prototype.bind yourself.

    Function.prototype.myBind = function (context, ...preset) {
      const fn = this;
      if (typeof fn !== "function") throw new TypeError("myBind must be called on a function");
      function bound(...later) {
        // when called with new, ignore context and use the new object
        const self = this instanceof bound ? this : context;
        return fn.apply(self, [...preset, ...later]);
      }
      bound.prototype = Object.create(fn.prototype);
      return bound;
    };
    
    function greet(greeting, mark) { return `${greeting}, ${this.name}${mark}`; }
    const hi = greet.myBind({ name: "Riya" }, "Hi");
    console.log(hi("!"));
    
    function Point(x, y) { this.x = x; this.y = y; }
    const AtOrigin = Point.myBind(null, 0);
    const p = new AtOrigin(5);
    console.log(p.x, p.y, p instanceof Point);

    Output:

    Hi, Riya!
    0 5 true

    The simple answer, return (...args) => fn.apply(context, [...preset, ...args]), handles this and partial arguments. The full answer also supports new: a bound function used as a constructor ignores the bound this, which is why the check this instanceof bound is there. The same idea gives you polyfills for call and apply: temporarily attach the function to the context object as a Symbol-keyed property and call it as a method.

    Q81ExperiencedObjects and arrays

    81. Write a deep clone function that handles nested objects and circular references.

    function deepClone(value, seen = new WeakMap()) {
      if (value === null || typeof value !== "object") return value;   // primitives and functions
      if (seen.has(value)) return seen.get(value);                     // circular reference
      if (value instanceof Date) return new Date(value);
      if (value instanceof RegExp) return new RegExp(value.source, value.flags);
      if (value instanceof Map) {
        const m = new Map(); seen.set(value, m);
        value.forEach((v, k) => m.set(deepClone(k, seen), deepClone(v, seen)));
        return m;
      }
      if (value instanceof Set) {
        const s = new Set(); seen.set(value, s);
        value.forEach(v => s.add(deepClone(v, seen)));
        return s;
      }
      const copy = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
      seen.set(value, copy);
      for (const key of Reflect.ownKeys(value)) copy[key] = deepClone(value[key], seen);
      return copy;
    }
    
    const original = { name: "Riya", joined: new Date(2024, 0, 15), tags: new Set(["js"]), address: { city: "Surat" } };
    original.self = original;
    const copy = deepClone(original);
    copy.address.city = "Pune";
    console.log(original.address.city, copy.address.city);
    console.log(copy.self === copy, copy.joined instanceof Date, copy.tags.has("js"));

    Output:

    Surat Pune
    true true true

    The WeakMap remembers objects that are already copied, which handles circular references and objects that appear twice. Reflect.ownKeys also copies Symbol keys. In real code, prefer the built-in structuredClone(), which handles Dates, Maps, Sets, typed arrays and cycles, but not functions, DOM nodes or class prototypes.

    Q82ExperiencedObjects and this

    82. What are Proxy and Reflect?

    A Proxy wraps an object and lets you intercept basic operations on it, such as reading, writing, deleting and checking properties, through handler functions called traps. Reflect has one method for each trap that performs the default behaviour, so a trap can do its extra work and then forward the operation.

    function validated(target, rules) {
      return new Proxy(target, {
        set(obj, key, value, receiver) {
          if (rules[key] && !rules[key](value)) throw new TypeError(`Invalid value for ${key}: ${value}`);
          console.log(`set ${key} = ${value}`);
          return Reflect.set(obj, key, value, receiver);
        },
        get(obj, key, receiver) {
          if (!(key in obj)) return `<no ${String(key)}>`;
          return Reflect.get(obj, key, receiver);
        }
      });
    }
    
    const user = validated({}, { age: v => Number.isInteger(v) && v >= 0 });
    user.name = "Riya";
    user.age = 22;
    try { user.age = -4; } catch (e) { console.log(e.message); }
    console.log(user.age, user.email);

    Output:

    set name = Riya
    set age = 22
    Invalid value for age: -4
    22 <no email>

    Vue 3’s reactivity system is built on Proxy: the get trap records which component used a property, and the set trap re-renders it. Other uses are validation, default values, logging, access control and negative array indexes. Proxies are slower than plain objects, so avoid them in hot loops.

    Q83ExperiencedObjects and this

    83. What are property descriptors and Object.defineProperty()?

    Every property has a descriptor with these flags: value, writable, enumerable and configurable (or get and set for accessor properties). Normal assignment sets all flags to true, while Object.defineProperty defaults them to false.

    "use strict";
    const product = { name: "Course" };
    Object.defineProperty(product, "id", { value: 101, writable: false, enumerable: false });
    Object.defineProperty(product, "label", {
      get() { return this.name.toUpperCase() + " #" + this.id; },
      enumerable: true
    });
    
    console.log(product.id, product.label);
    console.log(Object.keys(product), JSON.stringify(product));
    try { product.id = 5; } catch (e) { console.log(e.constructor.name, "- id is read-only"); }
    console.log(Object.getOwnPropertyDescriptor(product, "name"));

    Output:

    101 COURSE #101
    [ 'name', 'label' ] {"name":"Course","label":"COURSE #101"}
    TypeError - id is read-only
    { value: 'Course', writable: true, enumerable: true, configurable: true }

    This is how built-in methods such as Array.prototype.map are kept out of for…in loops (they are not enumerable), and how Object.freeze works (it sets writable and configurable to false on every property). Vue 2 used getters and setters defined this way for its reactivity.

    Q84ExperiencedES6+

    84. What are iterators and the iterable protocol?

    An object is iterable if it has a [Symbol.iterator]() method that returns an iterator, an object with a next() method that returns { value, done }. for…of, spread, destructuring, Array.from, Promise.all and new Map/Set all use this protocol.

    class Playlist {
      constructor(...songs) { this.songs = songs; }
      [Symbol.iterator]() {
        let i = 0;
        const songs = this.songs;
        return {
          next: () => i < songs.length ? { value: `${i + 1}. ${songs[i++]}`, done: false } : { value: undefined, done: true }
        };
      }
    }
    const p = new Playlist("Intro", "Closures", "Event loop");
    for (const s of p) console.log(s);
    console.log([...p].length);
    
    const [first] = p;
    console.log(first);
    
    class Countdown {
      constructor(n) { this.n = n; }
      *[Symbol.iterator]() { for (let i = this.n; i > 0; i--) yield i; }   // generator shortcut
    }
    console.log([...new Countdown(3)]);

    Output:

    1. Intro
    2. Closures
    3. Event loop
    3
    1. Intro
    [ 3, 2, 1 ]

    Writing the iterator by hand shows you understand the protocol; in practice a generator method (*[Symbol.iterator]()) is shorter. Iterators are lazy, so they can describe large or infinite sequences without building an array.

    Q85ExperiencedAsync

    85. What are async iterators and for await…of?

    An async iterator is like a normal iterator, but next() returns a promise. Objects that have [Symbol.asyncIterator], including async generators (async function*), can be consumed with for await...of. They are a natural fit for data that arrives over time: paginated APIs, streams and event sources.

    const fakeApi = page => new Promise(r => setTimeout(() => r({
      items: [`item ${page * 2 - 1}`, `item ${page * 2}`],
      next: page < 3 ? page + 1 : null
    }), 30));
    
    async function* allItems() {
      let page = 1;
      while (page) {
        const res = await fakeApi(page);
        console.log("fetched page", page);
        yield* res.items;
        page = res.next;
      }
    }
    
    (async () => {
      for await (const item of allItems()) {
        console.log("  got", item);
        if (item === "item 5") break;      // stops fetching more pages
      }
      console.log("done");
    })();

    Output:

    fetched page 1
      got item 1
      got item 2
    fetched page 2
      got item 3
      got item 4
    fetched page 3
      got item 5
    done

    Breaking out of for await calls the generator’s return(), so no more pages are fetched. In Node.js, readable streams are async iterables, so for await (const chunk of stream) reads a file chunk by chunk. Array.fromAsync() (ES2024) collects an async iterable into an array.

    Q86ExperiencedDesign patterns

    86. Implement an event emitter (observer pattern).

    class EventEmitter {
      #events = new Map();
      on(name, fn) {
        if (!this.#events.has(name)) this.#events.set(name, new Set());
        this.#events.get(name).add(fn);
        return () => this.off(name, fn);           // handy unsubscribe function
      }
      off(name, fn) { this.#events.get(name)?.delete(fn); }
      once(name, fn) {
        const wrapper = (...args) => { this.off(name, wrapper); fn(...args); };
        return this.on(name, wrapper);
      }
      emit(name, ...args) {
        const fns = this.#events.get(name);
        if (!fns) return false;
        [...fns].forEach(fn => fn(...args));        // copy: listeners may unsubscribe while we loop
        return true;
      }
    }
    
    const orders = new EventEmitter();
    const stop = orders.on("placed", o => console.log("email for order", o.id));
    orders.once("placed", o => console.log("first order bonus for", o.id));
    orders.emit("placed", { id: 1 });
    orders.emit("placed", { id: 2 });
    stop();
    console.log(orders.emit("placed", { id: 3 }), orders.emit("cancelled"));

    Output:

    email for order 1
    first order bonus for 1
    email for order 2
    true false

    This is the observer (publish-subscribe) pattern behind Node.js’s EventEmitter, DOM events and state libraries. Details interviewers look for: returning an unsubscribe function, a correct once(), copying the listener list before looping, and using a Set so the same listener is not added twice.

    Q87ExperiencedDesign patterns

    87. Which design patterns are common in JavaScript?

    PatternIdeaWhere you see it
    ModuleKeep state private and expose a small public APIES modules, IIFE modules, closures
    SingletonOne shared instanceA database connection, a store, a logger
    FactoryA function that creates and returns objectsReact.createElement, document.createElement
    Observer / Pub-SubSubscribers are notified of changesEventEmitter, DOM events, RxJS, Redux subscribe
    Decorator / Higher-order functionWrap something to add behaviourdebounce, memoize, higher-order components, middleware
    ProxyControl access to an objectVue reactivity, validation, API clients
    StrategySwap an algorithm at run timePayment methods, sort comparators, form validators
    // Singleton with a module-level instance
    const Config = (() => {
      let instance;
      return { get() { return instance ??= { env: "prod", createdAt: Date.now() }; } };
    })();
    console.log(Config.get() === Config.get());
    
    // Strategy: pick the behaviour at run time
    const shipping = {
      standard: kg => 40 + kg * 10,
      express: kg => 99 + kg * 20,
      pickup: () => 0
    };
    const cost = (method, kg) => (shipping[method] ?? shipping.standard)(kg);
    console.log(cost("standard", 2), cost("express", 2), cost("pickup", 2));

    Output:

    true
    60 139 0
    Q88ExperiencedDOM and browser

    88. What are Web Workers and when would you use them?

    A Web Worker runs a script on a separate background thread, so heavy CPU work does not freeze the page. Workers cannot touch the DOM; they talk to the page by sending messages with postMessage. The data is copied with the structured clone algorithm, unless you transfer ownership of an ArrayBuffer, which avoids the copy.

    // main.js
    const worker = new Worker(new URL("./prime-worker.js", import.meta.url), { type: "module" });
    worker.postMessage({ limit: 5_000_000 });
    worker.onmessage = e => console.log("primes found:", e.data.count);   // the UI stays responsive
    worker.onerror = e => console.error(e.message);
    
    // prime-worker.js
    self.onmessage = e => {
      const { limit } = e.data;
      const sieve = new Uint8Array(limit + 1);
      let count = 0;
      for (let i = 2; i <= limit; i++) {
        if (sieve[i]) continue;
        count++;
        for (let j = i * i; j <= limit; j += i) sieve[j] = 1;
      }
      self.postMessage({ count });
    };

    Use workers for image and video processing, parsing large files, encryption, search indexing and running WebAssembly. Shared workers are shared by several tabs of the same site, and SharedArrayBuffer with Atomics allows real shared memory (it needs cross-origin isolation headers). The “Run” buttons on this page use a worker, which is why an endless loop in your code can be stopped.

    Q89ExperiencedDOM and browser

    89. What is a service worker?

    A service worker is a background script that sits between your web app and the network. It can intercept every request the page makes and answer from a cache, which enables offline support and instant repeat loads. It also handles push notifications and background sync. Service workers are the core of a Progressive Web App (PWA), and they only work on HTTPS (or localhost).

    // register (in the page)
    if ("serviceWorker" in navigator) navigator.serviceWorker.register("/sw.js");
    
    // sw.js: cache-first for static files, network-first for the API
    const CACHE = "static-v3";
    self.addEventListener("install", e => {
      e.waitUntil(caches.open(CACHE).then(c => c.addAll(["/", "/app.css", "/app.js"])));
    });
    self.addEventListener("activate", e => {
      e.waitUntil(caches.keys().then(keys => Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k)))));
    });
    self.addEventListener("fetch", e => {
      const url = new URL(e.request.url);
      if (url.pathname.startsWith("/api/")) {
        e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
      } else {
        e.respondWith(caches.match(e.request).then(hit => hit || fetch(e.request)));
      }
    });

    Lifecycle: install, then waiting (until no open tab uses the old version), then activate. Forgetting about the waiting step is the usual reason “my update is not showing”. Unlike a Web Worker, a service worker is event driven and the browser stops it when it is idle, so it must not keep state in variables.

    Q90ExperiencedDOM and browser

    90. What is CORS?

    Browsers follow the same-origin policy: a page can only read responses from its own origin (the same protocol, host and port). CORS (Cross-Origin Resource Sharing) is how a server tells the browser that another origin is allowed to read its responses, using response headers such as Access-Control-Allow-Origin.

    • Simple requests (GET, HEAD or POST with basic headers and content types) are sent directly, and the browser checks the response headers before letting your code read the response.
    • Preflighted requests (PUT, DELETE, JSON bodies, custom headers such as Authorization) first send an OPTIONS request. The server must reply with Access-Control-Allow-Methods and Access-Control-Allow-Headers.
    • To send cookies across origins, the client sets credentials: "include", and the server must name the exact origin (not *) and send Access-Control-Allow-Credentials: true.

    CORS is enforced by the browser, not the server: the request still reaches the server, and tools like curl or Postman ignore CORS completely. So CORS is not a security layer for your API; authentication is. The fix for a CORS error is always on the server (or a proxy on your own origin), never in the front-end code.

    Q91ExperiencedDOM and browser

    91. How do you protect a web app from XSS and CSRF?

    XSS (cross-site scripting) is when an attacker gets their script to run on your page, usually through user input that you insert as HTML. That script can then read data, act as the user and steal tokens kept in localStorage.

    document.body.innerHTML = '<p id="out"></p>';
    const comment = '<img src="data:," onerror="console.log(\'XSS ran!\')">';
    const out = document.getElementById("out");
    
    out.textContent = comment;            // safe: shown as plain text
    console.log("textContent stored:", out.innerHTML.slice(0, 20) + "...");
    
    out.innerHTML = comment;              // unsafe: the browser parses the HTML
    console.log("innerHTML inserted an", out.firstChild.nodeName);
    setTimeout(() => {}, 300);           // give the broken image time to fire onerror

    Output:

    textContent stored: &lt;img src="data:,"...
    innerHTML inserted an IMG
    XSS ran!
    • Insert user data with textContent, not innerHTML. Frameworks such as React escape values for you, unless you use dangerouslySetInnerHTML.
    • If you must render user HTML, sanitise it with a library such as DOMPurify.
    • Add a Content-Security-Policy header that blocks inline scripts and unknown script sources.
    • Keep session tokens in HttpOnly cookies, which scripts cannot read.

    CSRF (cross-site request forgery) tricks a logged-in user’s browser into sending a request to your site from another site, with the user’s cookies attached. Defend with SameSite=Lax or Strict cookies, anti-CSRF tokens on forms that change data, and by checking the Origin header on the server.

    Q92ExperiencedPerformance

    92. What are reflow and repaint? How do you avoid layout thrashing?

    Reflow (layout) is when the browser recalculates the size and position of elements. Repaint redraws pixels without changing layout, for example after a colour change. Changes to transform and opacity can often skip both and run on the compositor, which is why they are best for animations.

    Layout thrashing happens when code alternates between writing styles and reading layout values (offsetHeight, getBoundingClientRect, scrollTop). Each read forces the browser to do the pending layout immediately, many times in one frame.

    // Slow: read, write, read, write... forces a layout on every iteration
    for (const box of boxes) {
      box.style.width = box.parentNode.offsetWidth / 2 + "px";
    }
    
    // Fast: do all the reads first, then all the writes
    const widths = boxes.map(box => box.parentNode.offsetWidth);
    boxes.forEach((box, i) => { box.style.width = widths[i] / 2 + "px"; });
    
    // Build many nodes off-page, then insert them once
    const frag = document.createDocumentFragment();
    for (const item of items) {
      const li = document.createElement("li");
      li.textContent = item.name;
      frag.appendChild(li);
    }
    list.appendChild(frag);

    Other habits that help: change a class instead of many inline styles, use content-visibility: auto and virtualised lists for long pages, and give images a width and height so the layout does not shift as they load (CLS).

    Q93ExperiencedPerformance

    93. What is the virtual DOM and how do frameworks update the UI?

    The virtual DOM is a lightweight JavaScript description of the UI. When state changes, React renders a new virtual tree, compares it with the previous one (diffing or reconciliation) and applies only the differences to the real DOM, in one batch.

    • Diffing assumes that elements of different types produce different trees, and uses the key prop to match list items between renders. That is why keys must be stable and unique, and array indexes are a bad key when items can be reordered or removed.
    • The virtual DOM is not automatically faster than careful manual DOM code. Its benefit is that you describe the UI as a function of state, and the framework works out a reasonably efficient set of updates.
    • Other frameworks skip the virtual DOM. Svelte compiles components into direct DOM updates, and Solid, Vue’s Vapor mode and Angular signals use fine-grained reactivity that updates exactly the nodes that depend on a changed value.

    Follow-ups you may get: React batches state updates, React Fiber splits rendering into small units that can be paused so input stays responsive, and React.memo, useMemo and useCallback skip unnecessary re-renders (that is memoization, question 54).

    Q94ExperiencedES6+

    94. What are tagged template literals?

    A tagged template is a function call written as tag`text ${value}`. The function receives the literal string parts as an array and the interpolated values as separate arguments, and it can return anything. Libraries use this for safe escaping and for embedded languages.

    function html(strings, ...values) {
      const escape = v => String(v).replace(/[&<>"']/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
      return strings.reduce((out, str, i) => out + str + (i < values.length ? escape(values[i]) : ""), "");
    }
    
    const name = "<script>alert(1)</script>";
    console.log(html`<p>Hello ${name}</p>`);
    
    function inspect(strings, ...values) { return { strings, values }; }
    console.log(inspect`a${1}b${2}c`);
    console.log(String.raw`C:\new\table`);

    Output:

    <p>Hello &lt;script&gt;alert(1)&lt;/script&gt;</p>
    { strings: [ 'a', 'b', 'c' ], values: [ 1, 2 ] }
    C:\new\table

    Real examples: styled-components and Emotion (styled.div`...`), GraphQL’s gql`...`, lit-html, and SQL libraries that turn sql`SELECT * FROM users WHERE id = ${id}` into a parameterised query, which prevents SQL injection. String.raw is the built-in tag that leaves backslashes unprocessed.

    Q95ExperiencedObjects and this

    95. What are private class fields and static blocks?

    Fields and methods whose names start with # are truly private: the language enforces that they can only be used inside the class body. That is stronger than the old convention of an underscore prefix, or of hiding state in closures. static members belong to the class itself, and a static { } block runs once when the class is defined.

    class BankAccount {
      static #count = 0;
      static bankName;
      static { BankAccount.bankName = "CD Bank"; }       // static initialisation block
    
      #balance = 0;
      constructor(owner) { this.owner = owner; BankAccount.#count++; }
      deposit(amount) { this.#validate(amount); this.#balance += amount; return this; }
      #validate(n) { if (n <= 0) throw new RangeError("Amount must be positive"); }
      get balance() { return this.#balance; }
      static get count() { return BankAccount.#count; }
      static isAccount(obj) { return #balance in obj; }   // brand check
    }
    
    const a = new BankAccount("Riya").deposit(500).deposit(250);
    console.log(a.balance, BankAccount.count, BankAccount.bankName);
    console.log(Object.keys(a), a["#balance"]);           // not a normal property
    console.log(BankAccount.isAccount(a), BankAccount.isAccount({ balance: 1 }));

    Output:

    750 1 CD Bank
    [ 'owner' ] undefined
    true false

    Writing a.#balance outside the class is a SyntaxError, before the code even runs. Private fields are not inherited in a usable way by subclasses (they cannot read them), and Proxies cannot see them.

    Q96ExperiencedAsync

    96. How do you cancel async work with AbortController?

    An AbortController has a signal that you pass to cancellable APIs, and an abort() method. fetch, addEventListener, many Node.js APIs and your own functions can listen to the signal. A common use is cancelling an old search request when the user types again, so a slow old response cannot overwrite a newer one.

    function sleep(ms, { signal } = {}) {
      return new Promise((resolve, reject) => {
        if (signal?.aborted) return reject(signal.reason);
        const t = setTimeout(() => resolve(`slept ${ms} ms`), ms);
        signal?.addEventListener("abort", () => { clearTimeout(t); reject(signal.reason); }, { once: true });
      });
    }
    
    const controller = new AbortController();
    sleep(500, { signal: controller.signal })
      .then(console.log)
      .catch(e => console.log("cancelled:", e.name));
    setTimeout(() => controller.abort(), 50);
    
    sleep(1000, { signal: AbortSignal.timeout(80) })
      .catch(e => console.log("timed out:", e.name));
    
    const both = AbortSignal.any([new AbortController().signal, AbortSignal.timeout(120)]);
    sleep(1000, { signal: both }).catch(e => console.log("any():", e.name));

    Output:

    cancelled: AbortError
    timed out: TimeoutError
    any(): TimeoutError

    AbortSignal.timeout(ms) gives a signal that aborts by itself, and AbortSignal.any([...]) combines several signals. Passing a signal to addEventListener removes the listener on abort, which is a tidy way to remove many listeners at once.

    Q97ExperiencedPerformance

    97. What are code splitting, lazy loading and tree shaking?

    • Code splitting breaks one large bundle into smaller chunks, so users download only the code the current page needs. Bundlers such as Vite, webpack and Rollup create a new chunk at every dynamic import().
    • Lazy loading loads a chunk, image or component only when it is needed: when a route opens, when a modal is clicked, or when the element scrolls into view.
    • Tree shaking removes exports that are never imported. It needs ES modules, because static imports can be analysed at build time, and code without side effects ("sideEffects": false in package.json helps).
    // Load a heavy library only when the user needs it
    exportBtn.addEventListener("click", async () => {
      const { jsPDF } = await import("jspdf");      // separate chunk, downloaded on first click
      new jsPDF().text("Report", 10, 10).save("report.pdf");
    });
    
    // React: route-level splitting
    const Dashboard = React.lazy(() => import("./pages/Dashboard"));
    <Suspense fallback={<Spinner />}><Dashboard /></Suspense>
    
    // Tree-shaking friendly import
    import { debounce } from "lodash-es";   // only debounce is bundled
    // import _ from "lodash";             // pulls in the whole library

    Measure before and after with a bundle analyser (for example rollup-plugin-visualizer) and the Lighthouse or WebPageTest reports. Native loading="lazy" on images and iframes gives you lazy loading without any JavaScript.

    Q98ExperiencedAsync

    98. How do you limit how many promises run at the same time?

    Promise.all starts everything at once. With 1,000 uploads or API calls, that can overload the server, hit rate limits or run out of memory. A concurrency limit (a promise pool) keeps at most N tasks running and starts the next one whenever one finishes.

    async function runWithLimit(tasks, limit) {
      const results = new Array(tasks.length);
      let next = 0;
      async function worker(id) {
        while (next < tasks.length) {
          const i = next++;                       // take the next task index
          results[i] = await tasks[i]();
          console.log(`worker ${id} finished task ${i}`);
        }
      }
      await Promise.all(Array.from({ length: Math.min(limit, tasks.length) }, (_, k) => worker(k + 1)));
      return results;
    }
    
    const job = (ms, v) => () => new Promise(r => setTimeout(() => r(v), ms));
    const tasks = [job(60, "A"), job(20, "B"), job(40, "C"), job(10, "D"), job(30, "E")];
    runWithLimit(tasks, 2).then(r => console.log(r));

    Output:

    worker 2 finished task 1
    worker 1 finished task 0
    worker 2 finished task 2
    worker 1 finished task 3
    worker 2 finished task 4
    [ 'A', 'B', 'C', 'D', 'E' ]

    Results stay in input order even though tasks finish in a different order. Because JavaScript is single-threaded, next++ cannot be interrupted, so no lock is needed. In production you would add error handling (stop or collect failures) and retries with backoff, or use a library such as p-limit.

    Q99ExperiencedES6+

    99. Which new JavaScript features (ES2022 to ES2025) should you know?

    FeatureYearExample
    at()ES2022arr.at(-1) for the last element
    Top-level await, class fields, #private, Object.hasOwn, error causeES2022
    findLast, toSorted, toReversed, toSpliced, withES2023Non-mutating array methods
    Object.groupBy, Map.groupBy, Promise.withResolversES2024
    Set methods (union, intersection, difference…), iterator helpers, RegExp.escape, Promise.tryES2025
    const nums = [5, 12, 8, 130, 44];
    console.log(nums.at(-1), nums.findLast(n => n < 10));
    console.log(nums.toSorted((a, b) => a - b), nums.with(0, 99), nums);
    
    const people = [{ name: "Riya", dept: "Tech" }, { name: "Aman", dept: "Sales" }, { name: "Neha", dept: "Tech" }];
    const byDept = Object.groupBy(people, p => p.dept);
    console.log(Object.keys(byDept), byDept.Tech.map(p => p.name));
    
    const { promise, resolve } = Promise.withResolvers();
    promise.then(v => console.log("resolved with", v));
    resolve("ok");
    
    const a = new Set([1, 2, 3]), b = new Set([2, 3, 4]);
    console.log([...a.union(b)], [...a.intersection(b)], [...a.difference(b)]);

    Output:

    44 8
    [ 5, 8, 12, 44, 130 ] [ 99, 12, 8, 130, 44 ] [ 5, 12, 8, 130, 44 ]
    [ 'Tech', 'Sales' ] [ 'Riya', 'Neha' ]
    [ 1, 2, 3, 4 ] [ 2, 3 ] [ 1 ]
    resolved with ok

    Check support before using the newest features in production: Object.groupBy and the Set methods need a recent browser (and Node.js 21+ and 22+ respectively), so older targets need a polyfill such as core-js.

    Q100ExperiencedPerformance

    100. How would you find and fix a slow web page?

    1. Measure first. Run Lighthouse or PageSpeed Insights for lab data, and check real-user data (Core Web Vitals in Search Console or CrUX): LCP for loading, INP for responsiveness, CLS for layout shifts.
    2. Loading (LCP): compress and resize images (WebP or AVIF, srcset), preload the main image and fonts, use a CDN, cache with long-lived headers, and cut render-blocking CSS and JavaScript (defer, code splitting).
    3. Responsiveness (INP): use the Performance panel to find long tasks. Break them up, debounce input handlers, move heavy work to a worker, and avoid layout thrashing.
    4. Bundle size: analyse the bundle, remove unused or duplicate libraries, lazy load routes and heavy widgets, and prefer smaller alternatives (for example date-fns or Day.js instead of Moment).
    5. Rendering: virtualise long lists, memoise expensive components, and avoid re-rendering the whole page for small state changes.
    6. Network: fewer requests, HTTP/2 or HTTP/3, caching API responses, and showing data as it streams in.
    7. Verify the improvement with the same measurement, and add a performance budget to CI so it does not slowly get worse again.

    In an interview, walk through a real example: “LCP was 4.1 s because the hero image was a 2 MB PNG; we served a 120 KB WebP with preload and LCP dropped to 1.8 s.” Numbers make the answer convincing.

    JavaScript coding interview questions: 20 problems with tests

    Front-end interviews often include a short coding task. These 20 problems are the ones asked most often, from reversing a string to writing debounce and Promise.all yourself. Complete the function and press Run tests: the page runs your code on several inputs and shows which tests passed. Your code and your progress are saved in this browser.

    Try each problem for at least ten minutes before you open “Show solution”. Several of them are explained in the questions above, so you can check the idea there first.

    Practice

    Your progress

    Done
    0 / 20

    Easy JavaScript coding questions

    Strings and arrays: the warm-up questions in most rounds.

    P1Easy

    1. Reverse a string

    Write reverseString(s) that returns the string reversed.

    Example: reverseString("hello") → "olleh"

    Show solution
    function reverseString(s) {
      return [...s].reverse().join("");
    }
    P2Easy

    2. Check a palindrome

    Write isPalindrome(s) that returns true if the string reads the same backwards, ignoring case, spaces and punctuation.

    Example: isPalindrome("Madam") → true

    Show solution
    function isPalindrome(s) {
      const clean = s.toLowerCase().replace(/[^a-z0-9]/g, "");
      return clean === [...clean].reverse().join("");
    }
    P3Easy

    3. Count vowels

    Write countVowels(s) that returns how many vowels (a, e, i, o, u, in either case) the string has.

    Example: countVowels("JavaScript") → 3

    Show solution
    function countVowels(s) {
      return (s.match(/[aeiou]/gi) || []).length;
    }
    P4Easy

    4. Largest number in an array

    Write largest(arr) that returns the largest number in a non-empty array, without using Math.max or sorting.

    Example: largest([3, 9, 2]) → 9

    Show solution
    function largest(arr) {
      let max = arr[0];
      for (const n of arr) if (n > max) max = n;
      return max;
    }
    P5Easy

    5. Capitalise every word

    Write capitalize(s) that makes the first letter of every word upper case and the rest lower case. Words are separated by single spaces.

    Example: capitalize("hello world") → "Hello World"

    Show solution
    function capitalize(s) {
      return s.split(" ").map(w => w ? w[0].toUpperCase() + w.slice(1).toLowerCase() : w).join(" ");
    }
    P6Easy

    6. Remove duplicates

    Write unique(arr) that returns a new array without duplicates, keeping the first occurrence of each value in its original order.

    Example: unique([1, 2, 2, 3, 1]) → [1, 2, 3]

    Show solution
    function unique(arr) {
      return [...new Set(arr)];
    }
    P7Easy

    7. FizzBuzz

    Write fizzBuzz(n) that returns an array for the numbers 1 to n: “Fizz” for multiples of 3, “Buzz” for multiples of 5, “FizzBuzz” for multiples of both, and the number itself otherwise.

    Example: fizzBuzz(5) → [1, 2, "Fizz", 4, "Buzz"]

    Show solution
    function fizzBuzz(n) {
      const out = [];
      for (let i = 1; i <= n; i++) {
        out.push(i % 15 === 0 ? "FizzBuzz" : i % 3 === 0 ? "Fizz" : i % 5 === 0 ? "Buzz" : i);
      }
      return out;
    }

    Medium JavaScript coding questions

    Higher-order functions and closures: once, memoize, curry and debounce.

    P8Medium

    8. Flatten a nested array

    Write flatten(arr) that flattens an array nested to any depth, without using arr.flat().

    Example: flatten([1, [2, [3, [4]]], 5]) → [1, 2, 3, 4, 5]

    Show solution
    function flatten(arr) {
      const out = [];
      for (const x of arr) {
        if (Array.isArray(x)) out.push(...flatten(x));
        else out.push(x);
      }
      return out;
    }
    P9Medium

    9. Split an array into chunks

    Write chunk(arr, size) that splits an array into groups of size. The last group can be smaller.

    Example: chunk([1, 2, 3, 4, 5], 2) → [[1, 2], [3, 4], [5]]

    Show solution
    function chunk(arr, size) {
      const out = [];
      for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
      return out;
    }
    P10Medium

    10. Group by a key

    Write groupBy(arr, fn) that returns an object whose keys are the results of fn(item) and whose values are arrays of the matching items, in their original order.

    Example: groupBy([1, 2, 3, 4], n => n % 2 ? "odd" : "even") → {"odd": [1, 3], "even": [2, 4]}

    Show solution
    function groupBy(arr, fn) {
      return arr.reduce((acc, item) => {
        const k = fn(item);
        (acc[k] ||= []).push(item);
        return acc;
      }, {});
    }
    P11Medium

    11. Check an anagram

    Write isAnagram(a, b) that returns true if the two words use exactly the same letters, ignoring case.

    Example: isAnagram("listen", "silent") → true

    Show solution
    function isAnagram(a, b) {
      const norm = s => [...s.toLowerCase()].sort().join("");
      return a.length === b.length && norm(a) === norm(b);
    }
    P12Medium

    12. Run a function only once

    Write once(fn) that returns a new function. The first call runs fn and returns its result; every later call returns that same first result without running fn again.

    Show solution
    function once(fn) {
      let called = false, result;
      return function (...args) {
        if (!called) { called = true; result = fn.apply(this, args); }
        return result;
      };
    }
    P13Medium

    13. Memoize a function

    Write memoize(fn) that caches results by argument list, so calling it again with the same arguments returns the cached value without calling fn.

    Show solution
    function memoize(fn) {
      const cache = new Map();
      return function (...args) {
        const key = JSON.stringify(args);
        if (!cache.has(key)) cache.set(key, fn.apply(this, args));
        return cache.get(key);
      };
    }
    P14Medium

    14. Curry a function

    Write curry(fn) so that a function of n parameters can be called with its arguments one at a time or in groups, for example curry(add3)(1)(2)(3) or curry(add3)(1, 2)(3).

    Example: curry(add3)(1)(2)(3) → 6

    Show solution
    function curry(fn) {
      return function curried(...args) {
        if (args.length >= fn.length) return fn.apply(this, args);
        return (...more) => curried.apply(this, [...args, ...more]);
      };
    }
    P15Medium

    15. Debounce

    Write debounce(fn, ms) that returns a function which delays calling fn until ms milliseconds have passed since the last call. Only the last call’s arguments are used.

    Show solution
    function debounce(fn, ms) {
      let t;
      return function (...args) {
        clearTimeout(t);
        t = setTimeout(() => fn.apply(this, args), ms);
      };
    }

    Hard JavaScript coding questions

    Recursion and promises: deep clone, Promise.all, deep equality, pipe and retry.

    P16Hard

    16. Deep clone

    Write deepClone(value) that copies nested plain objects and arrays so that changing the copy never changes the original. Do not use structuredClone or JSON.

    Show solution
    function deepClone(value) {
      if (value === null || typeof value !== "object") return value;
      if (Array.isArray(value)) return value.map(deepClone);
      const out = {};
      for (const k of Object.keys(value)) out[k] = deepClone(value[k]);
      return out;
    }
    P17Hard

    17. Implement Promise.all

    Write promiseAll(items) that behaves like Promise.all: it resolves with an array of results in input order, accepts plain values as well as promises, and rejects as soon as any promise rejects. Do not use Promise.all.

    Show solution
    function promiseAll(items) {
      return new Promise((resolve, reject) => {
        const results = [];
        let left = items.length;
        if (left === 0) return resolve(results);
        items.forEach((item, i) => {
          Promise.resolve(item).then(v => {
            results[i] = v;
            if (--left === 0) resolve(results);
          }, reject);
        });
      });
    }
    P18Hard

    18. Deep equality

    Write deepEqual(a, b) that returns true if two values have the same structure and values. Handle nested plain objects and arrays; key order does not matter.

    Example: deepEqual({ a: 1, b: [1, 2] }, { b: [1, 2], a: 1 }) → true

    Show solution
    function deepEqual(a, b) {
      if (a === b) return true;
      if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
      if (Array.isArray(a) !== Array.isArray(b)) return false;
      const ka = Object.keys(a), kb = Object.keys(b);
      if (ka.length !== kb.length) return false;
      return ka.every(k => Object.prototype.hasOwnProperty.call(b, k) && deepEqual(a[k], b[k]));
    }
    P19Hard

    19. Compose functions (pipe)

    Write pipe(...fns) that returns a function which passes its input through every function from left to right. pipe() with no functions returns the input unchanged.

    Example: pipe(x => x + 1, x => x * 2)(5) → 12

    Show solution
    function pipe(...fns) {
      return input => fns.reduce((acc, fn) => fn(acc), input);
    }
    P20Hard

    20. Retry an async function

    Write retry(fn, times) that calls the async function fn, and if it rejects, calls it again, up to times attempts in total. Resolve with the first successful result, or reject with the last error.

    Show solution
    async function retry(fn, times) {
      let lastError;
      for (let i = 0; i < times; i++) {
        try {
          return await fn();
        } catch (e) {
          lastError = e;
        }
      }
      throw lastError;
    }

    Download all 100 JavaScript interview questions as a PDF

    The PDF has the same 100 JavaScript interview questions and answers, with every code example and its output, plus the 20 coding questions with solutions, in 69 printable pages with a clickable table of contents. Use it to revise offline, on your phone, or on paper before the interview. It is free, with no sign-up.

    Free PDF

    100 JavaScript Interview Questions and Answers

    69 pages · Freshers, intermediate and experienced · 94 code examples

    Download PDF

    Frequently asked questions

    What JavaScript questions are asked in interviews for freshers?

    Freshers are most often asked about data types, var vs let vs const, hoisting, == vs ===, null vs undefined, closures, arrow functions, map, filter and reduce, promises and async/await, and basic DOM events. Questions 1 to 40 on this page cover them.

    Which JavaScript topics are most important for interviews?

    Closures, the this keyword, prototypes, promises and the event loop come up in almost every JavaScript interview, along with ES6 features and array methods. For front-end roles add DOM events, event delegation and browser storage; for senior roles add performance, security and memory leaks.

    What JavaScript coding questions are asked in interviews?

    Common ones are reversing a string, removing duplicates, flattening an array, and writing debounce, throttle, memoize, curry, deep clone and Promise.all from scratch. The 20 coding questions on this page cover these and check your answer automatically.

    How should I prepare for a JavaScript interview with 2 to 5 years of experience?

    Expect deeper questions on the event loop, promises, closures and prototypes, plus polyfills, performance (Core Web Vitals, reflow, code splitting), security (XSS, CSRF, CORS) and memory leaks. Be ready to explain a real performance or bug fix from your own project, and to write utility functions without an IDE.

    Are React questions asked in a JavaScript interview?

    For front-end roles, usually yes, often in a separate round. This page covers JavaScript itself, which React builds on: closures explain hooks, immutability explains state updates, and the event loop explains batching. React-specific questions (hooks, rendering, state management) are a separate topic.

    Can I download these JavaScript interview questions as a PDF?

    Yes. All 100 questions and answers, with every code example and its output, plus the coding questions with solutions, are in a free 69-page PDF. Use the Download PDF button at the top of this page; no sign-up is needed.

    Next steps

    Work through one level at a time and press “Mark as done” on each of the JavaScript interview questions once you can answer it out loud without looking. Run the examples and change them; predicting the output before you press Run is the fastest way to learn. Most interviews also include a DSA round and some general computer science, so continue with our DSA interview cheat sheet, OOPs interview questions, computer networks interview questions and SQL interview questions. All the best for your interview!

    JavaScript
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous Article100 Python Programs with Examples and Output (Run Online + PDF)
    Anirudh Khurana
    • Website

    Anirudh Khurana is the founder of Code and Debug, an Indian EdTech platform that helps students and working professionals crack coding interviews and move into data and AI roles. He teaches DSA, Python, SQL, data engineering and machine learning through live bootcamps and his YouTube channel, Code and Debug, which has over 50,000 subscribers. Every guide on this blog is written or reviewed by him and tested with real code.

    Related Posts

    Interview Questions

    100 Java Interview Questions and Answers (Freshers to Experienced)

    30 November 2026
    Interview Questions

    100 Machine Learning Interview Questions and Answers (Freshers to Experienced)

    25 November 2026
    Interview Questions

    100 OOPs Interview Questions and Answers (Freshers to Experienced)

    16 November 2026
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • AI & Machine Learning (8)
    • Data Structures & Algorithms (243)
      • Beginner (84)
      • Expert (52)
      • Intermediate (106)
    • Interview Questions (8)
    • Pandas (1)
    • Python (2)
    • Resume (1)
    • SQL (3)
    Recent Posts

    100 JavaScript Interview Questions and Answers (2026) + Free PDF

    2 December 2026

    100 Python Programs with Examples and Output (Run Online + PDF)

    1 December 2026

    100 Java Interview Questions and Answers (Freshers to Experienced)

    30 November 2026

    SQL Queries with Examples: Run Online, 50 Practice Questions and Free PDF

    27 November 2026

    Normalization in DBMS: 1NF, 2NF and 3NF With SQL Examples

    25 November 2026
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.