← Interview prep

JavaScript interview questions

Language fundamentals, ES features, and async behavior.

200 questions · Page 3 of 10

Want the full pack? Interview packs · Mock interview · Mentora

Page 3 of 10

Questions 41–60 of 200 · 0 of 20 on this page marked learned

41.javascript-0041Hardsenior

How do you cancel asynchronous work in JavaScript using AbortController?

An AbortController has a signal that is passed to cancellable APIs such as fetch. Calling abort() flips the signal and notifies listeners, and the API rejects with an AbortError. Your own async functions can accept a signal, listen for the abort event, and clean up. AbortSignal.timeout and AbortSignal.any combine timeouts and several reasons for cancelling.

Full answer

Promises cannot be cancelled, so cancellation needs a separate signal. The platform provides AbortController for this. The controller owns a signal property, which is an AbortSignal. The signal is handed to the work, and the controller keeps abort().

Calling controller.abort(reason) sets signal.aborted to true, stores signal.reason, and fires an abort event once. APIs that accept { signal }, such as fetch, stop and reject their promise with the reason. The default reason is a DOMException named AbortError.

To make your own function cancellable, check the signal at the start with signal.throwIfAborted(), add an abort listener that cancels the timer or request and rejects the promise, and remove the listener when the work finishes normally so it does not leak.

AbortSignal.timeout(ms) creates a signal that aborts itself after a delay, with a reason named TimeoutError. AbortSignal.any([a, b]) aborts when any of the given signals does, which combines a user cancel button with a timeout.

Uses include cancelling a search request when the user types again (avoiding out-of-order responses), cancelling work when a component is removed, and request timeouts. Cancelling does not undo side effects that already reached the server, so server operations should be idempotent or confirmed.

One signal can cancel many operations, and a signal that has already aborted stays aborted.

javascript
function delay(ms, { signal } = {}) {
  return new Promise((resolve, reject) => {
    signal?.throwIfAborted();
    const timer = setTimeout(() => {
      signal?.removeEventListener('abort', onAbort);
      resolve(`finished after ${ms} ms`);
    }, ms);
    function onAbort() {
      clearTimeout(timer);
      reject(signal.reason);
    }
    signal?.addEventListener('abort', onAbort, { once: true });
  });
}

(async () => {
  console.log(await delay(10));

  const controller = new AbortController();
  const pending = delay(200, { signal: controller.signal });
  setTimeout(() => controller.abort(), 20);
  try {
    await pending;
  } catch (error) {
    console.log('manual abort:', error.name, controller.signal.aborted);
  }

  try {
    await delay(200, { signal: AbortSignal.timeout(20) });
  } catch (error) {
    console.log('timeout:', error.name);
  }

  const userCancel = new AbortController();
  const combined = AbortSignal.any([userCancel.signal, AbortSignal.timeout(500)]);
  userCancel.abort(new Error('user pressed cancel'));
  try {
    await delay(100, { signal: combined });
  } catch (error) {
    console.log('combined:', error.message);
  }

  const reused = new AbortController();
  reused.abort();
  try {
    await delay(10, { signal: reused.signal });
  } catch (error) {
    console.log('already aborted:', error.name);
  }
})();

Run with Node.js v24.22.1 as js-41.js; two runs gave identical output. Output: finished after 10 ms manual abort: AbortError true timeout: TimeoutError combined: user pressed cancel already aborted: AbortError

Key points

  • Promises cannot cancel; a signal carries the cancel request.
  • abort() sets aborted, stores reason, and fires the abort event once.
  • Cancellable APIs reject with the reason, AbortError by default.
  • Custom async functions should check, listen, clean up, and remove their listener.
  • AbortSignal.timeout and AbortSignal.any cover timeouts and combined sources.

Common mistakes

  • Believing abort() undoes work the server already completed.
  • Forgetting to remove the abort listener after normal completion.
  • Catching the AbortError and treating it as a real failure with an error message to the user.
  • Reusing one controller after abort and expecting a new request to run.

Follow-ups

  • How would you avoid showing results from an old search request when the user types quickly?
  • How do you pass a signal through several layers of async functions?
  • What does fetch reject with when the signal times out compared with a manual abort?

Tips

  • State that promises cannot be cancelled before you show the solution.
  • Show the cleanup of timers and listeners; it is the difference between a demo and production code.
  • Mention one real case such as a search box, and the race condition it prevents.
42.javascript-0042Hardsenior

How would you run many async tasks while limiting how many run at the same time?

Start a fixed number of workers, and let each worker repeatedly take the next task from a shared index until none remain. Store each result at its task's index so the output stays in input order. This keeps at most N tasks in flight and avoids both the sequential slowdown and the overload of Promise.all over thousands of tasks.

Full answer

Running tasks one by one is slow, but starting thousands at once can exhaust sockets, memory, or an API's rate limit. A concurrency limit sits between the two.

A simple and correct design is a worker pool. Create limit async worker functions. All of them share one counter next. Each worker loops: take the current index, move the counter forward, and if the index is within the list, await that task and store the result at the same index. When the list is exhausted, the worker ends. Promise.all over the workers waits until all tasks are done. Because JavaScript runs one piece of code at a time, taking the index and incrementing it happens without any race, as no await sits between the two steps.

The tasks must be functions that return promises, not promises that already started. Starting a promise begins its work immediately, so passing started promises cannot be limited.

Design points for a senior answer: results come back in input order because of index storage. Decide the failure policy: in the sketch, the first rejection rejects the whole pool, but remaining workers still pick up new tasks unless they are stopped with a shared flag or AbortSignal. For per-task error tolerance, catch inside the task and store an error object. The time cost is roughly the total work divided by the limit.

Libraries such as p-limit and p-queue provide the same idea with more features.

javascript
async function runWithLimit(tasks, limit) {
  const results = new Array(tasks.length);
  let next = 0;

  async function worker() {
    while (true) {
      const index = next++;
      if (index >= tasks.length) return;
      results[index] = await tasks[index]();
    }
  }

  const workerCount = Math.min(limit, tasks.length);
  await Promise.all(Array.from({ length: workerCount }, worker));
  return results;
}

let active = 0;
let maxActive = 0;
const order = [];

const makeTask = (id, ms) => async () => {
  active += 1;
  maxActive = Math.max(maxActive, active);
  order.push(`start ${id}`);
  await new Promise((resolve) => setTimeout(resolve, ms));
  active -= 1;
  order.push(`end ${id}`);
  return `result ${id}`;
};

const tasks = [makeTask(1, 100), makeTask(2, 10), makeTask(3, 10), makeTask(4, 10), makeTask(5, 10)];

runWithLimit(tasks, 2).then((results) => {
  console.log(results);
  console.log('max running at once:', maxActive);
  console.log(order.join(', '));
});

Run with Node.js v24.22.1 as js-42.js; two runs gave identical output. Output: [ 'result 1', 'result 2', 'result 3', 'result 4', 'result 5' ] max running at once: 2 start 1, start 2, end 2, start 3, end 3, start 4, end 4, start 5, end 5, end 1

Key points

  • Start N workers that pull from a shared index.
  • Tasks are functions returning promises, so they start only when a worker takes them.
  • Store results by index to keep input order.
  • Decide the failure policy: stop early or collect errors.
  • Total time is about the sum of task times divided by the limit.

Common mistakes

  • Passing already started promises and expecting a limit to apply.
  • Using Promise.all over chunks of N tasks, which waits for the slowest task in every chunk.
  • Collecting results in completion order instead of input order.
  • Ignoring the failure policy, so one rejection leaves orphaned workers running.

Follow-ups

  • How would you stop all workers after the first failure?
  • How would you add retry with exponential backoff for each task?
  • How would you handle a task list that arrives as a stream?

Tips

  • Explain why the pool beats chunking: no waiting for the slowest member of a batch.
  • Say aloud that the shared index is safe because JavaScript does not interleave code between statements without await.
  • Discuss the failure policy before the interviewer asks.
43.javascript-0043Hardsenior

How does memoization work, what are its pitfalls, and how would you bound the cache?

Memoization stores the result of a function for given arguments and returns it on repeat calls. It is only safe for pure functions and needs a reliable cache key, a size or time limit, and care with async results. A Map keeps insertion order, so deleting the oldest key on overflow gives a simple bounded cache, and refreshing keys on use gives LRU behavior.

Full answer

A memoized function keeps a cache in a closure. On each call, it builds a key from the arguments. If the key is in the cache, it returns the stored value. Otherwise, it computes, stores, and returns the value. It trades memory for speed, and it fits expensive pure computations such as recursive Fibonacci, parsing, or price calculation.

Pitfalls to name:

  • The function must be pure. If the result depends on time, randomness, or outside state, cached results become wrong.
  • The key must be both unique and stable. JSON.stringify(args) is a common choice, but it drops functions and undefined, treats objects with the same fields in a different order as different keys, and is slow for large inputs. For a single primitive argument, use the argument itself. For object arguments, a WeakMap keyed by the object avoids leaks.
  • An unbounded cache is a memory leak with a good reputation. Set a maximum size or an expiry time.
  • Return values that are objects are shared. A caller who mutates the cached object changes the result for everyone.
  • this must be forwarded if the function is used as a method.

For a bounded cache, a Map iterates keys in insertion order. When the size passes the limit, delete the first key. For LRU, on every hit delete the key and set it again so it moves to the end.

For async functions, cache the promise, not the resolved value, so concurrent callers share one request. Remove the entry if the promise rejects, otherwise a temporary failure is cached forever.

javascript
function memoize(fn, { limit = Infinity, key = (...args) => JSON.stringify(args) } = {}) {
  const cache = new Map();
  const memoized = function (...args) {
    const cacheKey = key(...args);
    if (cache.has(cacheKey)) {
      const value = cache.get(cacheKey);
      cache.delete(cacheKey); // refresh position for LRU behavior
      cache.set(cacheKey, value);
      return value;
    }
    const value = fn.apply(this, args);
    cache.set(cacheKey, value);
    if (cache.size > limit) cache.delete(cache.keys().next().value);
    return value;
  };
  memoized.cache = cache;
  return memoized;
}

let computeCount = 0;
const slowSquare = memoize((n) => {
  computeCount += 1;
  return n * n;
}, { limit: 2 });

console.log(slowSquare(4), slowSquare(4), computeCount);
slowSquare(5);
slowSquare(4); // refreshes 4, so 5 is the oldest
slowSquare(6); // evicts 5
console.log([...slowSquare.cache.keys()]);
slowSquare(5);
console.log(computeCount);

const fib = memoize((n) => (n < 2 ? n : fib(n - 1) + fib(n - 2)));
console.log(fib(60));

function memoizeAsync(fn) {
  const cache = new Map();
  return (arg) => {
    if (!cache.has(arg)) {
      const promise = fn(arg).catch((error) => {
        cache.delete(arg); // do not cache failures
        throw error;
      });
      cache.set(arg, promise);
    }
    return cache.get(arg);
  };
}

let requests = 0;
const loadUser = memoizeAsync(async (id) => {
  requests += 1;
  if (id === 0) throw new Error('not found');
  return { id };
});

(async () => {
  await Promise.all([loadUser(1), loadUser(1), loadUser(1)]);
  console.log('requests for three concurrent calls:', requests);
  await loadUser(0).catch(() => {});
  await loadUser(0).catch(() => {});
  console.log('requests after two failed calls:', requests);
})();

Run with Node.js v24.22.1 as js-43.js; two runs gave identical output. Output: 16 16 1 [ '[4]', '[6]' ] 4 1548008755920 requests for three concurrent calls: 1 requests after two failed calls: 3

Key points

  • Memoization caches results by argument key inside a closure.
  • Only pure functions are safe to memoize.
  • Choose stable keys; JSON.stringify has limits.
  • Bound the cache by size or time; Map insertion order gives a simple LRU.
  • For async work, cache the promise and drop it on rejection.

Common mistakes

  • Memoizing impure functions such as ones that read the current time.
  • Using JSON.stringify keys with object arguments where key order or functions matter.
  • Leaving the cache unbounded in a long-running process.
  • Caching a rejected promise, which makes a temporary error permanent.

Follow-ups

  • How would you memoize a method that depends on this?
  • How would you add a time-to-live to each cache entry?
  • When is memoization the wrong tool, and what would you use instead?

Tips

  • State the purity requirement first. It is the first thing a reviewer will check.
  • Mention cache size limits without being asked; it separates a toy from a production answer.
  • For async functions, say "cache the promise" and explain the concurrency benefit.
44.javascript-0044Hardsenior

How do you keep an application responsive while processing a large amount of data in JavaScript?

Long synchronous work blocks the single main thread, so timers, input, and rendering wait. Fix it by splitting the work into small chunks and yielding to the event loop between them, moving heavy computation to a Web Worker or worker thread, or reducing the work with better algorithms and data structures. Measure first with the performance tools.

Full answer

Because JavaScript runs on one thread, a loop that takes 500 ms freezes the page for 500 ms. Clicks are not handled, animations stop, and timers fire late. A browser aims to produce a frame every 16 ms, and responsiveness metrics such as Interaction to Next Paint penalize long tasks, which are tasks over 50 ms.

The options, from cheapest to most involved:

  1. Do less work. Use a better algorithm, avoid repeated array scans, debounce triggers, or use virtualized lists so only visible rows are processed.
  2. Chunk the work. Process a slice of items, then yield to the event loop so other tasks can run, then continue. Yielding must use a macrotask (setTimeout, MessageChannel, or scheduler.yield() where available). A promise microtask does not help, because the microtask queue is drained before the event loop moves on.
  3. Move the work off the main thread. A Web Worker (browser) or worker_threads (Node.js) runs code in a separate thread. Data is copied with structured cloning or transferred without copying for ArrayBuffer. Workers have no DOM access.
  4. Schedule low-priority work with requestIdleCallback when it can wait.

Choose chunking when the work needs the DOM or must be simple to ship. Choose a worker for heavy pure computation such as parsing, image processing, or sorting a large data set.

Always measure with the Performance panel, and look for long tasks before changing code.

javascript
const items = Array.from({ length: 200 }, (_, i) => i + 1);
const log = [];

function heavy(n) {
  let total = 0;
  for (let i = 0; i < 50000; i++) total += (n * i) % 7;
  return total;
}

function processAllAtOnce() {
  let sum = 0;
  for (const item of items) sum += heavy(item);
  log.push('blocking run finished');
  return sum;
}

const yieldToEventLoop = () => new Promise((resolve) => setTimeout(resolve, 0));

async function processInChunks(chunkSize) {
  let sum = 0;
  for (let start = 0; start < items.length; start += chunkSize) {
    for (const item of items.slice(start, start + chunkSize)) sum += heavy(item);
    log.push(`chunk ${start / chunkSize + 1} done`);
    await yieldToEventLoop();
  }
  return sum;
}

(async () => {
  setTimeout(() => log.push('timer fired'), 0);
  const blockingSum = processAllAtOnce();
  await yieldToEventLoop();
  console.log('blocking order:', log.join(' | '));

  log.length = 0;
  setTimeout(() => log.push('timer fired'), 0);
  const chunkedSum = await processInChunks(100);
  console.log('chunked order:', log.join(' | '));
  console.log('same result:', blockingSum === chunkedSum);
})();

Run with Node.js v24.22.1 as js-44.js; two runs gave identical output. Output: blocking order: blocking run finished | timer fired chunked order: chunk 1 done | timer fired | chunk 2 done same result: true

Key points

  • Long synchronous tasks block timers, input, and rendering.
  • Yield with a macrotask between chunks; a microtask does not let other tasks run.
  • Web Workers and worker threads move computation off the main thread but cannot touch the DOM.
  • Reduce work first with better algorithms and virtualization.
  • Measure long tasks (over 50 ms) before optimizing.

Common mistakes

  • Yielding with await Promise.resolve(), which only schedules a microtask and does not let timers, input, or rendering run.
  • Chunking too small, so scheduling overhead dominates, or too large, so each chunk is itself a long task.
  • Sending huge objects to a worker with copying instead of transferring buffers.
  • Optimizing without profiling and moving the wrong work.

Follow-ups

  • How would you show a progress indicator while a worker processes a file?
  • What is the difference between requestAnimationFrame and requestIdleCallback?
  • How does scheduler.yield differ from setTimeout for yielding?

Tips

  • Start by naming the symptom: long tasks over 50 ms. It shows you know how to measure.
  • Explain why a microtask is not a valid yield point.
  • Offer two or three options and say how you would choose between them.
45.javascript-0045Hardsenior

What does the new operator do, and how would you implement it yourself?

new creates an empty object linked to the constructor's prototype, runs the constructor with this set to that object, and returns the object, unless the constructor returns another object, which then replaces it. A hand-written version uses Object.create and apply, and Reflect.construct handles classes and new.target correctly.

Full answer

Calling a function with new performs four steps.

  1. Create a new empty object whose [[Prototype]] is Constructor.prototype.
  2. Call the constructor with this bound to that object, passing the arguments.
  3. If the constructor returns an object (or function), that value is the result of the new expression.
  4. Otherwise, the new object from step 1 is the result. Returning a primitive is ignored.

Implementing this takes a few lines: const obj = Object.create(Constructor.prototype); const result = Constructor.apply(obj, args); return result !== null && (typeof result === 'object' || typeof result === 'function') ? result : obj;.

This hand-written version has limits. ES6 classes throw a TypeError when called without new, so apply fails for them. Built-in constructors such as Date or Array create special internal objects that Object.create cannot produce. Also, new.target, the value that tells a function whether it was called with new and which constructor started the call, would be undefined.

Reflect.construct(Constructor, args, newTarget) does the real construction, including new.target and the base-class behavior of extends. Arrow functions and methods are not constructors, and new on them throws.

A common defensive pattern in old code was if (!(this instanceof Person)) return new Person(name). Modern code checks new.target instead, or uses classes, which enforce new.

javascript
function myNew(Constructor, ...args) {
  const instance = Object.create(Constructor.prototype);
  const result = Constructor.apply(instance, args);
  const isObject = result !== null && (typeof result === 'object' || typeof result === 'function');
  return isObject ? result : instance;
}

function Student(name) {
  this.name = name;
}
Student.prototype.hello = function () {
  return `I am ${this.name}`;
};

const viaNew = new Student('Ria');
const viaMyNew = myNew(Student, 'Dev');
console.log(viaNew.hello(), viaMyNew.hello(), viaMyNew instanceof Student);

function ReturnsObject() {
  this.ignored = true;
  return { replaced: true };
}
function ReturnsPrimitive() {
  this.kept = true;
  return 42;
}
console.log(new ReturnsObject(), new ReturnsPrimitive());
console.log(myNew(ReturnsObject), myNew(ReturnsPrimitive));

class Course {
  constructor(title) {
    this.title = title;
  }
}
try {
  myNew(Course, 'JS');
} catch (error) {
  console.log('myNew with class:', error.name);
}
console.log(Reflect.construct(Course, ['JS']) instanceof Course);

function Shape() {
  return new.target ? 'called with new' : 'called without new';
}
console.log(Shape(), new Shape() instanceof Shape);

const date = Reflect.construct(Date, [2026, 0, 15]);
console.log(date instanceof Date, date.getFullYear());
try {
  new (() => {})();
} catch (error) {
  console.log('arrow with new:', error.name);
}

Run with Node.js v24.22.1 as js-45.js; two runs gave identical output. Output: I am Ria I am Dev true { replaced: true } ReturnsPrimitive { kept: true } { replaced: true } ReturnsPrimitive { kept: true } myNew with class: TypeError true called without new true true 2026 arrow with new: TypeError

Key points

  • new creates an object linked to Constructor.prototype, runs the constructor on it, and returns it.
  • A constructor that returns an object overrides the result; a primitive return is ignored.
  • Classes cannot be called without new, so apply-based imitation fails for them.
  • Reflect.construct supports new.target and built-in subclassing.
  • Arrow functions and methods are not constructors.

Common mistakes

  • Forgetting that returning an object from a constructor replaces the new instance.
  • Linking the prototype with the instance's __proto__ assignment instead of Object.create or Object.setPrototypeOf.
  • Implementing new with apply and assuming it works for classes and built-ins.
  • Forgetting that new.target is undefined when a function is called normally.

Follow-ups

  • What does new.target return inside a derived class constructor?
  • Why must a derived class call super before using this?
  • What happens if Constructor.prototype is not an object when you call new?

Tips

  • List the four steps in order; interviewers usually ask for exactly that.
  • Write the implementation, then volunteer its two weaknesses (classes and built-ins).
  • Mention Reflect.construct as the faithful alternative.
46.javascript-0046Hardsenior

What are property descriptors in JavaScript? Explain writable, enumerable, configurable, and accessor properties.

Every property has a descriptor. A data property has value, writable, enumerable, and configurable attributes, and an accessor property has get and set functions instead of a value. Object.defineProperty sets these attributes, and they control assignment, listing, JSON output, deletion, and later redefinition.

Full answer

A property is more than a name and a value. The engine stores attributes beside it, and Object.getOwnPropertyDescriptor(obj, key) shows them.

A data property has value and three flags. writable decides whether assignment can change the value. enumerable decides whether the key appears in for...in, Object.keys, spread, and JSON.stringify. configurable decides whether the property can be deleted and whether its attributes can be changed again. Once configurable is false, it cannot be made true again.

An accessor property has get and set functions instead of value and writable. Reading runs the getter and writing runs the setter. Getters give computed or validated values that look like plain fields. Object literals and classes both support get and set syntax. A class getter lives on the prototype, so it is not an own property of the instance. As a result it is not copied by spread, and JSON.stringify ignores it.

Object.defineProperty creates or changes a property. Attributes not given default to false when it creates a property, but keep their current values when it changes an existing one. In contrast, properties created by normal assignment have all three flags set to true.

Object.freeze and Object.seal work by changing these flags on all properties. Spread and Object.assign read through getters and copy plain values, so the copy loses the accessor behavior.

javascript
'use strict';

const product = { name: 'Notebook' };
Object.defineProperty(product, 'sku', { value: 'NB-01' }); // all flags default to false
Object.defineProperty(product, 'internalNote', { value: 'reorder soon', enumerable: false, writable: true });

console.log(Object.getOwnPropertyDescriptor(product, 'name'));
console.log(Object.getOwnPropertyDescriptor(product, 'sku'));
console.log(Object.keys(product), JSON.stringify(product), product.internalNote);

try {
  product.sku = 'CHANGED';
} catch (error) {
  console.log('assign to read-only:', error.name);
}
try {
  delete product.sku;
} catch (error) {
  console.log('delete non-configurable:', error.name);
}

const temperature = {
  celsius: 25,
  get fahrenheit() {
    return this.celsius * 9 / 5 + 32;
  },
  set fahrenheit(value) {
    this.celsius = (value - 32) * 5 / 9;
  },
};
console.log(temperature.fahrenheit);
temperature.fahrenheit = 212;
console.log(temperature.celsius);
console.log(typeof Object.getOwnPropertyDescriptor(temperature, 'fahrenheit').get);

const copy = { ...temperature };
console.log(Object.getOwnPropertyDescriptor(copy, 'fahrenheit').value, 'get' in Object.getOwnPropertyDescriptor(copy, 'fahrenheit'));

class Circle {
  constructor(radius) {
    this.radius = radius;
  }
  get area() {
    return Math.round(Math.PI * this.radius ** 2);
  }
}
const circle = new Circle(2);
console.log(circle.area, Object.keys(circle), JSON.stringify(circle), Object.hasOwn(circle, 'area'));

Run with Node.js v24.22.1 as js-46.js; two runs gave identical output. Output: { value: 'Notebook', writable: true, enumerable: true, configurable: true } { value: 'NB-01', writable: false, enumerable: false, configurable: false } [ 'name' ] {"name":"Notebook"} reorder soon assign to read-only: TypeError delete non-configurable: TypeError 77 100 function 212 false 13 [ 'radius' ] {"radius":2} false

Key points

  • Data attributes: value, writable, enumerable, configurable. Accessor attributes: get, set, enumerable, configurable.
  • Properties made by assignment have every flag true; defineProperty defaults missing flags to false.
  • Non-enumerable properties are hidden from keys, spread, and JSON.
  • Non-configurable cannot be deleted or reconfigured, and cannot be switched back.
  • Spread copies getter results as plain values.

Common mistakes

  • Assuming defineProperty defaults flags to true; they default to false when creating.
  • Expecting a class getter to appear in JSON.stringify or Object.keys output.
  • Trying to make a non-configurable property configurable again.
  • Forgetting that spread and Object.assign turn getters into plain values.

Follow-ups

  • How does Object.freeze use these flags internally?
  • How does a getter on the prototype differ from a getter defined directly on the instance?
  • How can you define several properties at once and read all descriptors?

Tips

  • List the four data flags, then say what each controls in one line.
  • Show a getter and setter pair with a clear use, such as unit conversion.
  • Mention that class getters live on the prototype; it answers the most common follow-up before it is asked.
47.javascript-0047Hardsenior

What are Symbols in JavaScript, and what are well-known symbols used for?

A Symbol is a unique, immutable primitive used as a property key that cannot collide with any other key. Symbol keys are skipped by for...in, Object.keys, and JSON.stringify. Well-known symbols such as Symbol.iterator, Symbol.toPrimitive, Symbol.toStringTag, and Symbol.hasInstance let an object customize how the language treats it.

Full answer

Symbol('label') creates a new value that is different from every other symbol, even one with the same description. The description is only for debugging. Symbols are primitives, but they cannot be converted to a string implicitly, so 'x' + symbol throws a TypeError. Use symbol.toString() or symbol.description.

As property keys, symbols avoid name collisions. A library can attach metadata to an object without clashing with the user's own keys. Symbol keys do not show up in for...in, Object.keys, Object.entries, or JSON.stringify. They are still not private. Object.getOwnPropertySymbols and Reflect.ownKeys list them. For true privacy, use #private fields.

Symbol.for('key') reads from a global registry shared across the whole program (and across realms such as iframes), returning the same symbol for the same key. This is for cases where separate pieces of code must agree on a key.

Well-known symbols are built-in keys that hook into language behavior:

  • Symbol.iterator makes an object iterable by for...of and spread.
  • Symbol.asyncIterator does the same for for await...of.
  • Symbol.toPrimitive controls conversion to a number, string, or default value.
  • Symbol.toStringTag changes the text in Object.prototype.toString output.
  • Symbol.hasInstance customizes instanceof.

These make symbols the entry point for much of JavaScript's metaprogramming.

javascript
const idA = Symbol('id');
const idB = Symbol('id');
console.log(idA === idB, idA.description, idA.toString());
console.log(Symbol.for('app.id') === Symbol.for('app.id'), Symbol.keyFor(Symbol.for('app.id')));

try {
  console.log('id: ' + idA);
} catch (error) {
  console.log('implicit string conversion:', error.name);
}

const user = { name: 'Tia', [idA]: 'hidden-key-value' };
console.log(Object.keys(user), JSON.stringify(user));
console.log(Object.getOwnPropertySymbols(user).length, Reflect.ownKeys(user));

class Money {
  constructor(amount) {
    this.amount = amount;
  }
  [Symbol.toPrimitive](hint) {
    return hint === 'string' ? `Rs ${this.amount}` : this.amount;
  }
  get [Symbol.toStringTag]() {
    return 'Money';
  }
}
const price = new Money(250);
console.log(`${price}`, price + 50, price * 2);
console.log(Object.prototype.toString.call(price));

class EvenNumber {
  static [Symbol.hasInstance](value) {
    return Number.isInteger(value) && value % 2 === 0;
  }
}
console.log(4 instanceof EvenNumber, 5 instanceof EvenNumber);

const range = {
  start: 1,
  end: 3,
  *[Symbol.iterator]() {
    for (let n = this.start; n <= this.end; n++) yield n;
  },
};
console.log([...range]);

Run with Node.js v24.22.1 as js-47.js; two runs gave identical output. Output: false id Symbol(id) true app.id implicit string conversion: TypeError [ 'name' ] {"name":"Tia"} 1 [ 'name', Symbol(id) ] Rs 250 300 500 [object Money] true false [ 1, 2, 3 ]

Key points

  • Every symbol is unique; the description is for debugging only.
  • Symbols cannot be implicitly converted to strings.
  • Symbol keys are hidden from for...in, Object.keys, and JSON but not private.
  • Symbol.for shares symbols through a global registry.
  • Well-known symbols (iterator, toPrimitive, toStringTag, hasInstance) customize language behavior.

Common mistakes

  • Treating symbol keys as private. Reflect.ownKeys reveals them.
  • Concatenating a symbol with a string and getting a TypeError.
  • Expecting JSON.stringify to include symbol-keyed properties.
  • Using Symbol.for for keys that should be unique to one module.

Follow-ups

  • How do private class fields differ from symbol keys?
  • How would you make a custom class work with for await...of?
  • What does the hint argument to Symbol.toPrimitive contain, and when is it default?

Tips

  • Lead with uniqueness and collision avoidance; then add the well-known symbols as the "hooks".
  • Say symbols are hidden but not private. It is the most common wrong claim.
  • Give two examples of well-known symbols you have used, with one line each.
48.javascript-0048Hardsenior

How would you implement a retry helper with exponential backoff for an unreliable async operation?

Call the operation in a loop, and when it fails with a retryable error, wait before the next attempt and double the delay each time, up to a maximum number of attempts. Add random jitter so many clients do not retry together, retry only errors that can succeed later, and stop when the caller aborts. Operations that are retried should be safe to repeat.

Full answer

Networks and services fail briefly. A retry with a growing delay gives a service time to recover, whereas immediate retries in a tight loop add load exactly when it is struggling.

Exponential backoff means the delay grows by a factor each attempt: for example 100 ms, 200 ms, 400 ms. A cap such as maxDelay stops it from growing without limit. Jitter adds randomness, for example choosing a random value between 0 and the computed delay (called full jitter). Without it, thousands of clients that failed together retry at the same moment and cause a second wave of failures.

A sound helper has these properties:

  • It takes a maximum attempt count and throws the last error when it runs out.
  • It uses a shouldRetry(error) check. A network timeout or a 503 response is worth retrying. A 400 response or a validation error will fail the same way every time.
  • It accepts an AbortSignal so a user can cancel while it waits.
  • It makes the sleep and random functions injectable, so tests are fast and deterministic.
  • It is only used for idempotent operations, or the caller adds an idempotency key. Repeating a payment request without protection can charge twice.

In production, also respect a Retry-After header when the server sends one, and consider a circuit breaker if failures are long-lasting.

javascript
async function retry(operation, options = {}) {
  const {
    attempts = 4,
    baseDelay = 100,
    factor = 2,
    maxDelay = 2000,
    shouldRetry = () => true,
    random = Math.random,
    sleep = (ms, signal) =>
      new Promise((resolve, reject) => {
        const timer = setTimeout(resolve, ms);
        signal?.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason); }, { once: true });
      }),
    signal,
    onRetry = () => {},
  } = options;

  for (let attempt = 1; ; attempt++) {
    signal?.throwIfAborted();
    try {
      return await operation(attempt);
    } catch (error) {
      if (attempt >= attempts || !shouldRetry(error)) throw error;
      const ceiling = Math.min(maxDelay, baseDelay * factor ** (attempt - 1));
      const delay = Math.floor(random() * ceiling); // full jitter
      onRetry({ attempt, delay, ceiling, message: error.message });
      await sleep(delay, signal);
    }
  }
}

(async () => {
  const waits = [];
  const fakeSleep = async (ms) => waits.push(ms); // no real waiting in the demo
  let calls = 0;

  const flaky = async () => {
    calls += 1;
    if (calls < 3) throw Object.assign(new Error('503 service unavailable'), { retryable: true });
    return 'ok on call ' + calls;
  };

  const result = await retry(flaky, {
    sleep: fakeSleep,
    random: () => 1, // no randomness, so the full ceiling is used
    shouldRetry: (error) => error.retryable,
    onRetry: ({ attempt, ceiling }) => console.log(`attempt ${attempt} failed, waiting up to ${ceiling} ms`),
  });
  console.log(result, 'waits:', waits);

  try {
    await retry(async () => { throw new Error('400 bad request'); }, { sleep: fakeSleep, shouldRetry: () => false });
  } catch (error) {
    console.log('not retried:', error.message);
  }

  try {
    await retry(async () => { throw new Error('always down'); }, { attempts: 3, sleep: fakeSleep });
  } catch (error) {
    console.log('gave up:', error.message);
  }

  const controller = new AbortController();
  const waiting = retry(async () => { throw new Error('down'); }, { baseDelay: 500, random: () => 1, signal: controller.signal });
  setTimeout(() => controller.abort(new Error('cancelled by user')), 20);
  try {
    await waiting;
  } catch (error) {
    console.log('aborted while waiting:', error.message);
  }
})();

Run with Node.js v24.22.1 as js-48.js; two runs gave identical output. Output: attempt 1 failed, waiting up to 100 ms attempt 2 failed, waiting up to 200 ms ok on call 3 waits: [ 100, 200 ] not retried: 400 bad request gave up: always down aborted while waiting: cancelled by user

Key points

  • Delay grows by a factor each attempt, capped at a maximum.
  • Jitter prevents many clients from retrying in sync.
  • Retry only errors that can succeed later; rethrow the last error at the end.
  • Support cancellation with an AbortSignal.
  • Retried operations must be idempotent or protected by an idempotency key.

Common mistakes

  • Retrying immediately in a tight loop.
  • Retrying errors that will never succeed, such as validation failures.
  • Leaving out jitter, so all clients retry together.
  • Retrying non-idempotent operations without an idempotency key.

Follow-ups

  • How does a circuit breaker complement retries?
  • How would you honour a Retry-After header?
  • How would you add a total time budget across all attempts?

Tips

  • Mention jitter and idempotency without being prompted; they are what an experienced engineer adds.
  • Show injectable sleep and random for testing. It signals production habits.
  • Explain which errors you would retry and which you would not.
49.javascript-0049Mediummid

What are the common pitfalls of the Date object in JavaScript, and how do you work with time zones safely?

Date stores a single UTC timestamp in milliseconds, but many of its methods read or format it in the machine's local time zone. Months are zero-based, date-only ISO strings parse as UTC while date-time strings without an offset parse as local time, and month arithmetic overflows. Use UTC methods or Intl.DateTimeFormat with an explicit timeZone, and store timestamps in UTC.

Full answer

A Date is nothing more than a number: milliseconds since 1 January 1970 UTC. There is no time zone inside it. What changes is how it is read. getHours() converts to the local zone of the machine, while getUTCHours() does not, and toISOString() always prints UTC.

Frequent pitfalls:

  • Months run from 0 to 11, but days run from 1 to 31. new Date(2026, 0, 15) is 15 January.
  • Parsing is inconsistent. new Date('2026-01-15') (date only, ISO format) is read as UTC midnight, but new Date('2026-01-15T00:00:00') (no offset) is read as local time. Always include Z or an explicit offset such as +05:30 in stored strings.
  • Date setters overflow instead of failing. Setting the month to February on 31 January gives a date in March.
  • An invalid date does not throw. It becomes an Invalid Date object whose getTime() is NaN.
  • Adding 24 hours of milliseconds is not the same as adding one calendar day in a zone with daylight saving changes.
  • A Date object is mutable, so copy it before changing it.

For safe work: store and send UTC timestamps or ISO strings with an offset; do calendar arithmetic with UTC methods; and display with Intl.DateTimeFormat and an explicit timeZone option, for example Asia/Kolkata. Do not hard-code a zone offset, since offsets change with daylight saving time.

Temporal is the modern replacement API with separate types for instants, zoned times, and plain dates. Where it is not available yet, a library can fill the gap.

javascript
const january15 = new Date(Date.UTC(2026, 0, 15, 10, 30));
console.log(january15.toISOString(), january15.getTime());

const dateOnly = new Date('2026-01-15');
console.log(dateOnly.toISOString());

const withOffset = new Date('2026-01-15T10:30:00+05:30');
console.log(withOffset.toISOString());

const invalid = new Date('not a date');
console.log(String(invalid), Number.isNaN(invalid.getTime()));

const endOfJanuary = new Date(Date.UTC(2026, 0, 31));
endOfJanuary.setUTCMonth(1); // February has no 31st
console.log(endOfJanuary.toISOString().slice(0, 10));

const start = Date.UTC(2026, 0, 1);
const end = Date.UTC(2026, 2, 1);
console.log((end - start) / 86400000, 'days between 1 Jan and 1 Mar 2026');

const meeting = new Date('2026-03-10T14:00:00Z');
for (const timeZone of ['Asia/Kolkata', 'America/New_York', 'UTC']) {
  const text = new Intl.DateTimeFormat('en-GB', {
    timeZone,
    dateStyle: 'medium',
    timeStyle: 'short',
  }).format(meeting);
  console.log(timeZone.padEnd(17), text);
}

const original = new Date(Date.UTC(2026, 5, 1));
const next = new Date(original);
next.setUTCDate(next.getUTCDate() + 30);
console.log(original.toISOString().slice(0, 10), next.toISOString().slice(0, 10));

Run with Node.js v24.22.1 as js-49.js; two runs gave identical output. Output: 2026-01-15T10:30:00.000Z 1768473000000 2026-01-15T00:00:00.000Z 2026-01-15T05:00:00.000Z Invalid Date true 2026-03-03 59 days between 1 Jan and 1 Mar 2026 Asia/Kolkata 10 Mar 2026, 19:30 America/New_York 10 Mar 2026, 10:00 UTC 10 Mar 2026, 14:00 2026-06-01 2026-07-01

Key points

  • A Date is a UTC timestamp; local time appears only when reading or formatting.
  • Months are zero-based; setters overflow into the next month.
  • Date-only ISO strings parse as UTC; date-time strings without an offset parse as local.
  • Invalid dates produce NaN rather than an exception.
  • Store UTC; format with Intl.DateTimeFormat and an explicit timeZone.

Common mistakes

  • Forgetting that months start at 0.
  • Parsing a date-only string and a date-time string and assuming both use the same zone.
  • Adding 86,400,000 ms to move a calendar day across a daylight saving change.
  • Mutating a Date that is shared, such as one stored in state.

Follow-ups

  • Why does new Date('2026-01-15') show the previous day for users west of UTC when formatted in local time?
  • How would you display a time for a user in a time zone different from the server's?
  • What problems does the Temporal API solve?

Tips

  • Start with "a Date is a UTC timestamp"; every pitfall then follows from it.
  • Recommend one concrete practice: store UTC, format with an explicit timeZone.
  • If asked about libraries, mention Temporal and say you pick based on browser and runtime support.
50.javascript-0050Hardsenior

What does this set of classic JavaScript output puzzles print, and why? Cover loop closures, hoisting clashes, map(parseInt), and coercion.

Each puzzle tests one rule. var in a loop shares one variable across all callbacks, while let creates one per iteration. A function declaration beats a var of the same name at the start, but a later assignment wins. map passes three arguments, so parseInt reads the index as its radix, and unary plus on text gives the famous baNaNa.

Full answer

Interview puzzles are short, but each one hides a single rule. The method for answering is to name the rule before giving the output.

Loop closures: a var loop variable is one variable for the whole function. Callbacks created in the loop all read it later, after the loop has ended, so they see the final value. A let loop variable is created fresh for each iteration, so each callback keeps its own value. The old fix was an immediately invoked function that captured the value as a parameter.

Hoisting clash: a function declaration is hoisted with its value, and a var with the same name is hoisted without overriding it. So at the start, typeof shows function. A later assignment such as var g = 1 then replaces the function at its line, so the type becomes number afterwards.

['1', '2', '3'].map(parseInt): map calls its callback with (value, index, array). parseInt(value, radix) takes a radix as the second argument, so the calls are parseInt('1', 0), parseInt('2', 1), and parseInt('3', 2). Radix 0 means 10, radix 1 is invalid, and '3' is not a valid digit in base 2. The result is [1, NaN, NaN].

'b' + 'a' + +'a' + 'a': the unary plus turns 'a' into NaN, and joining it to text gives baNaNa.

Object keys: keys become strings, so every plain object used as a key turns into [object Object] and the entries overwrite each other.

javascript
'use strict';

const withVar = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);
const withLet = [];
for (let j = 0; j < 3; j++) withLet.push(() => j);
const withIife = [];
for (var k = 0; k < 3; k++) withIife.push(((copy) => () => copy)(k));
console.log(withVar.map((fn) => fn()), withLet.map((fn) => fn()), withIife.map((fn) => fn()));

console.log(typeof clash, typeof later);
function clash() {}
var clash;
var later = 1;
function later() {}
console.log(typeof later);

console.log(['1', '2', '3'].map(parseInt));
console.log(['1', '2', '3'].map((value) => parseInt(value, 10)));
console.log(['1', '2', '3'].map(Number));

console.log('b' + 'a' + +'a' + 'a');
console.log(typeof typeof 1, typeof NaN, [] + [] === '');
console.log(0.1 * 3 === 0.3, 9 > 8 > 7, 1 < 2 < 3);

const keyed = {};
keyed[{ id: 1 }] = 'first';
keyed[{ id: 2 }] = 'second';
console.log(Object.keys(keyed), keyed['[object Object]']);

const obj = {
  value: 10,
  regular() {
    return [1].map(function () { return this === undefined; })[0];
  },
  arrow() {
    return [1].map(() => this.value)[0];
  },
};
console.log(obj.regular(), obj.arrow());

Run with Node.js v24.22.1 as js-50.js; two runs gave identical output. Output: [ 3, 3, 3 ] [ 0, 1, 2 ] [ 0, 1, 2 ] function function number [ 1, NaN, NaN ] [ 1, 2, 3 ] [ 1, 2, 3 ] baNaNa string number true false false true [ '[object Object]' ] second true 10

Key points

  • Name the rule first, then give the output.
  • var is function-scoped and shared; let is per iteration.
  • A function declaration wins at the start; a later var assignment overwrites it.
  • map passes value, index, and array, so parseInt receives a radix.
  • Unary plus on a non-numeric string gives NaN; plain objects as keys become "[object Object]".

Common mistakes

  • Guessing outputs without stating the rule that decides them.
  • Forgetting that map passes three arguments to the callback.
  • Assuming the function declaration and the var of the same name conflict with an error.
  • Thinking let in a for loop is shared like var.

Follow-ups

  • How would you fix the var loop without changing it to let?
  • What does ['10', '10', '10'].map(parseInt) return?
  • Why is 9 > 8 > 7 false, while 1 < 2 < 3 is true?

Tips

  • Say the rule first; interviewers grade the reasoning more than the result.
  • Run unclear cases in the console during practice and keep a short list of the traps.
  • Admit when a case is outside what you know and explain the part you are sure of.
51.javascript-0051Easyfresher

What do the optional chaining (?.) and nullish coalescing (??) operators do, and how do they differ from && and ||?

Optional chaining a?.b stops and returns undefined when a is null or undefined, instead of throwing a TypeError. Nullish coalescing a ?? b returns b only when a is null or undefined, so valid values such as 0, false, and an empty string are kept. Together they replace long chains of && and || checks.

Full answer

Reading a property of null or undefined throws a TypeError. Before optional chaining, safe access meant writing user && user.address && user.address.city. The operator ?. does the same in one step: if the value on its left is null or undefined, the whole chain stops and the result is undefined. It works for properties (user?.address), computed keys (list?.[0]), and function calls (callback?.()). The rest of the chain is skipped, so arguments inside the call are not evaluated either.

Optional chaining checks only for null and undefined. A value such as 0 or '' continues the chain normally. It does not hide other errors: calling a property that exists but is not a function still throws.

The operator ?? supplies a default. a ?? b is b only when a is null or undefined. The older a || b returns b for every falsy value, so 0 || 10 gives 10 even when zero was a real answer. Use ?? for defaults when 0, false, or '' are valid data.

The two operators combine well: settings?.volume ?? 50. Mixing ?? with && or || without parentheses is a syntax error, which prevents unclear precedence.

Use optional chaining only where a value may really be missing. Spreading it everywhere hides bugs, because a typo in a property name quietly gives undefined.

javascript
const user = { name: 'Neha', address: null, scores: [0, 45], greet() { return 'hello'; } };

console.log(user.address?.city);
console.log(user.scores?.[0], user.missing?.[0]);
console.log(user.greet?.(), user.shout?.());

let calls = 0;
user.missing?.method(calls++); // arguments are skipped when the chain stops
console.log('argument evaluated:', calls);

try {
  user.address.city;
} catch (error) {
  console.log('without ?.:', error.name);
}
try {
  user.name?.nope(); // name exists, but nope is not a function
} catch (error) {
  console.log('real mistakes still throw:', error.name);
}

const volume = 0;
console.log(volume || 50, volume ?? 50);
const label = '';
console.log(label || 'untitled', label ?? 'untitled');
console.log(user.settings?.theme ?? 'light');

try {
  eval('null || undefined ?? 1');
} catch (error) {
  console.log('mixing without parentheses:', error.name);
}
console.log((null || undefined) ?? 'parenthesized');

Run with Node.js v24.22.1 as js-51.js; two runs gave identical output. Output: undefined 0 undefined hello undefined argument evaluated: 0 without ?.: TypeError real mistakes still throw: TypeError 50 0 untitled light mixing without parentheses: SyntaxError parenthesized

Key points

  • ?. short-circuits to undefined when its left side is null or undefined.
  • It also works for ?.[key] and fn?.() and skips the rest of the chain.
  • ?? falls back only for null and undefined; || falls back for every falsy value.
  • ?? cannot be mixed with && or || without parentheses.
  • Overusing ?. can hide typos and real data problems.

Common mistakes

  • Using || for defaults and replacing valid 0, false, or empty-string values.
  • Believing ?. catches every error. It only guards null and undefined on its left.
  • Putting ?. after every property, which hides typos and missing data bugs.
  • Assigning with the chain on the left side, such as user?.name = 'x', which is a SyntaxError.

Follow-ups

  • What does a?.b.c do when a exists but b is undefined?
  • How does optional chaining behave with delete?
  • What are the logical assignment operators ??=, ||=, and &&=?

Tips

  • Contrast ?? with || using the zero example; interviewers expect that one.
  • Mention that the arguments after a short-circuited call are not evaluated.
  • Say you use ?. only where missing data is expected, not as a habit.
52.javascript-0052Easyfresher

Which string methods should every JavaScript developer know, and why can string length surprise you with emoji and accents?

Strings are immutable, so every method returns a new string. The everyday set is includes, startsWith, slice, trim, split, replaceAll, padStart, repeat, and at. Length counts UTF-16 code units, not visible characters, so some emoji and combined accents count as more than one; use Array.from or Intl.Segmenter to count what a person sees.

Full answer

A string method never changes the string it is called on. It returns a new one, and the original stays as it was. Forgetting this is a classic beginner bug: text.trim() on its own line does nothing useful.

A working set of methods covers most tasks:

  • Searching: includes, startsWith, endsWith, indexOf (returns -1 when absent).
  • Cutting: slice(start, end), at(-1) for the last character, split(separator).
  • Cleaning: trim, trimStart, trimEnd, toLowerCase, toUpperCase.
  • Building: repeat, padStart, padEnd (handy for fixed-width numbers such as '7'.padStart(3, '0')), concat, and template literals.
  • Replacing: replace changes only the first match for a string pattern, while replaceAll changes every match.

Characters are stored as UTF-16 code units. Most letters take one unit, but many emoji take two (a surrogate pair), and an accented letter can be written as a base letter plus a combining mark. As a result, '\u{1F600}'.length is 2, and two strings that look identical can have different lengths. Array.from(text) or spread iterates by code point, which fixes emoji pairs. For what a reader counts as one character, including combined marks and family emoji, use Intl.Segmenter. normalize('NFC') makes the two forms of an accented letter equal before comparing.

For comparing text for humans, use localeCompare and not <.

javascript
const text = '  Learn JavaScript  ';
text.trim();
console.log(JSON.stringify(text), JSON.stringify(text.trim()));

const course = 'JavaScript';
console.log(course.includes('Script'), course.startsWith('Java'), course.indexOf('x'));
console.log(course.slice(0, 4), course.slice(-6), course.at(-1), course[0]);
console.log('a-b-c'.replace('-', '+'), 'a-b-c'.replaceAll('-', '+'));
console.log('7'.padStart(3, '0'), 'ab'.repeat(3), 'x'.padEnd(3, '.') + '|');
console.log('red,green,blue'.split(',').map((color) => color.toUpperCase()).join(' / '));

console.log('\u{1F600}'.length, Array.from('\u{1F600}').length, [...'a\u{1F600}b'].length);
const composed = '\u00e9'; // one code unit
const decomposed = 'e\u0301'; // e plus a combining accent
console.log(composed === decomposed, composed.normalize('NFC') === decomposed.normalize('NFC'));
console.log(composed.length, decomposed.length);

const family = '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}';
const segmenter = new Intl.Segmenter('en', { granularity: 'grapheme' });
console.log(family.length, [...family].length, [...segmenter.segment(family)].length);

console.log('a'.localeCompare('b'), ['z', 'ä', 'a'].sort((a, b) => a.localeCompare(b, 'de')));

Run with Node.js v24.22.1 as js-52.js; two runs gave identical output. Output: " Learn JavaScript " "Learn JavaScript" true true -1 Java Script t J a+b-c a+b+c 007 ababab x..| RED / GREEN / BLUE 2 1 3 false true 1 2 8 5 1 -1 [ 'a', 'ä', 'z' ]

Key points

  • Strings are immutable; methods return new strings.
  • Know includes, slice, at, trim, split, replaceAll, padStart, and repeat.
  • replace with a string pattern changes only the first match; replaceAll changes all.
  • length counts UTF-16 code units, not visible characters.
  • Use Array.from, Intl.Segmenter, and normalize for correct text handling.

Common mistakes

  • Calling trim or toUpperCase and ignoring the returned string.
  • Using replace with a string and expecting every match to change.
  • Counting characters with length for text that may contain emoji or accents.
  • Comparing user text without normalizing it first.

Follow-ups

  • How do you reverse a string that contains emoji correctly?
  • What is the difference between slice, substring, and the deprecated substr?
  • How do you compare strings in a case- and accent-insensitive way?

Tips

  • Say "strings are immutable" before listing any methods; it prevents the most common bug.
  • Show the emoji length example. It is quick and memorable.
  • Mention Intl.Segmenter for user-visible characters; few candidates know it.
53.javascript-0053Easyfresher

How do regular expressions work in JavaScript, and what are the common traps with the g flag and capture groups?

A regular expression describes a text pattern. test checks for a match, match and matchAll return matches, and replace rewrites them, with parentheses capturing parts and named groups giving them labels. A regex with the g flag keeps a lastIndex between calls, so reusing one with test or exec can skip matches.

Full answer

A regular expression, or regex, is a pattern that describes text. It is written between slashes, /pattern/flags, or created with new RegExp('pattern', 'flags'). Characters match themselves. Special pieces add power: \d is a digit, \w a letter, digit, or underscore, . any character except a line break, + one or more, * zero or more, ? optional, and ^ and $ mark the start and end.

Methods you need: regex.test(text) returns a boolean. text.match(regex) returns the first match with details, or all matches as plain strings when the g flag is set. text.matchAll(regex) returns an iterator with full details for each match and requires the g flag. text.replace(regex, replacement) rewrites matches, and the replacement can be a function.

Parentheses create capture groups. In /(\d{4})-(\d{2})/ the groups are numbered, and (?<year>\d{4}) gives a name that appears under match.groups. A group that does not match is undefined. Use (?:...) when grouping is needed without capturing.

Common flags: g global, i ignore case, m multiline anchors, s dot matches newlines, u Unicode mode, and y sticky.

The main trap is state. A regex with g or y remembers lastIndex, and test or exec starts from it. Calling test twice on the same global regex with the same text can return true and then false. Create the regex inside the function or avoid g with test.

Another warning: nested quantifiers such as (a+)+ can take exponential time on some inputs. Do not run untrusted patterns or inputs through such expressions.

javascript
const date = '2026-03-14';
const pattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = date.match(pattern);
console.log(match.groups.year, match.groups.month, match[3]);

const text = 'Call 98765 or 91234 now';
console.log(text.match(/\d{5}/g));
console.log([...text.matchAll(/(\d)(\d{4})/g)].map((m) => [m[0], m.index]));
console.log(text.replace(/\d{5}/g, (digits) => digits.slice(0, 2) + '***'));
console.log('2026-03-14'.replace(pattern, '$<day>/$<month>/$<year>'));

const globalRegex = /cat/g;
console.log(globalRegex.test('cat'), globalRegex.lastIndex);
console.log(globalRegex.test('cat'), globalRegex.lastIndex); // starts after the first match

const safeRegex = /cat/;
console.log(safeRegex.test('cat'), safeRegex.test('cat'));

console.log(/^[\w.+-]+@[\w-]+\.[\w.]+$/.test('asha@example.com'), /^[\w.+-]+@[\w-]+\.[\w.]+$/.test('no-at-sign'));
console.log('Hello'.match(/(x)?ello/)[1], /colou?r/i.test('COLOR'));
console.log('a\nb'.match(/a.b/), 'a\nb'.match(/a.b/s)?.[0]);

Run with Node.js v24.22.1 as js-53.js; two runs gave identical output. Output: 2026 03 14 [ '98765', '91234' ] [ [ '98765', 5 ], [ '91234', 14 ] ] Call 98*** or 91*** now 14/03/2026 true 3 false 0 true true true false undefined true null a b

Key points

  • Know the core pieces: \d, \w, ., +, *, ?, ^, $, and groups.
  • test returns a boolean; match, matchAll, and replace return details or new text.
  • Named groups appear in match.groups; non-participating groups are undefined.
  • Regex with g or y keeps lastIndex, which can make repeated test calls inconsistent.
  • Avoid nested quantifiers on untrusted input to prevent catastrophic backtracking.

Common mistakes

  • Reusing a global regex object with test and getting alternating results.
  • Using a simple regex to fully validate an email address; a basic check plus a confirmation message is more reliable.
  • Forgetting to escape special characters such as . or ( when they should match literally.
  • Using nested quantifiers on untrusted input and opening the door to catastrophic backtracking.

Follow-ups

  • What is the difference between greedy and lazy quantifiers?
  • How do lookahead and lookbehind assertions work?
  • What does the u flag change?

Tips

  • Show named groups and a replace callback; they signal current JavaScript knowledge.
  • Explain lastIndex whenever the g flag comes up.
  • Say that regexes are for pattern checks, and that parsers are better for HTML or nested structures.
54.javascript-0054Mediummid

What are the edge cases and pitfalls of JSON.stringify and JSON.parse?

JSON.stringify drops undefined, functions, and symbols in objects, turns them into null in arrays, converts NaN and Infinity to null, turns Dates into strings, throws on BigInt and circular references, and skips non-enumerable keys. JSON.parse never restores types by itself, and throws on invalid JSON. toJSON, replacer, and reviver let you control both directions.

Full answer

JSON is a text format with only six kinds of value: object, array, string, number, boolean, and null. Anything else has to be converted, and JSON.stringify makes quiet choices.

In objects, properties whose value is undefined, a function, or a symbol are skipped. In arrays, those same values become null to keep the positions. NaN, Infinity, and -Infinity become null. A Date has a toJSON method, so it becomes an ISO string, and Map, Set, and class fields that are private become {} or are absent. A BigInt throws a TypeError, and a circular reference throws a TypeError too. Only own, enumerable, string-keyed properties are written. If an object has a toJSON method, its return value is serialized instead.

JSON.parse turns text back into plain data. A date string stays a string, and a number stays a number, so types such as Date and Map are not restored. Invalid JSON throws a SyntaxError: single quotes, trailing commas, comments, and unquoted keys are not allowed. Large integers beyond 2^53 lose precision when parsed as numbers.

The second argument of stringify is a replacer, which is either a function or an array of allowed keys. The second argument of parse is a reviver, called for each key and value from the inside out, which is the place to rebuild dates. The third argument of stringify sets the indentation.

A __proto__ key in parsed JSON creates an ordinary own property, not a prototype change. Still, merging parsed objects unsafely can be dangerous, which is covered in the prototype pollution question.

javascript
const data = {
  title: 'Report',
  draft: undefined,
  run() {},
  id: Symbol('x'),
  ratio: NaN,
  limit: Infinity,
  createdAt: new Date('2026-02-01T08:00:00Z'),
  tags: new Set(['a']),
  list: [undefined, () => 1, 3],
};
console.log(JSON.stringify(data));

try {
  JSON.stringify({ big: 10n });
} catch (error) {
  console.log('BigInt:', error.name);
}
const loop = {};
loop.self = loop;
try {
  JSON.stringify(loop);
} catch (error) {
  console.log('circular:', error.name);
}

class Money {
  constructor(amount, currency) {
    this.amount = amount;
    this.currency = currency;
  }
  toJSON() {
    return `${this.amount} ${this.currency}`;
  }
}
console.log(JSON.stringify({ price: new Money(250, 'INR') }));
console.log(JSON.stringify({ a: 1, b: 2, c: 3 }, ['a', 'c']));
console.log(JSON.stringify({ a: 1, b: { c: 2 } }, (key, value) => (typeof value === 'number' ? value * 10 : value), 2));

const text = JSON.stringify({ when: new Date('2026-02-01T08:00:00Z'), n: 1 });
const plain = JSON.parse(text);
console.log(typeof plain.when);
const revived = JSON.parse(text, (key, value) => (key === 'when' ? new Date(value) : value));
console.log(revived.when instanceof Date, revived.when.getUTCFullYear());

for (const bad of ["{'a': 1}", '{"a": 1,}', '{a: 1}', '']) {
  try {
    JSON.parse(bad);
  } catch (error) {
    console.log(JSON.stringify(bad), '->', error.name);
  }
}
console.log(JSON.parse('{"__proto__": {"admin": true}}').admin, Object.keys(JSON.parse('{"__proto__": 1}')));
console.log(JSON.parse('12345678901234567890'));

Run with Node.js v24.22.1 as js-54.js; two runs gave identical output. Output: {"title":"Report","ratio":null,"limit":null,"createdAt":"2026-02-01T08:00:00.000Z","tags":{},"list":[null,null,3]} BigInt: TypeError circular: TypeError {"price":"250 INR"} {"a":1,"c":3} { "a": 10, "b": { "c": 20 } } string true 2026 "{'a': 1}" -> SyntaxError "{\"a\": 1,}" -> SyntaxError "{a: 1}" -> SyntaxError "" -> SyntaxError undefined [ '__proto__' ] 12345678901234567000

Key points

  • Only own enumerable string keys are written; undefined, functions, and symbols are skipped in objects and become null in arrays.
  • NaN and Infinity become null; BigInt and circular structures throw.
  • Dates become ISO strings and are not restored by parse.
  • toJSON, replacer, and reviver control the conversion in each direction.
  • Invalid JSON, including trailing commas and single quotes, throws SyntaxError.

Common mistakes

  • Using JSON.parse(JSON.stringify(x)) as a general deep copy for data with dates, undefined, Map, or Set.
  • Expecting dates to come back as Date objects after parse.
  • Parsing user input without a try/catch.
  • Storing large integer IDs as JSON numbers and losing precision.

Follow-ups

  • How would you serialize and restore a Map?
  • How would you send a BigInt in JSON safely?
  • What does JSON.stringify do with a property whose value is an object with a toJSON method?

Tips

  • List the "quietly dropped" values as a short group; this is what interviewers ask for.
  • Show a reviver for dates; it proves you know how to round-trip data.
  • Mention that single quotes, trailing commas, and comments are invalid JSON.
55.javascript-0055Easyfresher

How does the switch statement work in JavaScript, and what are labeled break and continue?

switch compares one value against each case using strict equality and, once a case matches, keeps running every following case until a break, return, or the end. This fallthrough is useful when cases share code and a common bug when break is forgotten. A label lets break or continue target an outer loop instead of only the innermost one.

Full answer

A switch evaluates its expression once and compares the result with each case value using ===. The string '1' does not match the number 1. When a case matches, execution starts there and continues into the next case bodies even when their values do not match. This behavior is called fallthrough. Add break (or return inside a function) to leave the switch. The default branch runs when nothing matches, and it can appear anywhere, but it is conventional to put it last.

Fallthrough is sometimes intended: case 'sat': case 'sun': return 'weekend'; groups several values on one result. Otherwise a missing break is a bug, and many linters warn about it. Each case shares one block scope, so declaring let in two cases with the same name clashes. Wrap case bodies in braces when they declare variables.

A common alternative is an object lookup, such as const messages = { 404: 'Not found' }, or a Map, which is shorter when each case only returns a value. Use switch when cases run statements.

A label is a name placed before a statement, such as outer: for (...). Inside nested loops, break outer leaves the labeled loop completely, and continue outer jumps to its next iteration. Without a label, break and continue apply only to the innermost loop. Labels are rare in everyday code, but they are cleaner than extra flag variables in a search over a grid. A function with return is often cleaner still.

javascript
function dayType(day) {
  switch (day) {
    case 'sat':
    case 'sun':
      return 'weekend';
    case 'fri':
      console.log('fri: runs, then falls through');
    case 'thu':
      return 'almost weekend';
    default:
      return 'weekday';
  }
}
console.log(dayType('sun'), dayType('fri'), dayType('mon'));

function strictCheck(value) {
  switch (value) {
    case 1:
      return 'number one';
    default:
      return 'no strict match';
  }
}
console.log(strictCheck(1), strictCheck('1'));

function describe(code) {
  switch (code) {
    case 200: {
      const text = 'OK';
      return text;
    }
    case 404: {
      const text = 'Not found';
      return text;
    }
    default:
      return 'Unknown';
  }
}
console.log(describe(200), describe(404), describe(500));

const messages = new Map([[200, 'OK'], [404, 'Not found']]);
console.log(messages.get(404) ?? 'Unknown');

const seats = [
  ['free', 'taken', 'free'],
  ['taken', 'free', 'free'],
];
let firstFree = null;
search: for (let row = 0; row < seats.length; row++) {
  for (let col = 0; col < seats[row].length; col++) {
    if (seats[row][col] === 'taken') continue; // next column
    firstFree = [row, col];
    break search; // leaves both loops
  }
}
console.log(firstFree);

outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (j === 1) continue outer;
    console.log('i,j =', i, j);
  }
}

Run with Node.js v24.22.1 as js-55.js; two runs gave identical output. Output: fri: runs, then falls through weekend almost weekend weekday number one no strict match OK Not found Unknown Not found [ 0, 0 ] i,j = 0 0 i,j = 1 0 i,j = 2 0

Key points

  • switch uses strict equality (===).
  • Without break, execution falls through into the next case.
  • Case bodies share one scope; use braces around cases that declare variables.
  • An object or Map lookup replaces a switch that only returns values.
  • break label and continue label control an outer loop.

Common mistakes

  • Forgetting break and running several cases by accident.
  • Expecting switch to compare with loose equality.
  • Declaring the same let name in two cases without braces.
  • Using labels when a function with return is clearer.

Follow-ups

  • How would you use switch (true) with conditions, and is it a good idea?
  • Where does a default placed in the middle run?
  • When would you replace a switch with polymorphism or a lookup table?

Tips

  • Mention strict equality and fallthrough first; they are the two facts interviewers look for.
  • Show the grid search with a label as the one realistic use.
  • Offer the Map lookup as a cleaner replacement when cases only return values.
56.javascript-0056Easyfresher

What is strict mode in JavaScript, and what does it change?

Strict mode is an opt-in, safer variant of the language turned on with the "use strict" directive. It turns silent mistakes into errors, such as assigning to an undeclared variable, and removes confusing features like with and automatic global this. Modules and classes are always strict, so most modern code already runs in it.

Full answer

Strict mode was added in ES5 so that old, error-prone behavior could be fixed without breaking existing sites. Placing the string 'use strict' at the top of a script turns it on for that script, and placing it at the top of a function turns it on for that function only. Older engines read the directive as an ordinary string, so it was safe to add.

The main changes are:

  • Assigning to an undeclared name throws a ReferenceError instead of creating a global variable.
  • Changes that used to fail silently throw a TypeError: writing to a read-only property, adding a property to a frozen object, or deleting a non-configurable one.
  • A plain function call gets this set to undefined instead of the global object.
  • Duplicate parameter names and some old octal literals such as 010 are syntax errors.
  • with statements are not allowed, and eval cannot add variables to the surrounding scope.
  • arguments no longer stays linked to the named parameters.
  • Some future keywords, for example let, static, and interface, cannot be used as variable names.

ES modules and class bodies are always strict, and no directive is needed. Because bundlers and frameworks use modules, new code seldom needs the directive, but older scripts and many Node.js CommonJS files still do. A common practice is a lint rule that enforces it where it is not automatic.

javascript
function sloppy() {
  undeclared = 5; // creates a global variable silently
  return typeof undeclared;
}
function strict() {
  'use strict';
  try {
    anotherUndeclared = 5;
  } catch (error) {
    return error.name;
  }
}
console.log(sloppy(), strict());
delete globalThis.undeclared;

function thisInSloppy() {
  return this === globalThis;
}
function thisInStrict() {
  'use strict';
  return this === undefined;
}
console.log(thisInSloppy(), thisInStrict());

function writeToFrozen(strictMode) {
  const body = (strictMode ? "'use strict';" : '') + 'const o = Object.freeze({ a: 1 }); o.a = 2; return o.a;';
  try {
    return new Function(body)();
  } catch (error) {
    return error.name;
  }
}
console.log(writeToFrozen(false), writeToFrozen(true));

for (const [label, source] of [
  ['duplicate parameter', "'use strict'; function f(a, a) {}"],
  ['octal literal', "'use strict'; var n = 010;"],
  ['with statement', "'use strict'; with ({}) {}"],
]) {
  try {
    new Function(source);
    console.log(label, 'allowed');
  } catch (error) {
    console.log(label, error.name);
  }
}

class Example {
  method() {
    return this;
  }
}
const detached = new Example().method;
console.log(detached());

Run with Node.js v24.22.1 as js-56.js; two runs gave identical output. Output: number ReferenceError true true 1 TypeError duplicate parameter SyntaxError octal literal SyntaxError with statement SyntaxError undefined

Key points

  • Opt in with 'use strict' at the top of a script or function.
  • Silent errors become thrown errors: undeclared assignment, read-only writes, and frozen objects.
  • Plain function calls get this equal to undefined.
  • Modules and classes are strict automatically.
  • It removes with, duplicate parameters, and old octal literals.

Common mistakes

  • Believing strict mode makes code faster. Its purpose is safety.
  • Putting the directive after another statement, where it is just an ordinary string.
  • Forgetting that class bodies and modules are already strict.
  • Mixing strict and sloppy scripts after concatenation, so the directive covers more or less code than intended.

Follow-ups

  • Where must 'use strict' appear for it to work?
  • How does strict mode change eval and arguments?
  • Why was the directive designed as a string and not a keyword?

Tips

  • Give the three changes everyone asks about: undeclared assignment, this in plain calls, and silent failures.
  • Note that modules and classes are strict by default; it shows current knowledge.
  • Mention a linter rule as the practical way to keep a codebase consistent.
57.javascript-0057Mediummid

How do getters and setters work in classes and object literals, and when should you use them?

A getter runs a function when a property is read, and a setter runs one when it is assigned, so code can compute values, validate input, or keep related fields in sync behind plain property syntax. They live on the prototype for classes, work well with private fields, and should stay cheap and free of surprising side effects.

Full answer

In an object literal or a class, get name() {} defines a property whose value is computed on each read, and set name(value) {} runs on assignment. To the caller they look like ordinary properties: account.balance, account.balance = 5.

The common reasons to use them are:

  • Computed values: get fullName() returns first and last name joined, with no stored copy to get out of date.
  • Validation: a setter can reject a negative age or trim text before it is stored.
  • Encapsulation: a private field #balance holds the data, a getter exposes it read-only, and no setter means no outside writes. Assigning to a getter-only property is ignored in sloppy mode and throws a TypeError in strict mode, which includes class bodies and modules.
  • Compatibility: a plain field can later become a getter and setter pair without changing the code that uses it.

Details worth knowing: a class getter lives on the prototype, so it is not an own property and is skipped by Object.keys, spread, and JSON.stringify. A setter without a getter makes the property read as undefined. Static getters belong to the class itself. A getter is called on every read, so an expensive one should cache its result. A getter that changes state makes debugging harder, because even logging the object runs it.

A common mistake is a setter that assigns to its own property name, set age(v) { this.age = v }, which calls itself forever and ends in a RangeError. Store the value in a differently named or private field.

javascript
'use strict';

class Temperature {
  #celsius = 0;

  constructor(celsius) {
    this.celsius = celsius; // goes through the setter
  }

  get celsius() {
    return this.#celsius;
  }
  set celsius(value) {
    if (typeof value !== 'number' || Number.isNaN(value)) {
      throw new TypeError('celsius must be a number');
    }
    if (value < -273.15) throw new RangeError('below absolute zero');
    this.#celsius = value;
  }

  get fahrenheit() {
    return this.#celsius * 9 / 5 + 32;
  }

  static get freezingPoint() {
    return 0;
  }
}

const t = new Temperature(25);
console.log(t.celsius, t.fahrenheit, Temperature.freezingPoint);
t.celsius = 100;
console.log(t.fahrenheit);

for (const bad of ['hot', -300]) {
  try {
    t.celsius = bad;
  } catch (error) {
    console.log(error.name, '-', error.message);
  }
}

try {
  t.fahrenheit = 50; // no setter: class code is strict
} catch (error) {
  console.log('getter only:', error.name);
}
console.log(Object.keys(t), JSON.stringify(t), Object.hasOwn(t, 'fahrenheit'));

class Broken {
  set value(v) {
    this.value = v; // calls the setter again
  }
}
try {
  new Broken().value = 1;
} catch (error) {
  console.log('recursive setter:', error.name);
}

const cart = {
  items: [{ price: 40, qty: 2 }, { price: 15, qty: 1 }],
  get total() {
    return this.items.reduce((sum, item) => sum + item.price * item.qty, 0);
  },
};
console.log(cart.total);
cart.items.push({ price: 5, qty: 4 });
console.log(cart.total);

Run with Node.js v24.22.1 as js-57.js; two runs gave identical output. Output: 25 77 0 212 TypeError - celsius must be a number RangeError - below absolute zero getter only: TypeError [] {} false recursive setter: RangeError 95 115

Key points

  • get runs on read, set runs on write; the call syntax is a plain property.
  • Use for computed values, validation, and read-only views of private fields.
  • Class accessors live on the prototype, so JSON.stringify and spread skip them.
  • Assigning to a getter-only property throws in strict mode.
  • A setter must not assign to the same property name, or it recurses.

Common mistakes

  • Writing a setter that assigns to the same property name and recurses until a RangeError.
  • Putting slow work or side effects in a getter.
  • Expecting JSON.stringify or spread to include class getters.
  • Making every field a getter and setter pair with no logic, which adds noise.

Follow-ups

  • How do you define a getter on an existing object with Object.defineProperty?
  • How do accessors interact with inheritance and super?
  • How would you cache an expensive getter result and invalidate it?

Tips

  • Lead with two uses: computed values and validation.
  • Show a private field behind a getter; it is the modern encapsulation answer.
  • State that getters should stay cheap and predictable.
58.javascript-0058Easyfresher

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

localStorage keeps string key-value pairs in the browser until they are cleared, sessionStorage keeps them only for one tab session, and cookies are small values that the browser also sends to the server with matching requests. Web storage is synchronous, limited to strings, and readable by any script on the page, so it is not a place for secrets.

Full answer

All three store data in the browser for one origin (scheme, host, and port), but they differ in lifetime, size, and who can see the data.

localStorage persists after the tab and the browser close. It is shared by every tab of the same origin. The space is typically about 5 MB. The API is setItem, getItem, removeItem, clear, and key. Data never leaves the browser unless the code sends it.

sessionStorage has the same API, but each tab has its own copy, and it is cleared when the tab closes. It suits state for one workflow, such as an unfinished form step.

Cookies are tiny (about 4 KB each) and are added automatically to every matching request to the server. They have an expiry, a path, and flags: HttpOnly hides the cookie from JavaScript, Secure limits it to HTTPS, and SameSite limits cross-site sending. Because of this, cookies are the usual home for session identifiers, and HttpOnly makes them harder to steal.

Web storage stores only strings. Numbers and objects must be converted, with JSON.stringify and JSON.parse. Calls are synchronous, so large reads can block the page. Any script on the page, including a compromised third-party script, can read it, so tokens and personal data do not belong there. Writing can also throw when storage is full or disabled, such as QuotaExceededError in some private modes.

For large or structured client data, IndexedDB is the better tool.

javascript
localStorage.clear();
sessionStorage.clear();

localStorage.setItem('theme', 'dark');
localStorage.setItem('visits', 3);
console.log(localStorage.getItem('theme'), localStorage.getItem('visits'), typeof localStorage.getItem('visits'));
console.log(localStorage.getItem('missing'), localStorage.length);

const profile = { name: 'Asha', courses: ['JS', 'React'] };
localStorage.setItem('profile', profile); // stores "[object Object]"
console.log(localStorage.getItem('profile'));
localStorage.setItem('profile', JSON.stringify(profile));
console.log(JSON.parse(localStorage.getItem('profile')).courses);

sessionStorage.setItem('step', '2');
console.log(sessionStorage.getItem('step'), localStorage.getItem('step'));

function readJson(key, fallback) {
  try {
    return JSON.parse(localStorage.getItem(key)) ?? fallback;
  } catch {
    return fallback;
  }
}
localStorage.setItem('broken', '{not json');
console.log(readJson('broken', 'default'), readJson('nothing', 'default'));

document.cookie = 'consent=yes; path=/';
document.cookie = 'lang=en; path=/';
console.log(document.cookie);

localStorage.removeItem('theme');
console.log(Object.keys(localStorage).sort());

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: dark 3 string null 2 [object Object] [ 'JS', 'React' ] 2 null default default consent=yes; lang=en [ 'broken', 'profile', 'visits' ]

Key points

  • localStorage persists and is shared across tabs; sessionStorage lasts for one tab.
  • Cookies are sent to the server automatically; web storage is not.
  • Web storage holds only strings; use JSON for objects.
  • HttpOnly, Secure, and SameSite are cookie flags that improve safety.
  • Do not store secrets in web storage; use IndexedDB for large data.

Common mistakes

  • Storing objects without JSON.stringify and getting "[object Object]".
  • Storing authentication tokens or personal data in localStorage.
  • Calling JSON.parse on a stored value without a try/catch and a fallback.
  • Assuming sessionStorage is shared across tabs of the same site.

Follow-ups

  • What does the storage event do, and which tabs receive it?
  • How do SameSite=Lax and SameSite=Strict differ?
  • When would you pick IndexedDB over localStorage?

Tips

  • Compare them on lifetime, size, and "is it sent to the server" in that order.
  • Mention that any script on the page can read web storage; it is the key security point.
  • Offer HttpOnly cookies for session identifiers.
59.javascript-0059Easyfresher

Which array methods find items or test conditions (find, findIndex, some, every, includes, indexOf), and how do they differ?

find returns the first matching item and findIndex its position, some says whether any item matches, every whether all do, and includes or indexOf look for an exact value. includes handles NaN while indexOf does not, and some and every stop as soon as the answer is known. findLast and findLastIndex search from the end.

Full answer

These methods answer different questions about an array, and choosing the right one makes code shorter and clearer.

includes(value) returns true or false for an exact value, using SameValueZero comparison, so [NaN].includes(NaN) is true. indexOf(value) returns the position or -1 and uses strict equality, so it cannot find NaN. For objects, both compare by reference.

find(callback) returns the first item for which the callback is truthy, or undefined when none match. findIndex(callback) returns its position, or -1. Because find returns undefined for "not found", it cannot tell a missing item from a stored undefined, and findIndex can. findLast and findLastIndex do the same from the end of the array.

some(callback) returns true if at least one item passes and stops at the first one that does. every(callback) returns true only if all items pass and stops at the first failure. On an empty array, some returns false and every returns true, which is a common interview question.

filter returns all matches as a new array, so use find or some when only one match or a yes/no answer is needed, as they can stop early. at(-1) reads the last item. flat and flatMap are often used before searching nested lists.

Sparse arrays behave differently: find and findIndex visit every index and see empty slots as undefined, while some, every, and forEach skip empty slots.

javascript
const students = [
  { name: 'Asha', marks: 82 },
  { name: 'Ravi', marks: 35 },
  { name: 'Meera', marks: 91 },
  { name: 'Dev', marks: 35 },
];

console.log(students.find((s) => s.marks < 40));
console.log(students.findIndex((s) => s.marks < 40), students.findLastIndex((s) => s.marks < 40));
console.log(students.findLast((s) => s.marks < 40).name);
console.log(students.find((s) => s.marks > 100), students.findIndex((s) => s.marks > 100));

console.log(students.some((s) => s.marks > 90), students.every((s) => s.marks >= 35));
console.log([].some(() => true), [].every(() => false));

const numbers = [10, NaN, 30];
console.log(numbers.includes(NaN), numbers.indexOf(NaN), numbers.indexOf(30));
console.log(students.includes({ name: 'Asha', marks: 82 })); // different object

let checks = 0;
[5, 12, 8, 20].some((n) => {
  checks += 1;
  return n > 10;
});
console.log('callbacks run by some:', checks);

console.log(students.at(-1).name, [[1, 2], [3]].flat(), ['a b', 'c'].flatMap((x) => x.split(' ')));
console.log([1, undefined, 3].find((x) => x === undefined), [1, undefined, 3].findIndex((x) => x === undefined));

Run with Node.js v24.22.1 as js-59.js; two runs gave identical output. Output: { name: 'Ravi', marks: 35 } 1 3 Dev undefined -1 true true false true true -1 2 false callbacks run by some: 2 Dev [ 1, 2, 3 ] [ 'a', 'b', 'c' ] undefined 1

Key points

  • includes checks for a value and finds NaN; indexOf returns a position and does not.
  • find gives the first matching item; findIndex gives its index or -1.
  • some is "any", every is "all"; both stop early.
  • some on [] is false; every on [] is true.
  • findLast and findLastIndex search from the end.

Common mistakes

  • Using filter(...)[0] when find is enough.
  • Using indexOf to look for NaN.
  • Using includes with objects and expecting content comparison.
  • Forgetting that every on an empty array is true.

Follow-ups

  • How would you check whether two arrays share at least one item?
  • What does find return when the array contains undefined, and how do you handle it?
  • How is flatMap different from map followed by flat?

Tips

  • Start with the question each method answers: first item, position, any, or all.
  • Mention the empty-array results; they are a favorite trick question.
  • Say that find, some, and every stop early, which makes them cheaper than filter.
60.javascript-0060Easyfresher

What is a callback in JavaScript, what is callback hell, and how do you avoid it?

A callback is a function passed to another function to be called later, either synchronously (like map) or asynchronously (like setTimeout). Deeply nested asynchronous callbacks, called callback hell, are hard to read and to handle errors in. Named functions, promises, and async/await flatten the code, and util.promisify wraps error-first callback APIs.

Full answer

In JavaScript, functions are values, so one function can receive another and call it when needed. That received function is a callback. A synchronous callback, such as the one given to map, is called before the outer function returns. An asynchronous callback is called later, after work such as a timer, a file read, or a network request has finished.

Node.js popularized the error-first convention: the callback receives (error, result), and the code checks error first. Every step must handle errors itself, and a throw inside an asynchronous callback cannot be caught by a try/catch around the outer call.

Callback hell appears when each step depends on the previous result and is nested inside it. The code drifts to the right, error handling is repeated at every level, and sharing data between steps is awkward. A deeper problem is inversion of control: you hand your function to code you do not control, and trust it to call back once, with the right arguments, at the right time.

There are several ways out. Name the functions and keep them at the top level, which flattens the nesting. Wrap callback APIs in promises, so steps chain with then and errors flow to one catch. Use async/await for code that reads in order. In Node.js, util.promisify turns an error-first function into one that returns a promise.

Callbacks are still fine for events and simple cases, such as addEventListener.

javascript
const { promisify } = require('node:util');

function loadStudent(id, callback) {
  setTimeout(() => {
    if (id < 0) callback(new Error('invalid id'));
    else callback(null, { id, name: 'Asha' });
  }, 5);
}
function loadMarks(student, callback) {
  setTimeout(() => callback(null, { ...student, marks: 88 }), 5);
}

// Nested callbacks: each step sits inside the one before it.
loadStudent(1, (error, student) => {
  if (error) return console.log('nested error:', error.message);
  loadMarks(student, (error2, withMarks) => {
    if (error2) return console.log('nested error:', error2.message);
    console.log('nested result:', withMarks);
  });
});

// The same flow with promisified functions and async/await.
const loadStudentAsync = promisify(loadStudent);
const loadMarksAsync = promisify(loadMarks);

(async () => {
  await new Promise((resolve) => setTimeout(resolve, 50));
  try {
    const student = await loadStudentAsync(1);
    console.log('flat result:', await loadMarksAsync(student));
    await loadStudentAsync(-1);
  } catch (error) {
    console.log('one catch for every step:', error.message);
  }

  try {
    setTimeout(() => {
      throw new Error('thrown later');
    }, 0);
  } catch (error) {
    console.log('never printed');
  }
})();
process.on('uncaughtException', (error) => console.log('uncaught outside try/catch:', error.message));

Run with Node.js v24.22.1 as js-60.js; two runs gave identical output. Output: nested result: { id: 1, name: 'Asha', marks: 88 } flat result: { id: 1, name: 'Asha', marks: 88 } one catch for every step: invalid id uncaught outside try/catch: thrown later

Key points

  • A callback is a function passed in to be called later, sync or async.
  • Error-first style: callback(error, result).
  • try/catch cannot catch errors thrown later inside an async callback.
  • Callback hell is deep nesting plus repeated error handling and inversion of control.
  • Fixes: named functions, promises, async/await, and promisify.

Common mistakes

  • Wrapping an asynchronous call in try/catch and expecting it to catch errors from the callback.
  • Calling a callback twice, for example after both a success path and an error path.
  • Mixing styles: a function that sometimes calls back synchronously and sometimes asynchronously.
  • Nesting more than two levels without extracting named functions.

Follow-ups

  • How would you write promisify yourself?
  • What is the difference between a synchronous and an asynchronous callback in terms of when errors surface?
  • Why is it a problem when an API calls its callback sometimes synchronously and sometimes later?

Tips

  • Define a callback, then give both a sync and an async example.
  • Mention inversion of control; it is the deeper problem behind callback hell.
  • Show promisify or a manual promise wrapper as the bridge between old and new styles.