← Interview prep

JavaScript interview questions

Language fundamentals, ES features, and async behavior.

200 questions · Page 8 of 10

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

Page 8 of 10

Questions 141–160 of 200 · 0 of 20 on this page marked learned

141.javascript-0141Hardsenior

What are custom elements and shadow DOM, how does their lifecycle work, and how would you build a small reusable component?

Custom elements let you define your own HTML tag with a class that extends HTMLElement, registered with customElements.define, with lifecycle callbacks such as connectedCallback and attributeChangedCallback. Shadow DOM gives the component a private DOM tree with scoped styles, and slots let users place their own content inside. Together they form framework-free components that work in any page.

Full answer

Web Components are three browser standards: custom elements, shadow DOM, and templates with slots.

Custom elements: write a class that extends HTMLElement and register it with customElements.define('user-card', UserCard). The tag name must contain a hyphen. After registration, <user-card> in HTML or document.createElement('user-card') creates an instance. Elements already in the page before the definition are upgraded when it is registered.

Lifecycle callbacks:

  • constructor: runs on creation or upgrade. Call super() first, set up state and the shadow root, and do not read attributes or children or add attributes here, because they may not exist yet.
  • connectedCallback: the element was added to the document. Render and add listeners here. It can run more than once if the element is moved.
  • disconnectedCallback: it was removed. Clean up timers, global listeners, and observers.
  • attributeChangedCallback(name, oldValue, newValue): called for attributes listed in static observedAttributes, including the initial values.
  • adoptedCallback: moved to another document (rare).

Shadow DOM: this.attachShadow({ mode: 'open' }) creates a separate DOM tree. Styles inside do not leak out, and page styles do not leak in, except inherited properties and CSS custom properties, which are the intended way to theme a component. Elements inside are hidden from document.querySelector.

Slots: <slot> inside the shadow tree shows the light DOM children given by the user, and named slots (<slot name="title">) place children that have slot="title".

Communication: pass data in through attributes (strings) and properties (any value), and send data out with CustomEvent. Events that must cross the shadow boundary need composed: true, and bubbles: true to travel up.

Security: when you build HTML from attribute values, escape them or build nodes with textContent, otherwise the component is an XSS hole.

Trade-offs: no built-in templating or state updates (you write them or use a small library such as Lit), and server-side rendering support needs extra work (declarative shadow DOM). The big benefit is interoperability across frameworks.

javascript
const log = [];
const escapeHtml = (text) => text.replace(/[&<>"']/g, (ch) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[ch]));

class UserCard extends HTMLElement {
  static observedAttributes = ['name', 'role'];
  #root;

  constructor() {
    super();
    this.#root = this.attachShadow({ mode: 'open' });
    // one delegated listener on the shadow root survives re-rendering
    this.#root.addEventListener('click', (event) => {
      const button = event.target.closest('button');
      if (!button) return;
      const detail = { name: this.getAttribute('name') };
      button.dispatchEvent(new CustomEvent('select', { detail, bubbles: true, composed: true }));
      button.dispatchEvent(new CustomEvent('select-local', { detail, bubbles: true, composed: false }));
    });
    log.push('constructor');
  }

  connectedCallback() {
    log.push('connected');
    this.#render();
  }

  disconnectedCallback() {
    log.push('disconnected');
  }

  attributeChangedCallback(attribute, oldValue, newValue) {
    log.push(`attribute ${attribute}: ${oldValue} -> ${newValue}`);
    if (this.isConnected) this.#render();
  }

  #render() {
    const name = escapeHtml(this.getAttribute('name') ?? 'unknown');
    const role = escapeHtml(this.getAttribute('role') ?? 'member');
    this.#root.innerHTML = `
      <style>h2 { color: teal; } .role { font-style: italic; }</style>
      <h2>${name}</h2>
      <span class="role">${role}</span>
      <slot>no extra content</slot>
      <button>Select</button>`;
  }
}

// An element in the page before the definition is upgraded when it is registered
document.body.innerHTML = '<user-card name="Asha" role="admin"><p>Extra note</p></user-card>';
const card = document.querySelector('user-card');
log.push('defined before upgrade: ' + Boolean(customElements.get('user-card')));
customElements.define('user-card', UserCard);
log.push('defined after: ' + Boolean(customElements.get('user-card')) + ', upgraded: ' + (card instanceof UserCard));

const shadow = card.shadowRoot;
console.log(log.join('\n'));
console.log('shadow h2:', shadow.querySelector('h2').textContent, '| role:', shadow.querySelector('.role').textContent);
console.log('hidden from the page:', document.querySelector('h2'), '| in shadow:', Boolean(shadow.querySelector('h2')));
console.log('slotted nodes:', shadow.querySelector('slot').assignedNodes().map((node) => node.textContent));

log.length = 0;
card.setAttribute('name', 'Ben <script>alert(1)</script>');
console.log(log);
console.log('escaped text shown as text:', shadow.querySelector('h2').textContent, '| script elements:', shadow.querySelectorAll('script').length);

const reached = [];
document.addEventListener('select', (event) => reached.push('select from ' + event.target.localName + ' for ' + event.detail.name));
document.addEventListener('select-local', () => reached.push('select-local'));
shadow.querySelector('button').click();
console.log('events that reached the document:', reached);

log.length = 0;
const created = document.createElement('user-card');
created.setAttribute('name', 'Chen');
document.body.append(created);
created.remove();
console.log(log);

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: defined before upgrade: false constructor attribute name: null -> Asha attribute role: null -> admin connected defined after: true, upgraded: true shadow h2: Asha | role: admin hidden from the page: null | in shadow: true slotted nodes: [ 'Extra note' ] [ 'attribute name: Asha -> Ben <script>alert(1)</script>' ] escaped text shown as text: Ben <script>alert(1)</script> | script elements: 0 events that reached the document: [ 'select from user-card for Ben <script>alert(1)</script>' ] [ 'constructor', 'attribute name: null -> Chen', 'connected', 'disconnected' ]

Key points

  • Custom elements are classes extending HTMLElement, registered with a hyphenated tag name.
  • Lifecycle: constructor, connectedCallback, disconnectedCallback, attributeChangedCallback with observedAttributes.
  • Shadow DOM scopes styles and hides internals; slots project the user's children.
  • Data in through attributes and properties, out through composed CustomEvents.
  • Escape or use textContent for attribute values; consider Lit and declarative shadow DOM.

Common mistakes

  • Reading attributes or children in the constructor.
  • Building innerHTML from attribute values without escaping.
  • Forgetting composed: true so an event from inside the shadow tree stops at the shadow boundary.
  • Leaving listeners and timers running after disconnectedCallback.

Follow-ups

  • How do CSS custom properties and the part attribute let users style a shadow tree?
  • What is declarative shadow DOM and why does it matter for server rendering?
  • When would you use Lit or another library instead of plain custom elements?

Tips

  • List the lifecycle callbacks and what each is for.
  • Say that shadow DOM scopes styles and slots project user content.
  • Mention escaping and composed events.
142.javascript-0142Mediummid

How do you implement a lazily computed property with a getter that runs once and then caches its value?

Define a getter that computes the value on first access, then replaces itself with a plain data property using Object.defineProperty (or stores the result in a private field or with ??=), so later reads are simple property reads. It saves work for values that are expensive and often not needed. Be careful with values that can change, with null results, and with inheritance.

Full answer

A lazy property postpones an expensive computation until the first time it is read. If it is never read, it never runs.

Pattern 1, self-replacing getter: the getter computes the value, then calls Object.defineProperty(this, 'name', { value, writable: false, enumerable: true, configurable: true }). That shadows the getter on the instance with a data property, so the next reads do not call any function. This is fast after the first access, and it does not need a separate cache field. It only works when the getter is defined on the prototype (a class getter) or on the object itself with configurable: true.

Pattern 2, cached field in the class: store the result in a private field and use the nullish assignment: get report() { return this.#report ??= buildReport(this.data); }. It is short and readable, and the cache stays private. Note that ??= recomputes when the cached value is null or undefined. Use a flag or a Symbol sentinel if those are valid results.

Pattern 3, a reusable helper: lazy(obj, key, factory) defines a getter on the object that calls the factory once, then redefines the property as a data property. It can be used on object literals, or for module-level configuration.

Things to watch:

  • Invalidation: a lazy value is computed once. If the inputs change later, the value is stale. Either make the object immutable, or provide a method to reset the cache.
  • Errors: if the factory throws, nothing is cached, and the next access tries again, which is usually what you want. State it clearly.
  • Inheritance and this: a getter defined on a prototype is shared, but the cached value must be stored per instance (use this, not the prototype).
  • Serialization: a self-replacing getter becomes an own enumerable property after the first read, so JSON.stringify results can change depending on whether it was read. Make it non-enumerable if that matters.
  • Async: for async values, cache the promise, not the resolved value.

Use lazy properties for expensive parsing, large derived data, and optional features. Do not use them to hide slow code on a hot path without measuring.

javascript
const log = [];
const expensive = (label) => {
  log.push('computing ' + label);
  return label.toUpperCase();
};

// Pattern 1: self-replacing getter on the prototype
class Report {
  constructor(title) {
    this.title = title;
  }
  get summary() {
    const value = expensive('summary of ' + this.title);
    Object.defineProperty(this, 'summary', { value, enumerable: false, configurable: true });
    return value;
  }
}
const report = new Report('q4');
console.log('keys before:', Object.keys(report));
console.log(report.summary, report.summary, report.summary);
console.log('computed times:', log.length, '| own property now:', Object.hasOwn(report, 'summary'), '| keys:', Object.keys(report));
console.log('another instance is separate:', new Report('q1').summary, log.length);

// Pattern 2: private field with ??=
class Config {
  #parsed;
  constructor(text) {
    this.text = text;
  }
  get parsed() {
    return (this.#parsed ??= JSON.parse(this.text));
  }
  reset() {
    this.#parsed = undefined;
  }
}
const config = new Config('{"retries":3}');
console.log(config.parsed === config.parsed, config.parsed);
const broken = new Config('{bad json');
for (let attempt = 1; attempt <= 2; attempt++) {
  try {
    broken.parsed;
  } catch (error) {
    console.log('attempt', attempt, 'failed again:', error.name);
  }
}

// null results with ??= are recomputed, a sentinel fixes that
let calls = 0;
const nullable = { _v: undefined, get value() { calls++; return (this._v ??= null); } };
nullable.value; nullable.value;
console.log('null is not cached by ??=, calls:', calls);

// Pattern 3: a reusable helper
function lazy(object, key, factory) {
  Object.defineProperty(object, key, {
    configurable: true,
    enumerable: true,
    get() {
      const value = factory.call(this);
      Object.defineProperty(this, key, { value, enumerable: true, configurable: true, writable: true });
      return value;
    },
  });
  return object;
}
log.length = 0;
const settings = lazy({ name: 'app' }, 'cache', () => expensive('cache for app'));
console.log(log.length, settings.cache, settings.cache, log.length, JSON.stringify(settings));

// async: cache the promise
const lazyUser = { get user() { const p = Promise.resolve({ id: 1 }); Object.defineProperty(this, 'user', { value: p }); return p; } };
console.log('same promise returned:', lazyUser.user === lazyUser.user);

Run with Node.js v24.22.1 as js-142.js; two runs gave identical output. Output: keys before: [ 'title' ] SUMMARY OF Q4 SUMMARY OF Q4 SUMMARY OF Q4 computed times: 1 | own property now: true | keys: [ 'title' ] another instance is separate: SUMMARY OF Q1 2 true { retries: 3 } attempt 1 failed again: SyntaxError attempt 2 failed again: SyntaxError null is not cached by ??=, calls: 2 0 CACHE FOR APP CACHE FOR APP 1 {"name":"app","cache":"CACHE FOR APP"} same promise returned: true

Key points

  • A lazy getter computes on first read and never again; unread values cost nothing.
  • Self-replacing: defineProperty on the instance turns the getter into a data property.
  • Cached private field with ??= is short, but null or undefined results recompute.
  • Watch for stale values, errors that are not cached, and enumerable properties changing JSON output.
  • For async values, cache the promise.

Common mistakes

  • Caching a value that depends on data that can change later.
  • Using ??= when null or undefined are valid results.
  • Storing the cache on the prototype so all instances share one value.
  • Making lazy properties enumerable and getting different JSON depending on read order.

Follow-ups

  • How would you reset a self-replacing getter?
  • How does lazy initialization differ from memoizing a function?
  • Why cache the promise instead of the resolved value for async data?

Tips

  • Show the self-replacing getter and the ??= field as the two main patterns.
  • Mention stale values and errors explicitly.
  • Say that you measure before adding laziness.
143.javascript-0143Mediummid

How do the module, singleton, and factory patterns look in modern JavaScript?

The module pattern hides private state in a closure (an IIFE) or, today, in an ES module file, and exports a small public API. A singleton is one shared instance, and in JavaScript the module cache already gives you one: export an instance and every importer gets the same object. A factory is a function that creates objects, hiding construction details and allowing different types or configurations.

Full answer

Design patterns are common solutions to recurring problems. In JavaScript, language features often make them smaller.

Module pattern: before ES modules, an IIFE (immediately invoked function expression) created a private scope and returned a public object, which gave private state through closure: const counter = (() => { let n = 0; return { inc: () => ++n }; })(). Today, every ES module file is already a private scope. Anything not exported is private, and the exports form the public API. Use the file, and use closures or #private fields for per-instance privacy.

Singleton: a class or object that must exist once, such as a configuration object, a logger, or a database connection pool. The classic version stores the instance in a static property and returns it from getInstance(). In JavaScript, simpler options exist. A module is evaluated once and cached, so export const logger = new Logger() gives every importer the same instance. The same applies to require through the require.cache. Caveats: the cache is per module path and per realm, so duplicate copies of a package in node_modules, or the same file loaded through different URLs or in a worker, create separate instances. Singletons are global state: they make testing harder (state leaks between tests) and hide dependencies. Prefer passing the instance in (dependency injection), and keep the singleton as the default wiring.

Factory: a function (or static method) that returns objects without exposing how they are built. Uses: choosing the right class by input (createShape('circle')), applying defaults and validation, returning plain objects with closures for privacy, and creating test doubles. A factory function avoids new and this, so there are no binding problems, and it can return different types. A registry (a Map from type name to constructor) makes factories extensible without a long switch.

When asked in interviews, give a short definition, the modern JavaScript form, and one downside for each. For singletons the downside is global state, for factories it is indirection, and for modules it is that circular imports can break initialization.

javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

// Module pattern with an IIFE: n is private
const counter = (() => {
  let n = 0;
  return { inc: () => ++n, get value() { return n; } };
})();
counter.inc();
counter.inc();
console.log('module pattern:', counter.value, counter.n);

// Singleton with a static instance
class Logger {
  static #instance;
  #lines = [];
  constructor() {
    if (Logger.#instance) return Logger.#instance;
    Logger.#instance = this;
  }
  log(line) {
    this.#lines.push(line);
    return this;
  }
  get count() {
    return this.#lines.length;
  }
}
const a = new Logger();
const b = new Logger();
a.log('one');
b.log('two');
console.log('singleton:', a === b, a.count);

// Singleton through the module cache
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'singleton-'));
fs.writeFileSync(path.join(dir, 'config.js'), 'module.exports = { loads: (globalThis.__loads = (globalThis.__loads ?? 0) + 1) };');
const first = require(path.join(dir, 'config.js'));
const second = require(path.join(dir, 'config.js'));
console.log('module cache gives one instance:', first === second, 'module ran', globalThis.__loads, 'time(s)');
delete require.cache[require.resolve(path.join(dir, 'config.js'))];
console.log('after clearing the cache a new instance appears:', require(path.join(dir, 'config.js')) !== first, 'runs:', globalThis.__loads);
fs.rmSync(dir, { recursive: true, force: true });

// Factory with a registry
class Circle { constructor({ r }) { this.area = Math.PI * r * r; } }
class Rect { constructor({ w, h }) { this.area = w * h; } }
const registry = new Map([['circle', Circle], ['rect', Rect]]);
function createShape(type, options) {
  const Shape = registry.get(type);
  if (!Shape) throw new RangeError(`Unknown shape: ${type}`);
  return new Shape(options);
}
console.log(createShape('circle', { r: 1 }).area.toFixed(2), createShape('rect', { w: 2, h: 3 }).area);
registry.set('square', class Square extends Rect { constructor({ s }) { super({ w: s, h: s }); } });
console.log(createShape('square', { s: 4 }).area);
try {
  createShape('hexagon', {});
} catch (error) {
  console.log(error.message);
}

// Factory function with closure privacy and no new
function createAccount(owner, balance = 0) {
  return {
    owner,
    deposit(amount) { balance += amount; return balance; },
    get balance() { return balance; },
  };
}
const account = createAccount('Asha', 10);
account.deposit(5);
console.log(account.balance, Object.keys(account));

Run with Node.js v24.22.1 as js-143.js; two runs gave identical output. Output: module pattern: 2 undefined singleton: true 2 module cache gives one instance: true module ran 1 time(s) after clearing the cache a new instance appears: true runs: 2 3.14 6 16 Unknown shape: hexagon 15 [ 'owner', 'deposit', 'balance' ]

Key points

  • Module pattern: private state in an IIFE closure, or simply an ES module file with exports as the API.
  • Singleton: one shared instance; the module cache gives it for free, but duplicate copies break it.
  • Singletons are global state that complicates tests; prefer injection with a default instance.
  • Factory: a function that builds objects, hiding construction, choosing types, and avoiding new and this.
  • A registry Map makes a factory extensible; each pattern has a trade-off to state.

Common mistakes

  • Using a singleton for state that tests need to reset.
  • Assuming a module is loaded once when two copies of the package exist.
  • Using long switch statements in factories instead of a registry.
  • Using classes with static getInstance in JavaScript when a module export is enough.

Follow-ups

  • How does dependency injection reduce the problems of singletons?
  • Why can the same module be evaluated twice in a project?
  • How does the factory pattern help when writing tests?

Tips

  • Give the modern form of each pattern, not only the textbook version.
  • Mention the module cache as the natural singleton.
  • State one downside for each pattern.
144.javascript-0144Mediummid

What are the observer and strategy patterns, and how do you implement them in JavaScript?

Observer lets a subject notify any number of subscribed observers when its state changes, without knowing who they are, which is the idea behind events and reactive stores. Strategy puts interchangeable algorithms behind one interface and lets the caller choose one at runtime, which in JavaScript is often just passing a function. Both reduce conditionals and coupling.

Full answer

Both are behavioral patterns that decouple parts of a program.

Observer: a subject keeps a list of observers and calls them when something changes. The subject does not know what the observers do. Examples are DOM events (addEventListener), Node's EventEmitter, store subscriptions in UI libraries, and MutationObserver. A good implementation has:

  • subscribe(observer) that returns an unsubscribe function, so cleanup is easy and no one needs a reference to the original function.
  • notify(data) that iterates over a copy of the observer list, so observers can unsubscribe while being called.
  • Error isolation, so one failing observer does not stop the rest.
  • No memory leaks: observers that are never removed keep the subject, and everything they capture, alive. This is a classic leak with long-lived subjects.

Observer differs from publish and subscribe: in observer, observers subscribe directly to the subject; in pub/sub, a broker sits between publishers and subscribers who share only topic names.

Strategy: define a family of algorithms with the same signature, put each in its own unit, and choose one at runtime. In class-based languages you create an interface and several classes. In JavaScript, functions are first-class values, so a strategy is usually a function, and the context stores it or receives it as an argument. A map from names to functions replaces a growing if or switch chain: const strategies = { flat, percent, bulk }. Examples: sort comparators, validation rules, pricing and shipping rules, retry policies, and formatting.

Benefits: you add a new behavior without editing the code that uses it (open and closed principle), and each strategy is easy to test alone. Cost: more units to name and find, and for two simple branches a plain if is clearer.

Together they appear often: a settings object holds a strategy and notifies observers when the strategy changes.

javascript
// Observer
class Store {
  #state;
  #observers = new Set();
  constructor(initial) {
    this.#state = initial;
  }
  get state() {
    return this.#state;
  }
  subscribe(observer) {
    this.#observers.add(observer);
    return () => this.#observers.delete(observer);
  }
  set(change) {
    const previous = this.#state;
    this.#state = { ...previous, ...change };
    for (const observer of [...this.#observers]) {
      try {
        observer(this.#state, previous);
      } catch (error) {
        console.log('observer failed:', error.message);
      }
    }
  }
  get observerCount() {
    return this.#observers.size;
  }
}

const store = new Store({ theme: 'light', user: null });
const seen = [];
const stopLogging = store.subscribe((state, previous) => seen.push(`log: ${previous.theme} -> ${state.theme}`));
store.subscribe(() => { throw new Error('bad observer'); });
const stopOnce = store.subscribe(() => { seen.push('once'); stopOnce(); });
store.set({ theme: 'dark' });
store.set({ theme: 'light' });
stopLogging();
store.set({ theme: 'dark' });
console.log(seen, 'observers left:', store.observerCount);

// Strategy: plain functions chosen by name
const discounts = {
  none: (price) => price,
  percent: (price, value) => price * (1 - value / 100),
  flat: (price, value) => Math.max(0, price - value),
  bulk: (price, value, quantity) => (quantity >= 10 ? price * 0.9 : price),
};
function totalPrice({ price, quantity, strategy = 'none', value = 0 }) {
  const apply = discounts[strategy];
  if (!apply) throw new RangeError('Unknown discount: ' + strategy);
  return Number((apply(price, value, quantity) * quantity).toFixed(2));
}
console.log(totalPrice({ price: 50, quantity: 2 }));
console.log(totalPrice({ price: 50, quantity: 2, strategy: 'percent', value: 20 }));
console.log(totalPrice({ price: 50, quantity: 2, strategy: 'flat', value: 60 }));
console.log(totalPrice({ price: 50, quantity: 10, strategy: 'bulk' }));
try {
  totalPrice({ price: 1, quantity: 1, strategy: 'coupon' });
} catch (error) {
  console.log(error.message);
}

// Strategies as comparators
const people = [{ name: 'Chen', age: 42 }, { name: 'Asha', age: 31 }, { name: 'Ben', age: 25 }];
const sortBy = { name: (a, b) => a.name.localeCompare(b.name), age: (a, b) => a.age - b.age };
console.log(people.toSorted(sortBy.name).map((p) => p.name), people.toSorted(sortBy.age).map((p) => p.name));

Run with Node.js v24.22.1 as js-144.js; two runs gave identical output. Output: observer failed: bad observer observer failed: bad observer observer failed: bad observer [ 'log: light -> dark', 'once', 'log: dark -> light' ] observers left: 1 100 80 0 450 Unknown discount: coupon [ 'Asha', 'Ben', 'Chen' ] [ 'Ben', 'Asha', 'Chen' ]

Key points

  • Observer: a subject notifies subscribed observers of changes without knowing them; subscribe returns an unsubscribe function.
  • Iterate over a copy, isolate errors, and remove observers to avoid leaks.
  • Pub/sub adds a broker between publishers and subscribers; observer connects them directly.
  • Strategy: interchangeable algorithms chosen at runtime; in JavaScript usually plain functions.
  • A map of strategies replaces long conditionals; use plain if for two simple cases.

Common mistakes

  • Never unsubscribing observers from long-lived subjects, which leaks memory.
  • Iterating the live observer collection while observers remove themselves.
  • Letting one throwing observer stop the others.
  • Building a class hierarchy for strategies when functions are enough.

Follow-ups

  • How is the observer pattern different from publish and subscribe?
  • When is a plain if statement better than the strategy pattern?
  • How would you combine strategy with dependency injection in tests?

Tips

  • Show that subscribe returns an unsubscribe function.
  • Say that in JavaScript a strategy is often just a function.
  • Name the leak risk of observers.
145.javascript-0145Mediummid

What is transpilation, what does Babel do, and how is it different from a polyfill?

Transpilation rewrites new syntax into older syntax that the target browsers understand, for example arrow functions, optional chaining, or classes. A polyfill adds a missing runtime feature, such as Array.prototype.at or Promise, by defining it in JavaScript. Babel's preset-env does the first based on your target list and can add imports for the second. Syntax needs transpiling, new APIs need polyfills, and fewer targets mean less code.

Full answer

New JavaScript features come in two kinds, and they are handled differently.

Syntax: new grammar such as arrow functions, ?., ??, classes, private fields, or async/await. An older engine cannot parse it at all, and it throws a SyntaxError for the whole file. These need transpilation: a tool rewrites them into equivalent older syntax. Babel is the classic transpiler, and SWC and esbuild do similar work faster. TypeScript's compiler also lowers syntax to a target.

APIs: new built-in functions and objects such as Array.prototype.at, Object.groupBy, Promise.allSettled, fetch, or structuredClone. Parsing works, but calling a missing function throws a TypeError at runtime. Syntax tools cannot fix this. A polyfill (from the core-js library, for example) defines the missing function if it is not already there. Some features cannot be polyfilled fully, for example Proxy.

How Babel is configured: @babel/preset-env reads your targets, either given directly or from a browserslist configuration, such as defaults, not dead or chrome >= 100. It transforms only the syntax that the targets lack. With useBuiltIns: 'usage' it adds core-js imports only for the APIs your code uses and the targets lack. Babel also adds small helper functions to the output (a class helper, a regenerator runtime for async functions on very old targets), which makes bundles bigger.

Practical points:

  • Choose targets honestly. Each very old target adds code, slows builds, and increases download size for everyone. Modern teams often target the last few versions of evergreen browsers, which needs little or no transpiling.
  • Serve modern code to modern browsers and a fallback bundle only if needed (type="module" and nomodule).
  • A library should usually publish modern syntax and let the application's build step lower it for the application's own targets.
  • Source maps map the transformed code back to the original for debugging.
  • Check support with a compatibility table instead of guessing.
javascript
const babel = require('@babel/core');

function transform(code, targets) {
  return babel.transformSync(code, {
    babelrc: false,
    configFile: false,
    presets: [['@babel/preset-env', { targets }]],
  }).code;
}

const cases = {
  'arrow function': 'const double = (n) => n * 2;',
  'template literal': 'const text = `Hello ${name}`;',
  'optional chaining and ??': 'const city = user.address?.city ?? "unknown";',
  'new API call, not syntax': 'const last = list.at(-1);',
};

for (const [label, code] of Object.entries(cases)) {
  console.log(`--- ${label}`);
  console.log('modern target (chrome 120):', transform(code, { chrome: '120' }).replace(/\n/g, ' '));
  console.log('old target (chrome 40)    :', transform(code, { chrome: '40' }).replace(/\n/g, ' '));
}

console.log('--- a missing API fails only when it is called');
try {
  const missing = {};
  missing.at(0);
} catch (error) {
  console.log('missing method gives:', error.name);
}
console.log('@babel/core version:', babel.version);

Run with Node.js v24.22.1 as js-145.js; two runs gave identical output. Output: --- arrow function modern target (chrome 120): const double = n => n * 2; old target (chrome 40) : var double = function double(n) { return n * 2; }; --- template literal modern target (chrome 120): const text = `Hello ${name}`; old target (chrome 40) : var text = "Hello ".concat(name); --- optional chaining and ?? modern target (chrome 120): const city = user.address?.city ?? "unknown"; old target (chrome 40) : var _user$address$city, _user$address; var city = (_user$address$city = (_user$address = user.address) === null || _user$address === void 0 ? void 0 : _user$address.city) !== null && _user$address$city !== void 0 ? _user$address$city : "unknown"; --- new API call, not syntax modern target (chrome 120): const last = list.at(-1); old target (chrome 40) : var last = list.at(-1); --- a missing API fails only when it is called missing method gives: TypeError @babel/core version: 8.1.5

Key points

  • Transpilation rewrites unsupported syntax; polyfills add missing runtime APIs; they solve different problems.
  • Old engines fail on new syntax with a SyntaxError for the whole file; missing APIs fail with a TypeError when called.
  • preset-env uses targets (browserslist) so it only transforms what is needed; useBuiltIns usage adds needed polyfills.
  • Smaller target lists mean smaller and faster bundles; helpers and polyfills add size.
  • Use source maps, and let applications, not libraries, decide the final syntax level.

Common mistakes

  • Thinking Babel adds missing APIs by itself without a polyfill setup.
  • Targeting very old browsers by default and shipping large bundles to everyone.
  • Publishing a library transpiled to very old syntax.
  • Assuming that a polyfill can reproduce every feature, such as Proxy.

Follow-ups

  • What is browserslist and how do build tools share it?
  • How do the module and nomodule script attributes serve different bundles?
  • Why are SWC and esbuild often faster than Babel, and what do they give up?

Tips

  • Separate syntax from APIs in the first sentence.
  • Mention targets and browserslist as the lever for bundle size.
  • Say that a library should leave final lowering to the application.
146.javascript-0146Mediummid

What are the basics of testing JavaScript code with Jest or Vitest, including assertions, mocks, async tests, and fake timers?

A unit test arranges inputs, runs one behavior, and asserts the result, with each test independent and fast. Jest and Vitest share a similar API: describe and it (or test) to organize, expect with matchers for assertions, mock functions (jest.fn or vi.fn) to replace dependencies and check calls, fake timers to control time, and async support through returning or awaiting promises. Test behavior, not implementation details.

Full answer

Structure: describe('name', () => { ... }) groups tests, it('does something', () => { ... }) or test(...) defines one. Hooks (beforeEach, afterEach, beforeAll, afterAll) set up and clean up shared state. A good test follows arrange, act, assert: prepare the input, call the code, check the result. Each test must be independent and not rely on the order of other tests.

Assertions: expect(value).toBe(3) for primitives and identity, toEqual for deep equality of objects and arrays, toStrictEqual to also check undefined properties and types, toThrow for errors, toContain, toMatchObject, and resolves and rejects for promises. Snapshot tests store the output and compare later, which is quick to write and noisy to maintain, so use them for small stable outputs.

Mocks: a mock function (jest.fn() in Jest, vi.fn() in Vitest) records calls and can return fixed values: fn.mockReturnValue(5), expect(fn).toHaveBeenCalledWith('a'). Use mocks to replace slow or external dependencies, such as network, time, and randomness. Prefer passing dependencies in as arguments, which makes mocking easy, over patching modules. A spy (jest.spyOn, vi.spyOn) wraps a real method so you can observe it, and restoring spies after each test avoids leaks between tests.

Async code: return the promise, or use async tests with await, or await expect(promise).rejects.toThrow(). A test that forgets to await can pass even if the code fails, because it finished before the assertion ran.

Timers: fake timers (jest.useFakeTimers(), vi.useFakeTimers()) replace setTimeout and Date so you can advance time (advanceTimersByTime(1000)) with no real waiting. This is the right way to test debounce, retries, and timeouts.

Good practice: test behavior and public results, not private details, keep tests fast and deterministic (no real network, no real clock, no random values without a seed), cover edge cases and error paths, and run tests in continuous integration. Coverage numbers show what is not tested, not whether tests are good. Vitest is faster for Vite projects and ES modules, and Jest is widely used with a large ecosystem. The newer built-in node:test runner needs no installation.

The snippet below uses only Node.js built-ins (node:assert, and the mock tools of node:test), with the same ideas. The Jest and Vitest calls in the answer text were not run here.

javascript
const assert = require('node:assert/strict');
const { mock } = require('node:test');

// code under test
function debounce(fn, wait) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), wait);
  };
}
async function loadUser(fetchUser, id) {
  if (!Number.isInteger(id)) throw new TypeError('id must be an integer');
  const user = await fetchUser(id);
  return { ...user, name: user.name.toUpperCase() };
}
const sum = (numbers) => numbers.reduce((total, n) => total + n, 0);

// a tiny runner with describe and it, so the output is easy to read
const results = [];
const tests = [];
let prefix = '';
const describe = (name, body) => {
  const outer = prefix;
  prefix += name + ' > ';
  body();
  prefix = outer;
};
const it = (name, test) => tests.push({ name: prefix + name, test });

describe('sum', () => {
  it('adds numbers', () => assert.equal(sum([1, 2, 3]), 6));
  it('returns 0 for an empty list', () => assert.equal(sum([]), 0));
  it('fails on purpose to show a failure (error on purpose)', () => assert.equal(sum([1, 1]), 3));
});

describe('loadUser', () => {
  it('uppercases the name and calls the fetcher once with the id', async () => {
    const fetchUser = mock.fn(async () => ({ id: 7, name: 'asha' }));
    const user = await loadUser(fetchUser, 7);
    assert.deepEqual(user, { id: 7, name: 'ASHA' });
    assert.equal(fetchUser.mock.callCount(), 1);
    assert.deepEqual(fetchUser.mock.calls[0].arguments, [7]);
  });
  it('rejects for a bad id and never calls the fetcher', async () => {
    const fetchUser = mock.fn();
    await assert.rejects(() => loadUser(fetchUser, 'x'), { name: 'TypeError', message: 'id must be an integer' });
    assert.equal(fetchUser.mock.callCount(), 0);
  });
  it('passes the failure of the fetcher on', async () => {
    await assert.rejects(() => loadUser(async () => { throw new Error('offline'); }, 1), /offline/);
  });
});

describe('debounce with fake timers', () => {
  it('calls once after the wait, with the last arguments', () => {
    mock.timers.enable({ apis: ['setTimeout'] });
    try {
      const spy = mock.fn();
      const debounced = debounce(spy, 100);
      debounced('a');
      debounced('b');
      debounced('c');
      mock.timers.tick(99);
      assert.equal(spy.mock.callCount(), 0);
      mock.timers.tick(1);
      assert.equal(spy.mock.callCount(), 1);
      assert.deepEqual(spy.mock.calls[0].arguments, ['c']);
    } finally {
      mock.timers.reset();
    }
  });
});

(async () => {
  for (const { name, test } of tests) {
    try {
      await test();
      results.push(`PASS ${name}`);
    } catch (error) {
      results.push(`FAIL ${name}: ${error.message.split('\n')[0]}`);
    }
  }
  console.log(results.join('\n'));
  console.log(`${results.filter((line) => line.startsWith('PASS')).length} passed, ${results.filter((line) => line.startsWith('FAIL')).length} failed`);
})();

Run with Node.js v24.22.1 as js-146.js; two runs gave identical output. Output: PASS sum > adds numbers PASS sum > returns 0 for an empty list FAIL sum > fails on purpose to show a failure (error on purpose): Expected values to be strictly equal: PASS loadUser > uppercases the name and calls the fetcher once with the id PASS loadUser > rejects for a bad id and never calls the fetcher PASS loadUser > passes the failure of the fetcher on PASS debounce with fake timers > calls once after the wait, with the last arguments 6 passed, 1 failed

Key points

  • Organize with describe and it; follow arrange, act, assert; keep tests independent.
  • Use toBe for primitives, toEqual for deep equality, toThrow and rejects for errors.
  • Mock functions replace external dependencies and record calls; prefer dependency injection.
  • Await promises in async tests; use fake timers for debounce, retries, and timeouts.
  • Test behavior, keep tests deterministic, and treat coverage as a hint.

Common mistakes

  • Forgetting to await an async test, so it passes before the assertion runs.
  • Testing private implementation details, so refactoring breaks tests that should still pass.
  • Using real timers, real network calls, or the real clock in unit tests.
  • Sharing state between tests and relying on their order.

Follow-ups

  • What is the difference between a mock, a stub, and a spy?
  • When are snapshot tests useful, and when are they harmful?
  • How do you test code that uses the current date or random numbers?

Tips

  • Describe arrange, act, assert and test independence.
  • Mention dependency injection as the way to make code testable.
  • Say that you test behavior, and use fake timers for time.
147.javascript-0147Mediummid

What is IntersectionObserver, and how do you use it for lazy loading images and infinite scroll?

IntersectionObserver reports asynchronously when a target element enters or leaves the viewport (or another root element), without scroll event handlers or layout reads. You create it with a callback and options (root, rootMargin, threshold), call observe on elements, and read isIntersecting and intersectionRatio from the entries. Typical uses are lazy loading, infinite scroll sentinels, and visibility analytics. Unobserve elements once their work is done.

Full answer

Before IntersectionObserver, code listened to scroll events and called getBoundingClientRect(), which forces layout and runs very often. The observer lets the browser compute visibility efficiently and notify you only when it changes.

Usage: const observer = new IntersectionObserver(callback, options), then observer.observe(element). The callback receives entries (one per element whose state changed) and the observer. Each entry has isIntersecting, intersectionRatio (from 0 to 1), target, boundingClientRect, and time.

Options:

  • root: the element used as the viewport. The default null is the browser viewport.
  • rootMargin: grows or shrinks the root box, like CSS margin, for example '200px' to start loading before an image is on screen.
  • threshold: a number or array of ratios at which to call back. 0 (default) means as soon as one pixel is visible, 1 means fully visible, and [0, 0.5, 1] reports at several steps.

Lazy loading images: put the real URL in data-src, observe each image, and when isIntersecting is true, set src from data-src and call unobserve. For simple cases, the native loading="lazy" attribute on img and iframe needs no JavaScript, so prefer it, and keep the observer for background images, videos, and custom behavior.

Infinite scroll: place a small sentinel element at the end of the list. When it intersects, load the next page, append items, and move the sentinel (the observer fires again if it is still visible). Guard against duplicate loads with a loading flag, and offer a way to reach the footer.

Details: the callback runs asynchronously, and the first call happens right after observe with the initial state. Call disconnect() when the component is removed, otherwise the observer keeps references. Elements with display: none never intersect. It does not report exact scroll positions, and sticky or transformed elements may behave in unexpected ways. Test with fakes, since jsdom has no layout engine.

Related: ResizeObserver for size changes and MutationObserver for DOM changes.

javascript
// jsdom has no layout engine, so it has no IntersectionObserver. This fake lets the logic be tested.
class FakeIntersectionObserver {
  static instances = [];
  constructor(callback, options = {}) {
    this.callback = callback;
    this.options = options;
    this.targets = new Set();
    FakeIntersectionObserver.instances.push(this);
  }
  observe(target) { this.targets.add(target); }
  unobserve(target) { this.targets.delete(target); }
  disconnect() { this.targets.clear(); }
  // test helper: pretend that these elements changed visibility
  trigger(changes) {
    const entries = changes
      .filter(([target]) => this.targets.has(target))
      .map(([target, isIntersecting]) => ({ target, isIntersecting, intersectionRatio: isIntersecting ? 1 : 0 }));
    this.callback(entries, this);
  }
}

// logic under test: receives the observer class, so it works with the real one and the fake
function lazyLoadImages(root, Observer) {
  const observer = new Observer((entries, obs) => {
    for (const entry of entries) {
      if (!entry.isIntersecting) continue;
      const img = entry.target;
      img.src = img.dataset.src;
      img.removeAttribute('data-src');
      obs.unobserve(img);
    }
  }, { rootMargin: '200px 0px' });
  root.querySelectorAll('img[data-src]').forEach((img) => observer.observe(img));
  return observer;
}

function infiniteScroll(list, sentinel, loadPage, Observer) {
  let page = 0;
  let loading = false;
  const observer = new Observer(async (entries) => {
    if (!entries.some((entry) => entry.isIntersecting) || loading) return;
    loading = true;
    for (const text of await loadPage(++page)) {
      const li = document.createElement('li');
      li.textContent = text;
      list.append(li);
    }
    loading = false;
  });
  observer.observe(sentinel);
  return observer;
}

document.body.innerHTML = `
  <img id="a" data-src="/photos/a.jpg" alt="A">
  <img id="b" data-src="/photos/b.jpg" alt="B">
  <ul id="list"></ul><div id="sentinel"></div>`;
const [a, b] = [document.getElementById('a'), document.getElementById('b')];

const lazy = lazyLoadImages(document, FakeIntersectionObserver);
console.log('observed:', lazy.targets.size, '| options:', JSON.stringify(lazy.options), '| src before:', a.getAttribute('src'));
lazy.trigger([[a, true], [b, false]]);
console.log('a loaded:', a.getAttribute('src'), '| b waiting:', b.getAttribute('src'), '| still observed:', lazy.targets.size);
lazy.trigger([[a, true]]);
console.log('already loaded image is ignored:', lazy.targets.size);
lazy.trigger([[b, true]]);
console.log('b loaded:', b.getAttribute('src'), '| observed:', lazy.targets.size);

const list = document.getElementById('list');
const sentinel = document.getElementById('sentinel');
let calls = 0;
const loadPage = async (page) => (calls++, [`item ${page}.1`, `item ${page}.2`]);
const scroller = infiniteScroll(list, sentinel, loadPage, FakeIntersectionObserver);

(async () => {
  scroller.trigger([[sentinel, true]]);
  scroller.trigger([[sentinel, true]]); // a second event while loading is ignored
  await new Promise((resolve) => setTimeout(resolve, 5));
  console.log('after two triggers during one load:', list.children.length, 'items, page loads:', calls);
  scroller.trigger([[sentinel, false]]);
  scroller.trigger([[sentinel, true]]);
  await new Promise((resolve) => setTimeout(resolve, 5));
  console.log('next page:', [...list.children].map((li) => li.textContent).join(', '));
  scroller.disconnect();
  console.log('disconnected, observed:', scroller.targets.size, '| real IntersectionObserver in jsdom:', typeof IntersectionObserver);
})();

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: observed: 2 | options: {"rootMargin":"200px 0px"} | src before: null a loaded: /photos/a.jpg | b waiting: null | still observed: 1 already loaded image is ignored: 1 b loaded: /photos/b.jpg | observed: 0 after two triggers during one load: 2 items, page loads: 1 next page: item 1.1, item 1.2, item 2.1, item 2.2 disconnected, observed: 0 | real IntersectionObserver in jsdom: undefined

Key points

  • The observer reports visibility changes asynchronously, replacing scroll handlers and layout reads.
  • Options: root, rootMargin to load early, threshold for ratios.
  • Lazy loading: swap data-src to src on intersection and unobserve; native loading="lazy" is simpler for images.
  • Infinite scroll uses a sentinel element, a loading flag, and attention to accessibility.
  • Disconnect when done; test with a fake because jsdom has no layout.

Common mistakes

  • Using scroll events and getBoundingClientRect for visibility checks.
  • Never calling unobserve or disconnect, which keeps elements and callbacks alive.
  • Triggering several page loads at once because there is no loading guard.
  • Ignoring native loading="lazy" for simple image lazy loading.

Follow-ups

  • How does rootMargin help to load content before it is visible?
  • How would you use thresholds to measure how long an ad is visible?
  • How is ResizeObserver different, and when would you use it?

Tips

  • Contrast with scroll handlers: asynchronous and efficient.
  • Give both use cases: lazy loading and a sentinel for infinite scroll.
  • Mention native lazy loading and accessibility for infinite lists.
148.javascript-0148Mediummid

How does MutationObserver work, what can it observe, and what are the common pitfalls?

MutationObserver watches a DOM node for changes to child nodes, attributes, or text, and calls your callback with a batch of records after the current script finishes, as a microtask. You configure what to watch with options such as childList, attributes, characterData, and subtree. Disconnect it when finished and avoid changing the observed node inside the callback in a way that triggers it again.

Full answer

A MutationObserver is the modern replacement for the old mutation events. It reports DOM changes efficiently, in batches, and asynchronously.

Setup: const observer = new MutationObserver(callback) and then observer.observe(target, options). The options choose what to watch, and at least one of childList, attributes, or characterData must be true:

  • childList: nodes added to or removed from the target.
  • attributes: attribute changes, with attributeFilter to limit the names and attributeOldValue to keep the previous value.
  • characterData: changes to the text of text nodes.
  • subtree: also watch all descendants, not only the target itself.

Callback: it receives an array of MutationRecord objects and the observer. Each record has type (childList, attributes, or characterData), target, addedNodes, removedNodes, attributeName, and oldValue. Records are queued while code runs, and the callback is called once, as a microtask, after the current script finishes. So ten changes in one function produce one callback with ten records. observer.takeRecords() empties the queue immediately, and disconnect() stops observing.

Use cases: reacting to content inserted by third-party scripts or widgets, waiting for an element to appear, undo history for editors, syncing attribute changes, and testing.

Pitfalls:

  • Infinite loops: if the callback changes the observed node (for example, rewrites an attribute), it triggers new records. Disconnect before changing, or guard with checks.
  • Performance: observing a large subtree with attributes and character data on a page that changes constantly produces many records. Observe the smallest node and the smallest set of options.
  • Changes to properties that are not attributes (such as input.value) are not reported.
  • It does not report layout or style changes, only DOM tree changes. Use ResizeObserver and IntersectionObserver for other things.
  • Forgetting disconnect() on removed components keeps the callback and the nodes alive.

If you control the code that changes the DOM, call your own function or dispatch a custom event rather than observing from far away. The observer is best for changes you do not control.

javascript
document.body.innerHTML = '<ul id="list"><li>one</li></ul><p id="note" data-state="idle">hello</p>';
const list = document.getElementById('list');
const note = document.getElementById('note');
const batches = [];

const observer = new MutationObserver((records) => {
  batches.push(
    records.map((record) => {
      if (record.type === 'childList') return `childList: +${record.addedNodes.length} -${record.removedNodes.length}`;
      if (record.type === 'attributes') return `attribute ${record.attributeName}: ${record.oldValue} -> ${record.target.getAttribute(record.attributeName)}`;
      return `characterData: ${record.oldValue} -> ${record.target.data}`;
    }),
  );
});
observer.observe(list, { childList: true });
observer.observe(note, { attributes: true, attributeFilter: ['data-state'], attributeOldValue: true, characterData: true, characterDataOldValue: true, subtree: true });

// several changes in one script produce one callback with several records
const item = document.createElement('li');
item.textContent = 'two';
list.append(item);
list.firstElementChild.remove();
note.setAttribute('data-state', 'busy');
note.setAttribute('class', 'ignored by the attribute filter');
note.firstChild.data = 'hello world';
console.log('callbacks so far (synchronous code):', batches.length);

Promise.resolve().then(() => {
  console.log('after one microtask:', batches.length, 'callback(s)');
  console.log(batches[0]);

  // takeRecords empties the queue and returns the pending records at once
  note.setAttribute('data-state', 'done');
  const pending = observer.takeRecords();
  console.log('takeRecords returned:', pending.length, 'record(s) of type', pending[0].type);
}).then(() => {
  console.log('callback was not called for records that were taken:', batches.length);

  // a callback that changes what it observes can loop: guard it
  let calls = 0;
  const guarded = new MutationObserver(() => {
    calls++;
    guarded.disconnect(); // stop before changing the observed node
    note.setAttribute('data-count', String(calls));
    guarded.observe(note, { attributes: true, attributeFilter: ['data-state'] });
  });
  guarded.observe(note, { attributes: true, attributeFilter: ['data-state'] });
  note.setAttribute('data-state', 'again');
  return new Promise((resolve) => setTimeout(() => {
    console.log('guarded callback ran', calls, 'time(s); data-count =', note.getAttribute('data-count'));
    guarded.disconnect();
    observer.disconnect();
    resolve();
  }, 5));
}).then(() => {
  const input = document.createElement('input');
  document.body.append(input);
  const valueObserver = new MutationObserver((records) => console.log('input records:', records.length));
  valueObserver.observe(input, { attributes: true });
  input.value = 'typed text';
  input.setAttribute('placeholder', 'name');
  return Promise.resolve().then(() => valueObserver.disconnect());
});

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: callbacks so far (synchronous code): 0 after one microtask: 1 callback(s) [ 'childList: +1 -0', 'childList: +0 -1', 'attribute data-state: idle -> busy', 'characterData: hello -> hello world' ] takeRecords returned: 1 record(s) of type attributes callback was not called for records that were taken: 1 guarded callback ran 1 time(s); data-count = 1 input records: 1

Key points

  • It watches childList, attributes, and characterData, optionally for the whole subtree.
  • Records are batched and delivered once as a microtask after the current script.
  • Use attributeFilter and attributeOldValue; takeRecords empties the queue; disconnect stops it.
  • Pitfalls: loops when the callback changes the observed node, broad observation cost, input.value is not reported.
  • Best for changes you do not control; for your own changes use direct calls or custom events.

Common mistakes

  • Changing the observed node in the callback without a guard, causing an endless loop.
  • Observing the whole document body with every option on a busy page.
  • Expecting input.value or other property changes to be reported.
  • Forgetting to disconnect when a component is destroyed.

Follow-ups

  • Why are mutation events deprecated, and how does MutationObserver improve on them?
  • How would you wait for an element to appear in the page?
  • What is the difference between MutationObserver, ResizeObserver, and IntersectionObserver?

Tips

  • Say that records are batched and delivered as a microtask.
  • List the options and one pitfall for each.
  • Prefer direct calls or custom events when you control the change.
149.javascript-0149Mediummid

What is requestAnimationFrame, why is it better than setTimeout for animation, and how do you use it correctly?

requestAnimationFrame schedules a callback to run right before the browser's next repaint, usually 60 times per second, and passes a high-resolution timestamp. It syncs visual updates with the display, pauses in background tabs, and avoids wasted work. Drive animations from the timestamp instead of counting frames, cancel with cancelAnimationFrame, and use it to batch DOM writes and throttle scroll handlers.

Full answer

Screens refresh at a fixed rate (60, 120, or more times per second). To look smooth, visual changes should happen once per frame, just before the browser paints. setTimeout(fn, 16) is not tied to that: it can run at any point in the frame, drift, and run in a hidden tab, which wastes power, and it may cause skipped or doubled frames.

requestAnimationFrame(callback) asks the browser to call callback(timestamp) once, before the next repaint. The timestamp is a DOMHighResTimeStamp in milliseconds, the same time base as performance.now(). To animate, call requestAnimationFrame again from inside the callback. It returns an id for cancelAnimationFrame(id). Browsers pause callbacks in background tabs, which saves battery and CPU.

Correct use:

  • Use time, not frame counts. A 120 Hz screen calls twice as often as a 60 Hz one. Compute progress as (timestamp - start) / duration, clamp it to 1, apply an easing function, and stop when it reaches 1. Then the animation takes the same time on every display.
  • Do small work. A callback that takes more than a few milliseconds causes dropped frames. Move heavy work to a Worker, or split it.
  • Batch DOM reads and writes. Reading layout properties (such as offsetWidth) after a write forces an early layout (layout thrashing). Read everything first, then write in the frame.
  • Throttle event handlers: events like scroll, resize, and mousemove can fire many times per frame. Store the latest value in the handler and schedule one requestAnimationFrame callback if none is pending.
  • Cancel when the component unmounts or the animation is replaced.

Alternatives: CSS transitions, animations, and the Web Animations API run on the compositor for properties like transform and opacity, and are smoother than JavaScript for simple effects. Use requestAnimationFrame when logic must run each frame (games, canvas drawing, physics, scroll-linked effects). For work that can wait, requestIdleCallback runs when the main thread is idle.

Order: promise callbacks (microtasks) run before the next animation frame callback, which runs before the paint.

javascript
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const easeOut = (t) => 1 - (1 - t) ** 3;

// 1. Time-based animation: the result does not depend on how many frames ran
function animate({ from, to, duration, onFrame }) {
  return new Promise((resolve) => {
    let start;
    let frames = 0;
    let lastTimestamp = -Infinity;
    let monotonic = true;
    function step(timestamp) {
      start ??= timestamp;
      frames++;
      if (timestamp < lastTimestamp) monotonic = false;
      lastTimestamp = timestamp;
      const progress = Math.min(1, (timestamp - start) / duration);
      onFrame(from + (to - from) * easeOut(progress));
      if (progress < 1) requestAnimationFrame(step);
      else resolve({ frames, monotonic, elapsed: timestamp - start });
    }
    requestAnimationFrame(step);
  });
}

// 2. Throttle many events into one frame
function rafThrottle(fn) {
  let pending = false;
  let latestArgs;
  return (...args) => {
    latestArgs = args;
    if (pending) return;
    pending = true;
    requestAnimationFrame(() => {
      pending = false;
      fn(...latestArgs);
    });
  };
}

async function main() {
  const values = [];
  const result = await animate({ from: 0, to: 100, duration: 100, onFrame: (v) => values.push(v) });
  console.log('final value is exactly the target:', values.at(-1) === 100);
  console.log('several frames ran:', result.frames > 1, '| timestamps never go backward:', result.monotonic, '| lasted at least the duration:', result.elapsed >= 100);
  console.log('eased values only go up:', values.every((v, i) => i === 0 || v >= values[i - 1]));

  let handled = 0;
  let lastSeen;
  const onScroll = rafThrottle((position) => { handled++; lastSeen = position; });
  for (let position = 1; position <= 100; position++) onScroll(position);
  console.log('100 events so far, handler runs before the frame:', handled);
  await wait(60);
  console.log('after a frame: handler ran', handled, 'time(s) with the latest value', lastSeen);

  let cancelledRan = false;
  const id = requestAnimationFrame(() => { cancelledRan = true; });
  cancelAnimationFrame(id);
  await wait(60);
  console.log('cancelled callback ran:', cancelledRan);

  const order = [];
  requestAnimationFrame(() => order.push('animation frame'));
  Promise.resolve().then(() => order.push('promise microtask'));
  order.push('synchronous code');
  await wait(60);
  console.log(order);
}
main();

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: final value is exactly the target: true several frames ran: true | timestamps never go backward: true | lasted at least the duration: true eased values only go up: true 100 events so far, handler runs before the frame: 0 after a frame: handler ran 1 time(s) with the latest value 100 cancelled callback ran: false [ 'synchronous code', 'promise microtask', 'animation frame' ]

Key points

  • requestAnimationFrame runs a callback before the next repaint with a high-resolution timestamp.
  • It matches display refresh, pauses in background tabs, and avoids wasted work compared with setTimeout.
  • Drive animations by elapsed time, not by frame count, and clamp progress to 1.
  • Batch reads before writes, keep callbacks short, and cancel when done.
  • Throttle scroll and resize handlers with a single pending frame; prefer CSS animations for simple effects.

Common mistakes

  • Counting frames for animation duration, so speed depends on the display rate.
  • Mixing layout reads and writes inside the frame and causing layout thrashing.
  • Forgetting cancelAnimationFrame when the animation is replaced or the component is removed.
  • Doing heavy work in the callback and dropping frames.

Follow-ups

  • How does the Web Animations API or a CSS transition compare with requestAnimationFrame?
  • What is layout thrashing and how do you avoid it?
  • When would you use requestIdleCallback instead?

Tips

  • Say what it syncs with: the next repaint.
  • Show progress based on timestamps and clamp it.
  • Mention throttling event handlers and cancellation.
150.javascript-0150Mediummid

Predict the output of these array and object puzzles, such as map with parseInt, holes, key order, and shared references.

Most array and object surprises come from a few rules: callbacks such as map receive extra arguments, arrays can be sparse, array length is writable, integer-like object keys are ordered first, objects and arrays compare by reference, fill and spread copy references and not values, and object keys are always strings or symbols. Name the rule before the output.

Full answer

Go through the puzzles by rule.

Rule 1, callback arguments: map, filter, and forEach call the function with (value, index, array). So ['1', '2', '3'].map(parseInt) calls parseInt('2', 1), where 1 is not a valid radix, and gives [1, NaN, NaN].

Rule 2, sparse arrays: [1, , 3] and new Array(3) have holes. forEach, map, and filter skip holes. delete arr[1] leaves a hole and does not change length. Object.keys skips holes and for...in too, while for...of and the spread syntax visit them as undefined.

Rule 3, length is writable: arr.length = 0 empties the array, and assigning to arr[10] on a short array grows length to 11 and leaves holes. A negative index is just a property: arr[-1] = 'x' does not change length.

Rule 4, key order: for plain objects, integer-like keys come first in ascending order, then string keys in insertion order, then symbols. So { b: 1, 2: 1, a: 1, 1: 1 } lists 1, 2, b, a.

Rule 5, reference comparison: {} === {} and [] === [] are false, and [1] == [1] is false. Two variables are equal only if they point to the same object.

Rule 6, shared references: new Array(3).fill([]) puts the same array in all three slots. Array.from({ length: 3 }, () => []) creates three arrays. Spread { ...obj } and [...arr] copy one level, so nested objects stay shared.

Rule 7, key coercion: object keys are converted to strings, so obj[1] and obj['1'] are the same key, and every object used as a key becomes '[object Object]'. A Map keeps the real key.

Also: the default sort compares as strings, typeof [] is 'object', and Array.isArray is the right check.

javascript
const show = (label, value) => console.log(label.padEnd(28), value);

show("['1','2','3'].map(parseInt)", ['1', '2', '3'].map(parseInt));
show("['1','2','3'].map(Number)", ['1', '2', '3'].map(Number));

const sparse = [1, , 3];
const visited = [];
sparse.forEach((v, i) => visited.push(i));
show('sparse forEach indexes', visited);
show('sparse length, keys', [sparse.length, Object.keys(sparse)]);
show('spread of a sparse array', [...sparse]);
show('map over holes', sparse.map((v) => v * 2));

const arr = [1, 2, 3];
delete arr[1];
show('after delete arr[1]', [arr, arr.length]);
arr.length = 1;
show('after length = 1', arr);
arr[4] = 'x';
show('after arr[4] = "x"', [arr, arr.length]);
arr[-1] = 'neg';
show('negative index', [arr.length, arr[-1]]);

show('key order', Object.keys({ b: 1, 2: 1, a: 1, 1: 1, [Symbol('s')]: 1 }));
show('{} === {}, [] == []', [{} === {}, [] == []]);
show('[1] == 1, [1,2] == "1,2"', [[1] == 1, [1, 2] == '1,2']);

const shared = new Array(3).fill([]);
shared[0].push('x');
show('fill with one array', JSON.stringify(shared));
const separate = Array.from({ length: 3 }, () => []);
separate[0].push('x');
show('Array.from with a factory', JSON.stringify(separate));

const original = { name: 'Asha', tags: ['a'] };
const copy = { ...original };
copy.name = 'Ben';
copy.tags.push('b');
show('shallow copy', [original.name, original.tags]);

const keyObject = {};
const key1 = { id: 1 };
const key2 = { id: 2 };
keyObject[key1] = 'first';
keyObject[key2] = 'second';
show('object keys', [Object.keys(keyObject), keyObject[key1]]);
const map = new Map([[key1, 'first'], [key2, 'second']]);
show('Map keeps real keys', [map.size, map.get(key1)]);
const numbers = { 1: 'a' };
show('obj[1], obj["1"]', [numbers[1], numbers['1']]);

show('[10, 9, 1].sort()', [10, 9, 1].sort());
show('typeof [] and Array.isArray', [typeof [], Array.isArray([])]);
show('Array(3) and Array(3, 4)', [Array(3).length, Array(3, 4)]);
show('[,].length, [,,].length', [[,].length, [, ,].length]);
show('[] + [] and [].length', [[] + [], [].length]);
show('indexOf(NaN), includes(NaN)', [[NaN].indexOf(NaN), [NaN].includes(NaN)]);

Run with Node.js v24.22.1 as js-150.js; two runs gave identical output. Output: ['1','2','3'].map(parseInt) [ 1, NaN, NaN ] ['1','2','3'].map(Number) [ 1, 2, 3 ] sparse forEach indexes [ 0, 2 ] sparse length, keys [ 3, [ '0', '2' ] ] spread of a sparse array [ 1, undefined, 3 ] map over holes [ 2, <1 empty item>, 6 ] after delete arr[1] [ [ 1, <1 empty item>, 3 ], 3 ] after length = 1 [ 1 ] after arr[4] = "x" [ [ 1, <3 empty items>, 'x' ], 5 ] negative index [ 5, 'neg' ] key order [ '1', '2', 'b', 'a' ] {} === {}, [] == [] [ false, false ] [1] == 1, [1,2] == "1,2" [ true, true ] fill with one array [["x"],["x"],["x"]] Array.from with a factory [["x"],[],[]] shallow copy [ 'Asha', [ 'a', 'b' ] ] object keys [ [ '[object Object]' ], 'second' ] Map keeps real keys [ 2, 'first' ] obj[1], obj["1"] [ 'a', 'a' ] [10, 9, 1].sort() [ 1, 10, 9 ] typeof [] and Array.isArray [ 'object', true ] Array(3) and Array(3, 4) [ 3, [ 3, 4 ] ] [,].length, [,,].length [ 1, 2 ] [] + [] and [].length [ '', 0 ] indexOf(NaN), includes(NaN) [ -1, true ]

Key points

  • map passes value, index, and array, so parseInt gets a radix; use unary wrappers.
  • Holes are skipped by forEach, map, and filter; delete leaves a hole; length is writable.
  • Object key order: integer keys ascending, then strings by insertion, then symbols.
  • Objects compare by reference; fill and spread copy references and are shallow.
  • Object keys are strings or symbols; use Map for other key types.

Common mistakes

  • Passing parseInt directly to map.
  • Treating holes as undefined values, and expecting forEach to visit them.
  • Creating a matrix with new Array(n).fill([]).
  • Copying an object with spread and assuming nested data is copied.

Follow-ups

  • How would you create a two-dimensional array of independent rows?
  • Why are integer-like keys ordered first, and does the same hold for a Map?
  • How does the sparse array differ from an array filled with undefined?

Tips

  • Name the rule first, then give the output.
  • Use Array.from with a factory for independent items.
  • Mention Map for non-string keys.
151.javascript-0151Easyfresher

What is JavaScript, and how does an engine such as V8 run your code?

JavaScript is a high-level, dynamically typed, multi-paradigm language standardized as ECMAScript. An engine such as V8 parses the source into a syntax tree, compiles it to bytecode that it starts running at once, and uses a just-in-time (JIT) compiler to turn hot code into optimized machine code. It runs on a single main thread inside a host environment, such as a browser or Node.js, that supplies APIs like the DOM, timers, and files.

Full answer

JavaScript is the programming language of the web. The language itself is defined by the ECMAScript specification, which is updated every year. The language has no built-in input or output. The host environment adds that: a browser provides the DOM, fetch, and timers, and Node.js provides files, networking, and process.

How code runs, in steps:

  1. Parsing: the engine reads the source text and checks the syntax. A syntax error stops the whole script before any line runs. The parser builds an abstract syntax tree (AST).
  2. Bytecode: an interpreter (Ignition in V8) turns the tree into compact bytecode and starts executing right away. This gives a fast start.
  3. Profiling and JIT: while the code runs, the engine records which functions are hot and what types they see. For hot code, an optimizing compiler (TurboFan in V8) produces machine code based on those assumptions.
  4. Deoptimization: if an assumption breaks (a function that always got numbers suddenly gets a string), the engine throws away the optimized code and falls back to bytecode.

Other facts to know: JavaScript is dynamically typed (variables hold any type, and types are checked while running), it is garbage collected, and it has one main thread with an event loop, so long synchronous work blocks everything else. Concurrency comes from asynchronous APIs and workers, not from threads that share objects.

Engines differ by environment: V8 (Chrome, Edge, Node.js, Deno), SpiderMonkey (Firefox), and JavaScriptCore (Safari, Bun). They follow the same specification. A JavaScript program is not purely interpreted and not purely compiled ahead of time: it is compiled while it runs.

Practical meaning: keep code simple and type-stable in hot paths, do not block the main thread, and measure instead of guessing about speed.

javascript
const { execFileSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const vm = require('node:vm');

console.log('engine:', 'V8', typeof process.versions.v8, '| host:', 'Node.js', typeof process.versions.node);

// 1. Parsing happens first: a syntax error means no line of the script runs
try {
  new vm.Script('console.log("this line never runs"); let = ;');
} catch (error) {
  console.log('whole script rejected at parse time:', error.name);
}

// 2. Dynamic typing: the same variable holds different types, checked while running
let value = 42;
console.log(typeof value);
value = 'now a string';
console.log(typeof value);

// 3. Bytecode: ask V8 to print the bytecode for a tiny function (run in a child process)
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bytecode-'));
const file = path.join(dir, 'add.js');
fs.writeFileSync(file, 'function add(a, b) { return a + b; }\nadd(1, 2);\n');
const dump = execFileSync(process.execPath, ['--print-bytecode', '--print-bytecode-filter=add', file], { encoding: 'utf8' });
const instructions = [...dump.matchAll(/@\s+\d+ : [0-9a-f ]+?\s{2,}(\w+)/g)].map((m) => m[1]);
console.log('bytecode of add(a, b):', instructions.join(' -> '));
fs.rmSync(dir, { recursive: true, force: true });

// 4. One main thread: a busy loop blocks timers, which only run after the synchronous code ends
const order = [];
setTimeout(() => order.push('timer (0 ms)'), 0);
const end = Date.now() + 30;
while (Date.now() < end) { /* blocking on purpose */ }
order.push('busy loop finished');
setTimeout(() => console.log(order), 10);

Run with Node.js v24.22.1 as js-151.js; two runs gave identical output. Output: engine: V8 string | host: Node.js string whole script rejected at parse time: SyntaxError number string bytecode of add(a, b): Ldar -> Add -> Return [ 'busy loop finished', 'timer (0 ms)' ]

Key points

  • ECMAScript is the standard; the host (browser or Node.js) provides APIs such as the DOM or files.
  • Engine pipeline: parse to AST, interpret bytecode, JIT-compile hot code, deoptimize if assumptions break.
  • JavaScript is dynamically typed, garbage collected, and single threaded with an event loop.
  • Syntax errors are found at parse time, before any code runs.
  • It is compiled at run time, not simply interpreted.

Common mistakes

  • Saying JavaScript is only interpreted, or only compiled in advance.
  • Mixing up the language (ECMAScript) with browser APIs such as the DOM.
  • Thinking that JavaScript is the same as Java.
  • Blocking the main thread with long synchronous work.

Follow-ups

  • What is the difference between the interpreter and the JIT compiler in an engine?
  • What is deoptimization and what can cause it?
  • Why do different engines behave the same for standard features?

Tips

  • Separate language, engine, and host environment in your first sentence.
  • Give the pipeline in four steps.
  • Mention that the main thread is single and what that means for slow code.
152.javascript-0152Easyfresher

What are the data types in JavaScript, how does typeof work, and which typeof results are surprising?

JavaScript has seven primitive types (string, number, bigint, boolean, undefined, symbol, null) and one structural type, object, which includes arrays, functions, and dates. The typeof operator returns a string and is reliable for primitives except null, which gives "object" because of an old bug. Functions give "function" although they are objects, and arrays give "object", so use Array.isArray, and an undeclared name is safe to test with typeof.

Full answer

Primitive types are immutable values: string, number, bigint, boolean, undefined, symbol, and null. Everything else is an object (objects, arrays, functions, dates, maps, and so on), compared by reference.

typeof returns one of these strings: 'string', 'number', 'bigint', 'boolean', 'undefined', 'symbol', 'function', 'object'. The quirks:

  • typeof null is 'object'. This is a bug from the first version of the language that cannot be fixed without breaking the web. Test for null with value === null.
  • typeof [] is 'object', and so are dates, regular expressions, and maps. Use Array.isArray(value) for arrays, and value instanceof Date or Object.prototype.toString.call(value) for others.
  • typeof function () {} and typeof class {} are 'function'. Functions are objects with extra behavior, and 'function' is a special case of the operator.
  • typeof NaN is 'number', because NaN is a special numeric value.
  • typeof undeclaredName is 'undefined' and does not throw, while reading an undeclared name throws a ReferenceError. That is why typeof window !== 'undefined' is a safe environment check.
  • Variables in the temporal dead zone throw even with typeof.
  • typeof new String('a') is 'object'. Wrapper objects created with new differ from primitive strings. Avoid them.
  • typeof 10n is 'bigint', and typeof Symbol() is 'symbol'.

A reliable type check helper: Object.prototype.toString.call(value) returns strings such as '[object Array]', '[object Null]', and '[object Date]'.

Primitives have no properties of their own, but they get temporary wrapper objects when you call methods: 'abc'.toUpperCase() works because the engine wraps the string for the call.

javascript
const samples = [
  ['"text"', 'text'], ['42', 42], ['NaN', NaN], ['10n', 10n], ['true', true], ['undefined', undefined],
  ['Symbol()', Symbol('s')], ['null', null], ['{}', {}], ['[]', []], ['new Date()', new Date(0)],
  ['/x/', /x/], ['function', function () {}], ['class', class {}], ['() => {}', () => {}],
  ['new Map()', new Map()], ['new String("a")', new String('a')],
];
for (const [label, value] of samples) {
  console.log(label.padEnd(18), typeof value, '|', Object.prototype.toString.call(value));
}

console.log('typeof undeclared:', typeof thisNameIsNotDeclared);
try {
  thisNameIsNotDeclared;
} catch (error) {
  console.log('reading it throws:', error.name);
}
try {
  typeof later;
  let later = 1;
} catch (error) {
  console.log('typeof in the temporal dead zone throws:', error.name);
}

const isPlainObject = (value) => Object.prototype.toString.call(value) === '[object Object]';
console.log(isPlainObject({}), isPlainObject([]), isPlainObject(null), isPlainObject(new Map()));
console.log(Array.isArray([]), Array.isArray({ length: 0 }), null === null, typeof null === 'object');

const primitive = 'abc';
const wrapper = new String('abc');
console.log(primitive === 'abc', wrapper === 'abc', wrapper == 'abc', typeof primitive, typeof wrapper);
primitive.extra = 1;
console.log('properties on a primitive are lost:', primitive.extra);

Run with Node.js v24.22.1 as js-152.js; two runs gave identical output. Output: "text" string | [object String] 42 number | [object Number] NaN number | [object Number] 10n bigint | [object BigInt] true boolean | [object Boolean] undefined undefined | [object Undefined] Symbol() symbol | [object Symbol] null object | [object Null] {} object | [object Object] [] object | [object Array] new Date() object | [object Date] /x/ object | [object RegExp] function function | [object Function] class function | [object Function] () => {} function | [object Function] new Map() object | [object Map] new String("a") object | [object String] typeof undeclared: undefined reading it throws: ReferenceError typeof in the temporal dead zone throws: ReferenceError true false false false true false true true true false true string object properties on a primitive are lost: undefined

Key points

  • Seven primitives plus object; primitives are immutable and compared by value.
  • typeof returns a string; null gives "object" (historic bug) so test with === null.
  • Arrays, dates, and maps are "object"; use Array.isArray or toString.call for details.
  • Functions give "function"; NaN gives "number"; an undeclared name gives "undefined" without throwing.
  • Wrapper objects from new String and similar are objects; avoid them.

Common mistakes

  • Using typeof to detect null or arrays.
  • Using new String, new Number, or new Boolean.
  • Reading an undeclared variable to test if it exists instead of using typeof.
  • Assuming that functions are not objects.

Follow-ups

  • Why does typeof null return object?
  • How would you write a function that returns an accurate type name for any value?
  • What happens to a property assigned on a primitive string?

Tips

  • List the seven primitives from memory and say everything else is an object.
  • Name the typeof null bug and the right replacement.
  • Mention the safe typeof check for undeclared names.
153.javascript-0153Easyfresher

How do operator precedence and associativity work in JavaScript, and which cases surprise people?

Precedence decides which operator in an expression is applied first, and associativity decides the direction for operators of the same level. Multiplication runs before addition, the exponent operator is right associative, and && binds tighter than ||. Mixing ?? with || or && without parentheses is a syntax error, and the increment operators and the ternary have surprising results, so use parentheses when it helps readers.

Full answer

Precedence is a ranking. In 2 + 3 * 4, multiplication has higher precedence than addition, so the result is 14. Parentheses override any precedence. Associativity applies when two operators have equal precedence: most operators are left associative (10 - 4 - 3 is (10 - 4) - 3, which is 3), but assignment, the ternary, and ** are right associative (2 ** 3 ** 2 is 2 ** (3 ** 2), which is 512).

A useful order from high to low:

  1. Member access and calls: a.b, a[b], f(), new X().
  2. Postfix and prefix ++ and --, unary !, -, +, typeof, void, delete, await.
  3. **.
  4. *, /, %, then + and -.
  5. Shifts, then relational (<, >, in, instanceof), then equality (==, ===).
  6. Bitwise &, ^, |.
  7. &&, then || and ??.
  8. Ternary ? :, then assignment, then the comma.

Cases that surprise people:

  • && binds tighter than ||: true || false && false is true because it reads true || (false && false).
  • ?? cannot be mixed with || or && without parentheses. Writing a ?? b || c is a SyntaxError on purpose, to avoid confusion.
  • A unary minus before ** is not allowed: -2 ** 2 is a SyntaxError. Write (-2) ** 2 or -(2 ** 2).
  • 1 < 2 < 3 is (1 < 2) < 3, which is true < 3, which is true. And 3 > 2 > 1 is false.
  • typeof a + b is (typeof a) + b. !a == b is (!a) == b.
  • Postfix i++ returns the old value, and prefix ++i returns the new one. Using both in one expression, such as i = i++ + ++i, is hard to read and should be avoided.
  • The ternary is right associative, which allows chains: a ? b : c ? d : e, but nested ternaries are hard to read.
  • Evaluation order differs from precedence: operands are evaluated left to right even when precedence groups them otherwise, as in f() + g() * h() which calls f, g, h in that order.

Advice: do not memorize the whole table. Know the common rules, and add parentheses when an expression mixes several kinds of operators.

javascript
console.log(2 + 3 * 4, (2 + 3) * 4, 10 - 4 - 3, 2 ** 3 ** 2, (2 ** 3) ** 2);
console.log(true || false && false, (true || false) && false);
console.log(1 < 2 < 3, 3 > 2 > 1, typeof 1 + 2, !0 == 1);

for (const source of ['null ?? "x" || "y"', '(null ?? "x") || "y"', '-2 ** 2', '(-2) ** 2', '-(2 ** 2)']) {
  try {
    console.log(source.padEnd(22), '->', new Function(`return ${source}`)());
  } catch (error) {
    console.log(source.padEnd(22), '->', error.name);
  }
}

let i = 5;
const a = i++;
const b = ++i;
console.log('postfix returns the old value:', a, '| prefix returns the new value:', b, '| i:', i);

let x = 1;
x += x++ + ++x;
console.log('x += x++ + ++x gives', x, '(hard to read, avoid)');

const grade = (score) => (score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F');
console.log([95, 85, 72, 10].map(grade));

const trace = [];
const f = (name, value) => (trace.push(name), value);
const result = f('f', 1) + f('g', 2) * f('h', 3);
console.log(result, trace.join(' then '));

let p, q, r;
p = q = r = 7;
console.log(p, q, r, '| assignment is right associative and returns the value');
console.log(typeof typeof 1, !!'0', +true, -'5', void 0);

Run with Node.js v24.22.1 as js-153.js; two runs gave identical output. Output: 14 20 3 512 64 true false true false number2 true null ?? "x" || "y" -> SyntaxError (null ?? "x") || "y" -> x -2 ** 2 -> SyntaxError (-2) ** 2 -> 4 -(2 ** 2) -> -4 postfix returns the old value: 5 | prefix returns the new value: 7 | i: 7 x += x++ + ++x gives 5 (hard to read, avoid) [ 'A', 'B', 'C', 'F' ] 7 f then g then h 7 7 7 | assignment is right associative and returns the value string true 1 -5 undefined

Key points

  • Precedence ranks operators; associativity breaks ties; parentheses override both.
  • Exponent, assignment, and ternary are right associative; most others are left associative.
  • && is higher than || and ??, but ?? cannot be mixed with them without parentheses.
  • Unary minus directly before ** is a syntax error.
  • Operands are evaluated left to right regardless of precedence; add parentheses for readability.

Common mistakes

  • Relying on memory of the table instead of adding parentheses.
  • Mixing ?? with || or && without parentheses.
  • Expecting 1 < 2 < 3 style chains to behave like in mathematics.
  • Combining ++ in the same expression with other uses of the same variable.

Follow-ups

  • Why is ?? not allowed to mix with || without parentheses?
  • What is the difference between precedence and evaluation order?
  • Why is the exponent operator right associative?

Tips

  • Show two or three examples instead of reciting the table.
  • Mention that parentheses make intent clear.
  • Name the syntax errors that are deliberate.
154.javascript-0154Easyfresher

How do push, pop, shift, and unshift work, which array methods change the array, and how do includes and indexOf differ?

push and pop add and remove at the end, while unshift and shift add and remove at the start, and all four change the original array. push and unshift return the new length, pop and shift return the removed item. indexOf returns a position or -1, includes returns a boolean and finds NaN. Operations at the start are slower on large arrays because every item moves.

Full answer

Arrays are ordered lists. The four basic methods work at the two ends and all mutate the array:

  • push(...items) adds to the end and returns the new length.
  • pop() removes the last item and returns it (or undefined for an empty array).
  • unshift(...items) adds to the start and returns the new length.
  • shift() removes the first item and returns it.

Together, push and pop make a stack (last in, first out). push and shift make a queue (first in, first out). For large queues, shift is slow, because the engine may need to move every element one place (it is O(n) in the worst case), while push and pop are O(1). For big queues, keep an index pointer or use a different structure.

Knowing which methods mutate matters. These change the array: push, pop, shift, unshift, splice, sort, reverse, fill, and copyWithin. These return a new value and leave the array alone: slice, concat, map, filter, flat, toSorted, toReversed, and the spread syntax. A bug often comes from sort or reverse on shared data.

Searching: indexOf(value) returns the first index or -1, and uses strict equality, so it cannot find NaN. includes(value) returns true or false, uses SameValueZero, and finds NaN. Use includes for a yes or no answer, because if (arr.indexOf(x)) is a bug: index 0 is falsy, and -1 is truthy. Both accept a start position. For objects, they compare by reference, so use some or find with a condition.

Length: length is the highest index plus one and is writable: arr.length = 0 empties the array. at(-1) reads the last element. Use Array.isArray to test if a value is an array.

javascript
const stack = [];
console.log('push returns the new length:', stack.push('a', 'b', 'c'), [...stack]);
console.log('pop returns the removed item:', stack.pop(), [...stack]);
console.log('unshift returns the new length:', stack.unshift('z'), [...stack]);
console.log('shift returns the removed item:', stack.shift(), [...stack]);
console.log([].pop(), [].shift(), [].length);

const queue = [1, 2, 3];
queue.push(4);
console.log('queue order:', queue.shift(), queue.shift(), queue);

const letters = ['a', 'b', 'c'];
console.log('indexOf:', letters.indexOf('a'), letters.indexOf('z'), '| includes:', letters.includes('a'), letters.includes('z'));
console.log('if (indexOf) bug:', letters.indexOf('a') ? 'truthy' : 'falsy (index 0)', letters.indexOf('z') ? 'truthy (-1)' : 'falsy');
console.log('NaN:', [NaN].indexOf(NaN), [NaN].includes(NaN));
console.log('objects by reference:', [{ id: 1 }].includes({ id: 1 }), [{ id: 1 }].some((o) => o.id === 1));
console.log('start position:', [1, 2, 1].indexOf(1, 1), [1, 2, 1].includes(1, 3));

const original = [3, 1, 2];
const sortedCopy = original.toSorted();
console.log(sortedCopy, original);
original.sort();
console.log('sort changed the original:', original);

const items = [1, 2, 3, 4, 5];
items.length = 2;
console.log(items, items.at(-1));

// shift is O(n) on large arrays: an index pointer is a cheap queue
const big = Array.from({ length: 5 }, (_, i) => i);
let head = 0;
const take = () => big[head++];
console.log(take(), take(), big.slice(head));

Run with Node.js v24.22.1 as js-154.js; two runs gave identical output. Output: push returns the new length: 3 [ 'a', 'b', 'c' ] pop returns the removed item: c [ 'a', 'b' ] unshift returns the new length: 3 [ 'z', 'a', 'b' ] shift returns the removed item: z [ 'a', 'b' ] undefined undefined 0 queue order: 1 2 [ 3, 4 ] indexOf: 0 -1 | includes: true false if (indexOf) bug: falsy (index 0) truthy (-1) NaN: -1 true objects by reference: false true start position: 2 false [ 1, 2, 3 ] [ 3, 1, 2 ] sort changed the original: [ 1, 2, 3 ] [ 1, 2 ] 2 0 1 [ 2, 3, 4 ]

Key points

  • push and pop work at the end, unshift and shift at the start; all mutate the array.
  • push and unshift return the new length; pop and shift return the removed element.
  • shift and unshift are slower for large arrays; push and pop are fast.
  • indexOf gives an index or -1 with strict equality; includes gives a boolean and finds NaN.
  • Know which methods mutate (sort, reverse, splice) and which return new arrays.

Common mistakes

  • Writing if (arr.indexOf(x)) instead of comparing with -1 or using includes.
  • Using shift in a loop over a very large array.
  • Calling sort or reverse on shared data and changing it for every user.
  • Expecting includes or indexOf to compare objects by content.

Follow-ups

  • What is the difference between splice and slice?
  • How would you implement a queue with O(1) dequeue?
  • Why can includes find NaN but indexOf cannot?

Tips

  • Group the methods into mutating and non-mutating.
  • Say what each method returns.
  • Mention the performance cost of shift and unshift.
155.javascript-0155Easyfresher

How do you create, read, format, and compare dates with the Date object, and what are the basic gotchas?

A Date stores one number, the milliseconds since 1 January 1970 UTC, and shows it in local time or UTC through different methods. Months are counted from 0, the date-only string "2026-03-05" is parsed as UTC while "2026-03-05T00:00" is local time, and comparing two dates with == compares references, so compare getTime values. Use toISOString for storage and Intl for display.

Full answer

A Date is a wrapper around a single timestamp: the number of milliseconds since the Unix epoch (1 January 1970, 00:00 UTC). Date.now() and date.getTime() return that number.

Creating dates:

  • new Date() is now.
  • new Date(ms) from a timestamp.
  • new Date('2026-03-05T10:30:00Z') from an ISO string. A trailing Z means UTC, and an offset such as +05:30 is also exact.
  • new Date(2026, 2, 5, 10, 30) from parts, in local time. The month is zero-based: 0 is January, so 2 is March. This is the most common beginner bug. Day numbers start at 1.

Reading: getFullYear(), getMonth() (0 to 11), getDate() (day of month), getDay() (0 is Sunday), getHours(), and so on give local time, and the getUTC... versions give UTC. Never use getYear().

Formatting: toISOString() gives a UTC string such as 2026-03-05T10:30:00.000Z, which is the best format for storing and sending. toLocaleDateString(locale, options) and Intl.DateTimeFormat format for people and handle languages and time zones. toString() depends on the machine and should not be used for storage.

Parsing gotchas: a date-only ISO string ('2026-03-05') is treated as UTC midnight, so in a time zone behind UTC the local date can be the day before. A date-time string without an offset ('2026-03-05T00:00') is local time. Other string formats are implementation-dependent, so avoid them. An invalid date has NaN as its time: check with Number.isNaN(date.getTime()).

Comparing: date1 < date2 works because dates convert to numbers, but date1 === date2 compares references, and == too. Use date1.getTime() === date2.getTime().

Arithmetic: dates are mutable. setDate(getDate() + 7) adds a week and handles month overflow. Copy a date with new Date(date) before changing it. Adding 24 * 60 * 60 * 1000 can be wrong across daylight saving changes.

For time zone and calendar-heavy work, use Intl, or the newer Temporal API when it is available.

javascript
const fixed = new Date('2026-03-05T10:30:00Z');
console.log(fixed.getTime(), fixed.toISOString(), fixed.toJSON() === fixed.toISOString());
console.log('month is zero-based:', new Date(2026, 2, 5).getMonth(), '(March)', '| UTC month of fixed:', fixed.getUTCMonth());
console.log('weekday (0 = Sunday):', fixed.getUTCDay(), '| day of month:', fixed.getUTCDate(), '| year:', fixed.getUTCFullYear());

console.log(new Date(Date.UTC(2026, 11, 31, 23, 59, 59)).toISOString());
console.log(new Date(0).toISOString(), new Date(86400000).toISOString());

const dateOnly = new Date('2026-03-05');
console.log('date-only string is UTC midnight:', dateOnly.toISOString());
const invalid = new Date('not a date');
console.log('invalid:', Number.isNaN(invalid.getTime()), String(invalid));

const a = new Date('2026-03-05T10:30:00Z');
const b = new Date('2026-03-05T10:30:00Z');
console.log('===:', a === b, '| ==:', a == b, '| getTime:', a.getTime() === b.getTime(), '| less than:', a < new Date('2026-03-06T00:00:00Z'));

const start = new Date(Date.UTC(2026, 0, 31));
const moved = new Date(start);
moved.setUTCDate(moved.getUTCDate() + 30);
console.log('mutation copy:', start.toISOString().slice(0, 10), '->', moved.toISOString().slice(0, 10));
const overflow = new Date(Date.UTC(2026, 0, 31));
overflow.setUTCMonth(1);
console.log('Jan 31 plus one month overflows to:', overflow.toISOString().slice(0, 10));

const diffDays = (x, y) => Math.round((y - x) / 86400000);
console.log('days between:', diffDays(new Date('2026-03-01T00:00:00Z'), new Date('2026-12-25T00:00:00Z')));

const format = new Intl.DateTimeFormat('en-GB', { dateStyle: 'full', timeStyle: 'short', timeZone: 'Asia/Kolkata' });
console.log(format.format(fixed));
console.log(new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeZone: 'UTC' }).format(fixed));

Run with Node.js v24.22.1 as js-155.js; two runs gave identical output. Output: 1772706600000 2026-03-05T10:30:00.000Z true month is zero-based: 2 (March) | UTC month of fixed: 2 weekday (0 = Sunday): 4 | day of month: 5 | year: 2026 2026-12-31T23:59:59.000Z 1970-01-01T00:00:00.000Z 1970-01-02T00:00:00.000Z date-only string is UTC midnight: 2026-03-05T00:00:00.000Z invalid: true Invalid Date ===: false | ==: false | getTime: true | less than: true mutation copy: 2026-01-31 -> 2026-03-02 Jan 31 plus one month overflows to: 2026-03-03 days between: 299 Thursday, 5 March 2026 at 16:00 Mar 5, 2026

Key points

  • A Date is one number of milliseconds since 1970 UTC; local and UTC getters show it differently.
  • Months start at 0; getDay is the weekday, getDate is the day of the month.
  • Date-only ISO strings are UTC, date-time without offset is local; avoid other formats.
  • Compare with getTime, not ===; check validity with Number.isNaN(date.getTime()).
  • Store with toISOString; display with Intl; copy dates before mutating.

Common mistakes

  • Using getMonth as if January were 1.
  • Parsing non-ISO date strings and getting different results in different browsers.
  • Comparing dates with === or ==.
  • Mutating a date that other code also uses.

Follow-ups

  • Why does the string 2026-03-05 sometimes show the previous day in local time?
  • How would you add one month to a date and keep the day at the end of the month?
  • Why prefer toISOString for storing dates?

Tips

  • Start with the epoch idea: one number.
  • Name the zero-based month early; it is the classic bug.
  • Recommend ISO strings for storage and Intl for display.
156.javascript-0156Easyfresher

What does it mean that functions are first-class values in JavaScript, and what is a higher-order function?

First-class means a function is a normal value: you can store it in a variable, put it in an array or object, pass it as an argument, and return it from another function. A higher-order function is a function that takes a function as an argument or returns one, such as map, filter, setTimeout, or a function that builds a validator. This enables callbacks, closures, and reusable behavior.

Full answer

In JavaScript a function is an object that can be called. Because it is a value, it can be used anywhere a value can:

  • Assigned: const greet = function () {} or const add = (a, b) => a + b.
  • Stored: in an array ([fn1, fn2]), or as an object property (a method).
  • Passed as an argument: [1, 2, 3].map(double), button.addEventListener('click', handler).
  • Returned from a function: makeAdder(5) returns a new function.

A higher-order function (HOF) takes a function, returns a function, or both. Built-in examples are map, filter, reduce, sort (with a comparator), forEach, setTimeout, and Promise.then. When you pass a function that will be called later, it is a callback.

Returned functions keep access to the variables where they were created, which is a closure. This makes it possible to write function factories: const multiplyBy = (n) => (x) => x * n; const double = multiplyBy(2);.

Why HOFs help: they let you separate what to do for each item from how to loop, reduce repeated code, and build reusable tools such as debounce, memoize, and retry wrappers. They also make code more declarative: users.filter(isActive).map(getName) says what you want.

Details to remember:

  • Pass the function itself, not the result of calling it: setTimeout(run, 1000), not setTimeout(run(), 1000). The second form calls run at once and passes its return value.
  • A function reference passed as a callback loses its this unless it is an arrow function or is bound.
  • Callbacks from map and similar methods receive (value, index, array), so passing a function that takes optional extra arguments, such as parseInt, gives surprises.
  • Functions have properties: name, length (number of declared parameters), and methods call, apply, and bind.
javascript
const add = (a, b) => a + b;
const operations = { add, subtract: (a, b) => a - b, multiply: (a, b) => a * b };
console.log(Object.entries(operations).map(([name, fn]) => `${name}(6, 3) = ${fn(6, 3)}`));

const pipeline = [(x) => x + 1, (x) => x * 2, String];
console.log(pipeline.reduce((value, fn) => fn(value), 4));

function multiplyBy(n) {
  return (x) => x * n;
}
const double = multiplyBy(2);
const triple = multiplyBy(3);
console.log(double(21), triple(5), multiplyBy.length, double.length);

function repeat(times, action) {
  for (let i = 0; i < times; i++) action(i);
}
const seen = [];
repeat(3, (i) => seen.push(i * i));
console.log(seen);

const numbers = [1, 2, 3, 4, 5, 6];
const isEven = (n) => n % 2 === 0;
const square = (n) => n * n;
console.log(numbers.filter(isEven).map(square), numbers.some(isEven), numbers.every(isEven));
console.log([5, 1, 10].sort((a, b) => a - b), ['b', 'a'].sort());

function callLater(fn, label) {
  return new Promise((resolve) => setTimeout(() => resolve(`${label}: ${fn()}`), 1));
}
const run = () => 'ran later';
callLater(run, 'reference').then(console.log);
console.log('passing run() instead of run passes:', typeof run(), '(a string, not a function)');

const user = { name: 'Asha', hello() { return `hi ${this.name}`; } };
const detached = user.hello;
console.log(user.hello(), (() => { try { return detached(); } catch (e) { return e.name; } })(), detached.bind(user)());

Run with Node.js v24.22.1 as js-156.js; two runs gave identical output. Output: [ 'add(6, 3) = 9', 'subtract(6, 3) = 3', 'multiply(6, 3) = 18' ] 10 42 15 1 1 [ 0, 1, 4 ] [ 4, 16, 36 ] true false [ 1, 5, 10 ] [ 'a', 'b' ] passing run() instead of run passes: string (a string, not a function) hi Asha hi undefined hi Asha reference: ran later

Key points

  • First-class: functions can be assigned, stored, passed, and returned like any other value.
  • A higher-order function takes or returns a function; callbacks are functions passed to be called later.
  • Returned functions form closures, which makes factories like multiplyBy possible.
  • Pass the function reference, not the call result; watch this and extra callback arguments.
  • HOFs reduce repetition and make code declarative.

Common mistakes

  • Writing setTimeout(run(), 1000), which runs the function at once.
  • Passing a method as a callback and losing this.
  • Passing a function with optional parameters, such as parseInt, directly to map.
  • Not returning a value from the callback of map or filter.

Follow-ups

  • What is the difference between a callback and a higher-order function?
  • How do closures make function factories work?
  • How would you write your own version of map?

Tips

  • Define first-class with the four uses: assign, store, pass, return.
  • Give a built-in HOF and a function factory example.
  • Mention the setTimeout(run()) mistake.
157.javascript-0157Easyfresher

What is an IIFE, why was it used, and is it still useful today?

An IIFE (immediately invoked function expression) is a function that is defined and called right away, such as (function () { ... })(). It creates a private scope, so variables do not leak into the global scope, and it can return a value, which made it the original module pattern. Today ES modules, block scope, and let and const cover most uses, but IIFEs remain useful for one-off setup, async code at the top level of scripts, and initialization with a result.

Full answer

An IIFE is a function expression that is called immediately. The extra parentheses turn a function declaration into an expression: (function () { ... })(); or with an arrow function, (() => { ... })();. A statement that starts with the word function is read as a declaration and needs a name, so the parentheses (or an operator such as ! or void in front) force expression parsing.

Why it was used: before let, const, and modules, the only scopes were the function and the global scope. Every top-level var became a property of the global object, and scripts from different files collided. An IIFE wrapped a file or a feature in its own scope. It also created private state: a returned object exposed a public API while the variables stayed hidden in the closure (the module pattern). It also captured the loop variable for each iteration in var loops: (function (i) { ... })(i).

Today:

  • ES modules give every file its own scope, so file-level IIFEs are not needed.
  • let and const are block scoped, so a plain block { ... } creates a private scope for temporary variables.
  • Loop variables declared with let are per iteration.

Where IIFEs still make sense:

  • Initialization that needs several statements to produce a single constant: const config = (() => { ...; return value; })();.
  • Running await in a script that is not a module: (async () => { ... })();. Handle errors with .catch, because an unhandled rejection can otherwise be lost.
  • Scripts that must not touch the global scope, such as bookmarklets, snippets injected into pages, and legacy bundles.
  • Making private state in a quick factory without a class.

Remember that the function runs once, and that an IIFE has its own this (a normal function) or the outer this (an arrow function).

javascript
// classic IIFE with private state
const counter = (function () {
  let count = 0;
  return {
    increment: () => ++count,
    get value() { return count; },
  };
})();
counter.increment();
counter.increment();
console.log(counter.value, typeof count);

// ways to force expression parsing
(function () { console.log('wrapped in parentheses'); })();
(() => console.log('arrow IIFE'))();
!function () { console.log('with a leading operator'); }();
void function () { console.log('with void'); }();

try {
  new Function('function () { }();');
} catch (error) {
  console.log('a bare function declaration call:', error.name);
}

// a constant computed by several statements
const settings = (() => {
  const base = { retries: 3 };
  const fromEnv = Number('2');
  return { ...base, retries: Number.isNaN(fromEnv) ? base.retries : fromEnv };
})();
console.log(settings);

// the old fix for var in loops
var oldStyle = [];
for (var i = 0; i < 3; i++) {
  (function (copy) { oldStyle.push(() => copy); })(i);
}
const withVar = [];
for (var j = 0; j < 3; j++) withVar.push(() => j);
console.log(oldStyle.map((fn) => fn()), withVar.map((fn) => fn()));

// let does the same without an IIFE
const withLet = [];
for (let k = 0; k < 3; k++) withLet.push(() => k);
console.log(withLet.map((fn) => fn()));

// async IIFE
(async () => {
  const value = await Promise.resolve('async result');
  console.log(value);
})().catch((error) => console.error(error));

console.log((function () { return typeof this; }).call('text'), (() => typeof this)());

Run with Node.js v24.22.1 as js-157.js; two runs gave identical output. Output: 2 undefined wrapped in parentheses arrow IIFE with a leading operator with void a bare function declaration call: SyntaxError { retries: 2 } [ 0, 1, 2 ] [ 3, 3, 3 ] [ 0, 1, 2 ] object object async result

Key points

  • An IIFE defines and calls a function at once; parentheses make it an expression.
  • It created private scope and the module pattern before let, const, and modules.
  • Modules and block scope replaced most uses.
  • Still useful for one-off initialization, async code in non-module scripts, and scripts that avoid globals.
  • Handle errors of async IIFEs; this differs between function and arrow forms.

Common mistakes

  • Forgetting the semicolon before an IIFE that starts with a parenthesis, which joins it with the previous line.
  • Using file-level IIFEs inside ES modules, where they add nothing.
  • Leaving an async IIFE without error handling.
  • Expecting this inside an arrow IIFE to be a new object.

Follow-ups

  • Why does a function declaration followed by () give a syntax error?
  • How did the module pattern work before ES modules?
  • When is a plain block with let better than an IIFE?

Tips

  • Explain why the parentheses are needed.
  • Say that modules and let replaced most uses, and name the cases where an IIFE still helps.
  • Mention error handling for async IIFEs.
158.javascript-0158Easyfresher

What do the comma operator, void, and delete do, and when do they matter?

The comma operator evaluates several expressions and returns the last one. void evaluates an expression and always returns undefined. delete removes a property from an object and returns true unless the property cannot be removed. They are rarely needed, but they appear in minified code, for loops, arrow functions that must return nothing, and in questions about arrays and variables.

Full answer

Comma operator: (a, b, c) evaluates a, then b, then c, and the value of the whole expression is c. It is different from the commas in argument lists, array literals, and let a = 1, b = 2, which only separate items. Practical uses: two updates in a for loop header, for (let i = 0, j = 10; i < j; i++, j--), and compact code written by minifiers. Avoid it in normal code, because it hides what is returned.

void expression: evaluates the expression and returns undefined. Uses:

  • void 0 is a safe way to get undefined in old code, where undefined could be overwritten in some scopes.
  • An arrow function that should return nothing: () => void doSomething(). This stops a callback from accidentally returning a value.
  • Marking a promise as intentionally not awaited: void fetchData(), which also satisfies lint rules against floating promises.
  • Legacy: <a href="javascript:void(0)"> to stop navigation. Use a button instead.

delete object.property: removes an own property and returns true if the property is gone or never existed, and false for a non-configurable property (in strict mode it throws a TypeError). Important points:

  • It removes only the property, not the object it referenced (garbage collection frees that when no references remain).
  • It does not affect inherited properties: deleting an own property that shadows a prototype property reveals the inherited one again.
  • On arrays, delete arr[1] leaves a hole and keeps length. Use splice to remove elements.
  • It cannot delete variables declared with var, let, or const, nor functions.
  • Deleting properties on hot objects can slow down engines, so for dictionaries, prefer Map, or set the value to undefined or null.
  • delete on a frozen or sealed object fails.

A related point: delete obj.x is different from obj.x = undefined. After the first, 'x' in obj is false. After the second, it is true.

javascript
let a = (1, 2, 3);
console.log(a, (console.log('evaluated first'), 'result'));
for (let i = 0, j = 5; i < j; i++, j--) console.log('i', i, 'j', j);

console.log(void 0, void 'text', void (1 + 2), typeof void 0);
const handler = () => void console.log('side effect only');
console.log('arrow with void returns:', handler());
const noisy = () => 42;
console.log([1].map(() => void noisy()), [1].map(() => noisy()));

const user = { name: 'Asha', age: 30, nickname: undefined };
console.log(delete user.age, user, 'age' in user, Object.keys(user));
console.log('nickname is undefined but still a key:', 'nickname' in user);
console.log(delete user.missing, delete user.name, user);

const proto = { kind: 'prototype value' };
const child = Object.create(proto);
child.kind = 'own value';
console.log(child.kind);
delete child.kind;
console.log('after delete, inherited value shows:', child.kind);

const list = [1, 2, 3];
delete list[1];
console.log(list, list.length, 1 in list);
list.splice(1, 1);
console.log(list);

const frozen = Object.freeze({ x: 1 });
console.log('delete on frozen object (sloppy mode):', delete frozen.x, frozen);
(function () {
  'use strict';
  try {
    delete frozen.x;
  } catch (error) {
    console.log('strict mode:', error.name);
  }
})();

var declared = 1;
console.log('delete a var declaration:', delete globalThis.declared, typeof declared);

Run with Node.js v24.22.1 as js-158.js; two runs gave identical output. Output: evaluated first 3 result i 0 j 5 i 1 j 4 i 2 j 3 undefined undefined undefined undefined side effect only arrow with void returns: undefined [ undefined ] [ 42 ] true { name: 'Asha', nickname: undefined } false [ 'name', 'nickname' ] nickname is undefined but still a key: true true true { nickname: undefined } own value after delete, inherited value shows: prototype value [ 1, <1 empty item>, 3 ] 3 false [ 1, 3 ] delete on frozen object (sloppy mode): false { x: 1 } strict mode: TypeError delete a var declaration: true number

Key points

  • Comma operator evaluates all operands and returns the last; common in for loop headers and minified code.
  • void returns undefined; used in void 0, no-return arrows, and intentionally floating promises.
  • delete removes an own, configurable property and returns true or false (throws in strict mode when it fails).
  • delete on arrays leaves holes; use splice. It does not remove variables or inherited properties.
  • delete differs from setting undefined: the key disappears from in and Object.keys.

Common mistakes

  • Using delete on array elements and expecting the length to shrink.
  • Using delete on variables.
  • Setting a property to undefined and expecting it to disappear from Object.keys.
  • Writing comma expressions that hide the returned value.

Follow-ups

  • Why can delete slow down an object in an engine?
  • What is the difference between delete obj.x and obj.x = undefined?
  • Where does void appear in lint rules about promises?

Tips

  • Describe each operator in one sentence and give one real use.
  • Mention the array hole behavior of delete.
  • Note that none of these are needed often.
159.javascript-0159Easyfresher

What is the difference between the in operator, Object.hasOwn, and checking a value against undefined when testing for a property?

The in operator is true for own and inherited properties, Object.hasOwn(obj, key) is true only for own properties, and obj.key !== undefined cannot tell a missing property from one whose value is undefined. Use hasOwn for own-property checks on plain data, in when inherited properties count (such as methods), and optional chaining or nullish checks when you only care about a usable value.

Full answer

There are three common ways to ask "does this object have this property?", and they answer different questions.

'key' in obj: true if the property exists on the object or anywhere on its prototype chain, whether or not the value is undefined. So 'toString' in {} is true, because toString is inherited from Object.prototype. It also works with arrays (indexes) and with symbols. It throws a TypeError if the right side is not an object.

Object.hasOwn(obj, 'key'): true only for an own property, including one whose value is undefined. It is the modern replacement for obj.hasOwnProperty('key'). The old form has two problems: it fails on objects with a null prototype (they have no such method), and it breaks if the object has its own property named hasOwnProperty. Object.hasOwn works for both.

obj.key !== undefined (or obj.key == null checks): this reads the value, so it cannot tell a missing property from a property that holds undefined. It also sees inherited values. Use it when you only care whether there is a usable value, often with ?? or ?.: const port = config.port ?? 3000.

Which to choose:

  • Dictionary or parsed JSON data, where inherited keys must not count: Object.hasOwn.
  • Checking for a method or a feature, such as 'fetch' in globalThis, or 'then' in value to detect a thenable: in.
  • Default values: ?? or optional chaining.

Related details: for...in loops over own and inherited enumerable string keys, while Object.keys returns own enumerable keys only. For Map, use map.has(key), which is also the safe choice for user-provided keys. Using plain objects as dictionaries with user keys like __proto__ or constructor is a security risk, so use Map or Object.create(null).

javascript
const base = { inherited: 1 };
const obj = Object.create(base);
obj.own = 'value';
obj.empty = undefined;

for (const key of ['own', 'empty', 'inherited', 'missing', 'toString']) {
  console.log(
    key.padEnd(10),
    'in:', String(key in obj).padEnd(5),
    'hasOwn:', String(Object.hasOwn(obj, key)).padEnd(5),
    '!== undefined:', obj[key] !== undefined,
  );
}

const plain = { hasOwnProperty: 'oops' };
try {
  plain.hasOwnProperty('x');
} catch (error) {
  console.log('old hasOwnProperty style breaks:', error.name);
}
console.log('Object.hasOwn still works:', Object.hasOwn(plain, 'hasOwnProperty'));

const bare = Object.create(null);
bare.key = 1;
console.log('null prototype object:', typeof bare.hasOwnProperty, Object.hasOwn(bare, 'key'), 'toString' in bare);

console.log('arrays:', 1 in ['a', 'b'], 5 in ['a', 'b'], 'length' in [], Object.hasOwn([], 'length'));
try {
  'a' in 'abc';
} catch (error) {
  console.log('in on a string:', error.name);
}

const config = { port: 0, host: null, debug: false };
console.log('|| loses valid falsy values:', config.port || 3000, '| ?? keeps them:', config.port ?? 3000, '| null host falls back:', config.host ?? 'localhost');
console.log('optional chaining:', config.db?.url, config.db?.url ?? 'no db');

const thenable = { then() {} };
console.log('detect a thenable with in:', 'then' in thenable, 'then' in {});

const dictionary = JSON.parse('{"__proto__": 1, "constructor": 2}');
console.log(Object.keys(dictionary), Object.hasOwn(dictionary, '__proto__'), new Map(Object.entries(dictionary)).has('constructor'));

Run with Node.js v24.22.1 as js-159.js; two runs gave identical output. Output: own in: true hasOwn: true !== undefined: true empty in: true hasOwn: true !== undefined: false inherited in: true hasOwn: false !== undefined: true missing in: false hasOwn: false !== undefined: false toString in: true hasOwn: false !== undefined: true old hasOwnProperty style breaks: TypeError Object.hasOwn still works: true null prototype object: undefined true false arrays: true false true true in on a string: TypeError || loses valid falsy values: 3000 | ?? keeps them: 0 | null host falls back: localhost optional chaining: undefined no db detect a thenable with in: true false [ '__proto__', 'constructor' ] true true

Key points

  • in checks own and inherited properties, including those with undefined values.
  • Object.hasOwn checks own properties only and works for null-prototype objects.
  • value !== undefined cannot tell a missing property from a property set to undefined.
  • Prefer hasOwn for data objects and in for feature detection; use ?? and ?. for defaults.
  • Use Map for dictionaries with user-provided keys.

Common mistakes

  • Using obj.hasOwnProperty(key) on data from outside, which may not be a normal object.
  • Using in when only own keys should count.
  • Using || for defaults and losing 0, empty strings, and false.
  • Checking value !== undefined and thinking it proves the key is missing.

Follow-ups

  • Why does the old hasOwnProperty call fail on Object.create(null) objects?
  • What is the difference between Object.keys and for...in?
  • How does a Map avoid the problems of plain objects as dictionaries?

Tips

  • Say which question each check answers.
  • Recommend Object.hasOwn and explain why it replaced hasOwnProperty.
  • Mention Map for user-supplied keys.
160.javascript-0160Easyfresher

How do property shorthand, computed property names, Object.entries, and Object.fromEntries work together?

Property shorthand writes { name } instead of { name: name }, method shorthand drops the function keyword, and computed keys write an expression in square brackets for the property name. Object.entries turns an object into an array of [key, value] pairs, and Object.fromEntries builds an object back from pairs, so together they let you transform objects with array methods such as map and filter.

Full answer

ES2015 added short ways to write objects.

Property shorthand: when a variable name matches the key, write { name, age } instead of { name: name, age: age }. Method shorthand: { greet() { ... } } instead of greet: function () { ... }. A shorthand method can use super, and it is not a constructor, but it still has its own this.

Computed property names: { [expression]: value } evaluates the expression and uses the result as the key. This is useful for dynamic keys ({ [field]: value }), for building keys from parts ([user_${id}]), for symbols ({ [Symbol.iterator]() {} }), and for updating state immutably: { ...state, [name]: value }. Computed keys can also be used in classes and for method names. If the computed value is not a string or symbol, it is converted to a string.

Object.entries(obj) returns an array of [key, value] pairs for the object's own enumerable string keys, in the standard order (integer-like keys ascending, then others in insertion order). Object.keys and Object.values return only keys or values. Object.fromEntries(iterable) does the reverse: it creates an object from any iterable of pairs, including a Map. The two together give a pattern for transforming objects: Object.fromEntries(Object.entries(obj).filter(...).map(...)). Typical tasks: pick or omit keys, map the values of an object, swap keys and values, convert between Map and object, and parse a query string into an object (Object.fromEntries(new URLSearchParams(search))).

Notes:

  • Duplicate keys in fromEntries: later pairs override earlier ones, and a repeated query string key keeps only the last value.
  • Symbols are ignored by entries.
  • Only own, enumerable properties are included. Inherited properties and non-enumerable ones are skipped.
  • A key like __proto__ in a literal sets the prototype, while ['__proto__'] creates a normal property.
javascript
const name = 'Asha';
const age = 30;
const person = { name, age, greet() { return `Hi, I am ${this.name}`; } };
console.log(person, person.greet());

const field = 'email';
const id = 7;
const key = Symbol('secret');
const dynamic = { [field]: 'a@example.com', [`user_${id}`]: true, [1 + 1]: 'two', [key]: 'hidden' };
console.log(dynamic, Object.keys(dynamic));

const state = { count: 1, theme: 'light' };
const update = (name, value) => ({ ...state, [name]: value });
console.log(update('theme', 'dark'), state);

const prices = { apple: 1.2, pear: 0.8, melon: 3.5 };
console.log(Object.entries(prices));
const doubled = Object.fromEntries(Object.entries(prices).map(([item, price]) => [item, price * 2]));
const cheap = Object.fromEntries(Object.entries(prices).filter(([, price]) => price < 2));
const swapped = Object.fromEntries(Object.entries({ a: 1, b: 2 }).map(([k, v]) => [v, k]));
console.log(doubled, cheap, swapped);

const pick = (object, keys) => Object.fromEntries(keys.filter((k) => k in object).map((k) => [k, object[k]]));
const omit = (object, keys) => Object.fromEntries(Object.entries(object).filter(([k]) => !keys.includes(k)));
console.log(pick(prices, ['apple', 'kiwi']), omit(prices, ['melon']));

const map = new Map([['x', 1], ['y', 2]]);
console.log(Object.fromEntries(map), new Map(Object.entries({ z: 3 })));
console.log(Object.fromEntries(new URLSearchParams('page=2&sort=asc&page=3')));

console.log(Object.entries({ b: 1, 2: 'two', a: 2, 1: 'one', [Symbol('s')]: 'skipped' }));
console.log(Object.fromEntries([['dup', 1], ['dup', 2]]));

const literal = { __proto__: { inherited: true } };
const computed = { ['__proto__']: 'plain property' };
console.log(literal.inherited, Object.keys(literal), Object.keys(computed));

Run with Node.js v24.22.1 as js-160.js; two runs gave identical output. Output: { name: 'Asha', age: 30, greet: [Function: greet] } Hi, I am Asha { '2': 'two', email: 'a@example.com', user_7: true, Symbol(secret): 'hidden' } [ '2', 'email', 'user_7' ] { count: 1, theme: 'dark' } { count: 1, theme: 'light' } [ [ 'apple', 1.2 ], [ 'pear', 0.8 ], [ 'melon', 3.5 ] ] { apple: 2.4, pear: 1.6, melon: 7 } { apple: 1.2, pear: 0.8 } { '1': 'a', '2': 'b' } { apple: 1.2 } { apple: 1.2, pear: 0.8 } { x: 1, y: 2 } Map(1) { 'z' => 3 } { page: '3', sort: 'asc' } [ [ '1', 'one' ], [ '2', 'two' ], [ 'b', 1 ], [ 'a', 2 ] ] { dup: 2 } true [] [ '__proto__' ]

Key points

  • Shorthand: { name } for matching variable names, and method shorthand without the function keyword.
  • Computed keys use [expression] to make dynamic, symbol, or generated keys.
  • Object.entries gives [key, value] pairs of own enumerable string keys; fromEntries builds an object from pairs.
  • entries plus array methods plus fromEntries transforms objects: pick, omit, map values, swap.
  • Later duplicate keys win; symbols and inherited keys are skipped.

Common mistakes

  • Writing {name: name} everywhere instead of shorthand, or using shorthand when the variable name differs from the key.
  • Forgetting the square brackets and getting the literal key name.
  • Expecting entries to include inherited properties or symbols.
  • Losing repeated values when turning a query string into an object.

Follow-ups

  • How would you invert an object whose values are not unique?
  • What is the order of keys that Object.entries returns?
  • When would you use a Map instead of an object for key-value data?

Tips

  • Show the entries, transform, fromEntries pattern with one example.
  • Mention the immutable update with a computed key.
  • Remember that later duplicates override earlier ones.