All categories

Category

JavaScript

Closures, async, prototypes, modules, and language internals.

117 questions

117 of 117
JavaScript
Easy
hot
What gets hoisted in JavaScript and how does it actually work?

Function declarations are fully hoisted (callable before the line). `var` is hoisted and initialized to undefined. `let`/`const`/`class` are hoisted but uninitialized — accessing them before the declaration throws (Temporal Dead Zone).

5 min
JavaScript
Easy
What is hoisting in JavaScript and what is the temporal dead zone?

Declarations are 'hoisted' to the top of their scope. `var` is hoisted and initialized to `undefined` (no TDZ). `let`/`const` are hoisted but in a Temporal Dead Zone (TDZ) until the declaration line — reading them throws ReferenceError. Function declarations are fully hoisted (callable before the line); function expressions and arrow functions follow the `var`/`let`/`const` rules of whatever declares them.

4 min
JavaScript
Medium
Can you explain hoisting in JavaScript with a code example?

Hoisting: declarations are processed before code runs. `var` declarations hoist to function scope, initialized to `undefined`. Function declarations hoist *with* their value. `let`/`const` hoist but stay in the Temporal Dead Zone until the declaration line — accessing them throws ReferenceError. Class declarations are TDZ too.

3 min
JavaScript
Easy
How do you use typeof and instanceof, and what is reliable type checking in JavaScript?

`typeof` returns a primitive type string but is wrong for null ("object") and arrays. `instanceof` checks the prototype chain but fails across realms (iframes). The reliable cross-realm check is `Object.prototype.toString.call(x)` → "[object Array]" etc. For primitives use `typeof`; for arrays `Array.isArray`; for null `=== null`; for plain objects there's no perfect check.

4 min
JavaScript
Easy
How does object reference comparison differ from primitive comparison in JavaScript?

Primitives compared by value: `1 === 1` is true. Objects compared by reference: `{a:1} === {a:1}` is false (different references). `===` (strict equality) skips coercion; `==` coerces (`1 == "1"` is true). For deep object equality, use `Object.is` for special cases or a deepEqual utility. `Object.is(NaN, NaN)` is true; `NaN === NaN` is false.

3 min
JavaScript
Medium
How does the value of this behave in Node.js compared to a browser console?

Browser console (script): `this` at top level is `window` (or `globalThis`). Node CommonJS module: top-level `this` is `module.exports` (which is `{}` initially), NOT `global`. Node ESM: top-level `this` is `undefined`. Inside functions: same rules everywhere — depends on call site, strict mode, arrow vs regular.

3 min
JavaScript
Medium
Can you explain how call, apply, and bind work in JavaScript?

`call(thisArg, ...args)` invokes immediately with a given `this`. `apply(thisArg, argsArray)` is the same but with args as an array. `bind(thisArg, ...partials)` returns a new function with `this` permanently set. The polyfill closes over `thisArg` + partials and uses `apply` (or `call`) internally — plus a `new.target` check so the bound function still works as a constructor.

5 min
JavaScript
Easy
What does the new operator do in JavaScript?

`new F(args)` does four things: (1) create an empty object whose prototype is `F.prototype`, (2) call `F` with `this` bound to the new object, (3) if `F` returns an object, use that; otherwise use the new object, (4) return the result. Powers class instantiation and constructor functions. Arrow functions can't be `new`'d.

3 min
JavaScript
Medium
What does obj.print() log when the print method uses this.value?

It depends entirely on HOW the method is called, not where it's defined. obj.print() → 'this' is obj. But pull the method off (const p = obj.print; p()) and 'this' is lost (undefined/global). Arrow methods capture lexical 'this', not obj. The lesson: 'this' is determined at call time.

5 min
JavaScript
Medium
When do function declarations versus arrow functions actually impact performance?

The function form itself (declaration vs arrow) is essentially zero perf impact. What matters is identity stability across renders in React: a new arrow function created inside a component on every render creates a new reference, which busts React.memo on child components and adds churn for useEffect deps. The fix is useCallback, hoisting, or stable references — not changing function syntax. For non-React code, the difference is negligible.

6 min
JavaScript
Easy
What is a closure and where have you used one in practice?

Closure = function + the variables of its enclosing scope, kept alive because the function references them. Real uses: private state in factories/modules, memoization caches, partial application/currying, React hooks capturing renders' props, debounce/throttle holding their timer, event handlers needing per-instance config.

3 min
JavaScript
Easy
How do closures and lexical scoping work in JavaScript?

A closure is a function that retains access to variables from the scope it was defined in, even after that outer scope has returned. Lexical scoping means scope is determined by where code is written, not where it's called. Powers module patterns, factories, currying, React hooks' captured values, and event handler state.

4 min
JavaScript
Easy
What is currying in JavaScript and when would you use it?

Currying transforms an n-arg function into a chain of unary calls: `f(a, b, c)` becomes `f(a)(b)(c)`. Implemented with closures. Useful for composition, point-free style, and reusable handlers. Distinct from partial application (which pre-fills some args once).

3 min
JavaScript
Easy
What is the difference between currying and partial application in JavaScript?

Currying: transform an n-arg function into a chain of unary functions — `f(a, b, c)` becomes `f(a)(b)(c)`. Partial application: pre-fix some args, returning a function expecting the rest — `f.bind(null, a)`. Both rely on closures. Useful for point-free style, event handlers per item, and composition. Overused, they hurt readability.

4 min
JavaScript
Easy
What are common interview questions that combine closures and currying?

Closures: inner functions remember their enclosing scope. Currying turns `f(a,b,c)` into `f(a)(b)(c)` using nested closures. Combined patterns interviewers love: counter factories, once/memoize, partial application, debounce/throttle, infinitely-curryable functions like `sum(1)(2)(3)... .valueOf()`.

4 min
JavaScript
Easy
Can you explain closures, hoisting, the event loop, and currying in JavaScript?

Four core JS concepts: closures (a function + its remembered lexical scope), the event loop (the scheduler that runs queued async callbacks on the single thread), hoisting (declarations are processed before execution — var/function hoisted, let/const in the temporal dead zone), and currying (transforming f(a,b,c) into f(a)(b)(c) via closures).

6 min
JavaScript
Easy
What is the difference between prototypal and classical inheritance in JavaScript?

Classical (Java/C++): classes are blueprints; objects are instances. Inheritance is declarative + compile-time. Prototypal (JS): objects inherit from other **objects** via the [[Prototype]] chain — runtime-flexible. ES6 `class` is syntactic sugar over prototypes. In practice both look similar; the JS difference is that you can compose objects dynamically (`Object.create`, mixins, delegation).

4 min
JavaScript
Medium
How can a library extend native objects via the prototype chain without breaking consumer code?

Every object has a hidden [[Prototype]] pointer. Property lookup walks this chain. SDKs that need to extend native types do so safely by **subclassing or adding namespaced static helpers**, not patching `Array.prototype` etc. — that pollutes globals and can collide with merchant code. The safe API gives consumers an SDK object whose own prototype chain is private.

4 min
JavaScript
Medium
How do you apply object oriented programming patterns in JavaScript?

Use `class` for encapsulated kinds (component, model, service). Fields for state, methods on prototype, private fields with `#`, `static` for class-level helpers, `extends` + `super` for inheritance. Favor composition + small classes; avoid deep hierarchies. For pure-data shapes use plain objects + TypeScript types, not classes.

5 min
JavaScript
Medium
How do array and object destructuring work in JavaScript?

Destructuring pattern-matches a value's shape: arrays by index, objects by key. Supports defaults (`= 0`), renaming (`{a: b}`), rest (`...rest`), nested patterns, and works in parameters. Under the hood, it desugars to indexed/property access — array destructuring uses the iterator protocol.

3 min
JavaScript
Medium
How do you use the spread and rest operators in JavaScript?

Same `...` syntax, opposite jobs. Spread EXPANDS an iterable/object into individual elements (copying arrays/objects, passing args). Rest COLLECTS multiple elements into one array (variadic params, destructuring). Both do shallow copies — nested objects are still shared.

4 min
JavaScript
Easy
What is the difference between Map and a plain Object in JavaScript?

Object: string/symbol keys, prototype chain (collisions like `__proto__`), no insertion order guarantee for integer-like keys, JSON-friendly. Map: any key (including objects, NaN, null), preserves insertion order, has `.size`, no prototype chain. Use Map when keys are non-strings, you need size, or iteration order matters; object for JSON-shaped data.

3 min
JavaScript
Easy
When should you reach for Map versus a plain Object in JavaScript?

Object: keys are strings/symbols, key order is mostly insertion (with integer-key quirks), prototype chain pollution. Map: any key type (objects, NaN), guaranteed insertion order, .size in O(1), better for frequent add/remove. Use Map for dictionaries; Object for shaped records.

5 min
JavaScript
Medium
What are WeakMap and WeakSet, and when would you use them?

Map/Set variants that hold their keys/values weakly — if nothing else references the object, it can be garbage-collected and the entry disappears. Keys must be objects; not iterable; no size. Use for: per-object private data, object-keyed caches that self-clean, and marking objects without leaking memory.

4 min
JavaScript
Medium
What are WeakMap and WeakSet in JavaScript, and what are their use cases?

WeakMap/WeakSet hold their keys/values WEAKLY — if nothing else references a key, it can be garbage-collected, and the entry vanishes. Keys must be objects. They're not iterable and have no size. Use cases: private data per object, caching/memoization keyed by object, and tracking objects without leaking memory.

4 min
JavaScript
Medium
When should you not use map, filter, or reduce in JavaScript?

Avoid functional iteration when: you need early exit (use `for` / `for..of` / `find` / `some`), you're chaining many passes over a large array (multiple traversals + allocations — use one for loop), the side effect is the point (`forEach`, but `for..of` reads better), or readability suffers from a tangled `reduce`. Idiomatic for transforms; not a universal hammer.

4 min
JavaScript
Easy
What are Promises in JavaScript and how do they work?

Objects representing the eventual outcome of an async operation. Three states: pending → fulfilled or rejected, settled once and then immutable. Read via `.then` / `.catch` / `.finally` or await. Static aggregators: `Promise.all`, `allSettled`, `race`, `any`. Replaced callbacks with composable async.

3 min
JavaScript
Medium
What is a Promise in JavaScript, how do you resolve one, and what are common use cases?

A Promise is an object representing the eventual result of an async operation. States: pending → fulfilled or rejected (once, then immutable). Create with `new Promise((resolve, reject) => …)`. Use for: fetch, timers, file I/O, any async API — and chain with `.then` / `.catch` or await. Promises moved JS off callback hell.

4 min
JavaScript
Easy
How would you write a function that returns a resolved Promise with a value?

Write a Promise-returning function that resolves with a value. Most common form: `function task() { return new Promise(res => setTimeout(() => res(value), ms)); }`. Or short: `return Promise.resolve(value)`. Real-world: wrap a non-Promise API (geolocation, FileReader, setTimeout) so it composes with async/await.

2 min
JavaScript
Medium
How does async/await actually work under the hood in JavaScript?

`async` makes a function return a Promise; `await` pauses the function until the awaited Promise settles. Same semantics as `.then` chains, but reads sequentially. Errors become rejected Promises; catch with try/catch or .catch at the call site. Independent awaits should be `Promise.all`'d, not sequential.

4 min
JavaScript
Medium
How do async/await and Promises relate, and how does the event loop handle them?

async/await is syntax sugar over Promises — same machinery. `await` pauses the async function and schedules its continuation as a microtask when the awaited Promise settles. So `await x` ≈ `.then(continuation)`. The event loop treats both identically: continuations are microtasks, drained fully before the next macrotask.

6 min
JavaScript
Medium
How does JavaScript handle asynchronous operations and what mechanisms does it use?

JS is single-threaded; async work uses the event loop. Mechanisms: Web APIs / Node libuv (timers, I/O, network) → task queues (macrotasks for setTimeout, I/O; microtasks for Promises, queueMicrotask). Event loop picks one task → drains microtasks → renders → repeat. Workers give true parallelism. AbortController for cancellation.

5 min
JavaScript
Medium
How are asynchronous tasks executed in JavaScript?

Duplicate-style question on the event loop and async execution: JS hands async work to Web APIs, which queue callbacks (microtask for Promises, macrotask for timers/events) on completion; the event loop drains all microtasks then runs one macrotask whenever the call stack is empty.

5 min
JavaScript
Medium
How do you handle asynchronous code using async/await and Promises?

Default to async/await for readability. Use Promise.all for parallel independent work, Promise.allSettled when you want every result regardless of failure, Promise.race / any for first-to-finish. Always wrap awaits in try/catch (or .catch on the call site). Pass an AbortSignal for cancellation. Never await sequentially when work is independent.

4 min
JavaScript
Easy
How do you handle errors in asynchronous JavaScript code?

Wrap awaits in try/catch or attach `.catch` at the call site. Unhandled rejections in browsers fire `unhandledrejection` event and console warning; in Node, eventually crash (since v15). Distinguish error kinds (network, 4xx, 5xx, AbortError). Use error boundaries (React) at UI level. Don't swallow errors with empty catch — escalate or convert to domain errors.

4 min
JavaScript
Easy
What is Node.js and how does its event loop differ from the browser's?

Node.js is a JS runtime built on V8 that runs JS outside the browser, using libuv for async I/O. Its event loop has distinct phases — timers, pending callbacks, poll, check (setImmediate), close — and between every phase it drains microtasks (Promises) and process.nextTick (which runs even before Promises). Same single-threaded model, different phase structure than the browser.

6 min
JavaScript
Medium
How does the JavaScript event loop work?

JavaScript is single-threaded with one call stack. Async work (timers, fetch, events) is handed to Web APIs / the host. When it completes, a callback is queued. The event loop runs: when the call stack is empty, it drains ALL microtasks (Promises, queueMicrotask), then takes ONE macrotask (timer, I/O, event) and repeats — rendering can happen between macrotasks.

6 min
JavaScript
Medium
How do execution contexts, the call stack, and async behavior fit together in JavaScript?

An execution context is the environment a piece of code runs in — it has a variable environment, scope chain, and `this`. The global context is created first; each function call pushes a new context on the call stack. Async behavior layers on top: Web APIs run async work off-thread and queue callbacks; the event loop pushes them back as new contexts when the stack is empty.

6 min
JavaScript
Easy
What is the difference between the microtask and macrotask queues?

Microtasks (Promise reactions, queueMicrotask, MutationObserver) are drained ENTIRELY after each task and before rendering. Macrotasks (setTimeout, setInterval, DOM events, I/O) run ONE per loop iteration. So all pending Promise callbacks run before the next setTimeout — and an unbounded microtask chain can starve macrotasks and block paint.

6 min
JavaScript
Easy
What kinds of operations can block JavaScript execution while running?

Synchronous code blocks the main thread until it finishes — long loops, big JSON.parse, sync XHR, alert/confirm/prompt, document.write, deep recursion. While blocked, no events, no rendering, no timers. Mitigate: break into chunks (yield to microtask/macrotask), use Web Workers for CPU, async APIs only, and avoid the listed blocking calls in production.

4 min
JavaScript
Easy
How do you approach output prediction questions involving Promises and async behavior?

Classic 'what's the output' problems hinge on: microtask queue order (Promises before setTimeout), synchronous code first, async function continuations are microtasks, await suspends even when value is already resolved, Promise.resolve().then(...) doesn't immediately invoke. Trace stack → micro → macro and you'll predict any ordering.

5 min
JavaScript
Medium
How do you handle multiple asynchronous operations using Promises?

A Promise is a placeholder for a future value — pending → fulfilled or rejected, settled once. For multiple async ops: `Promise.all` (fail-fast parallel), `Promise.allSettled` (parallel, never rejects, returns per-result status), `Promise.race` (first to settle), `Promise.any` (first to fulfill, ignores rejections). Use `for await…of` or a worker pool when you need bounded concurrency.

6 min
JavaScript
Medium
How is Promise.allSettled different from Promise.all, and when would you use it?

`Promise.all` rejects as soon as any input rejects — short-circuits. `Promise.allSettled` always resolves once every input has settled, with an array of `{status, value|reason}` objects. Use `allSettled` for independent best-effort work (dashboard cards, batch operations, analytics) where partial success is meaningful.

3 min
JavaScript
Medium
How do you send multiple API requests in parallel from a single button click?

Fire all with `Promise.all` if independent and you need all results; `Promise.allSettled` if you want every result regardless of failure; `p-limit` or a small async-pool for many requests (avoid hammering the server); chain awaits only when one depends on another's output. Add AbortController for cancel-on-unmount. Disable the button while in flight.

3 min
JavaScript
Medium
How do you handle errors when multiple requests are sent simultaneously?

Choose by semantics: `Promise.all` rejects on first failure — good for atomic ops. `Promise.allSettled` collects per-item outcomes — good for independent work. Retry transient failures with exponential backoff. Use AbortController to cancel siblings if one critical request fails. Surface partial-success states explicitly in UI.

4 min
JavaScript
Easy
How do you cancel an in flight fetch request in JavaScript?

fetch has no built-in timeout. Combine AbortController + setTimeout: create a controller, schedule abort() after N ms, pass signal to fetch, and clear the timer in finally. Always clear the timer to avoid aborting a now-completed request. Wrap into a reusable fetchWithTimeout helper. On modern platforms, AbortSignal.timeout(ms) is a one-liner replacement.

6 min
JavaScript
Easy
What are dynamic imports in JavaScript, and what do they enable?

import() is a function-like expression that loads a module on demand and returns a Promise. It enables code splitting, lazy loading, conditional/feature-flagged loading, and reduced initial bundle size — the foundation of React.lazy and route-based splitting.

4 min
JavaScript
Medium
What is the difference between npm and yarn?

Both are package managers for the npm registry. Yarn originally fixed npm's speed, lockfile, and determinism gaps; npm has since caught up (package-lock, npm ci, workspaces). Today differences are small — Yarn Berry adds PnP/zero-installs; pnpm is the notable alternative with a content-addressed store.

4 min
JavaScript
Easy
How would you write a custom debounce function in JavaScript?

Debounce: delay invoking until N ms have passed since the last call. Implementation captures a timer in a closure; each call clears the prior timer and schedules a new one. Variants: leading edge (call immediately, then ignore), trailing (default), `flush` / `cancel` methods, AbortSignal support.

3 min
JavaScript
Medium
How would you implement debouncing in JavaScript?

Debounce delays running a function until it stops being called for a set wait time — each call resets a timer. Implement with a closure over a timer id: clear the previous timeout and set a new one. Used for search-as-you-type, autosave, and resize handlers.

6 min
JavaScript
Medium
How would you implement throttling in JavaScript?

Throttle = call the function at most once per N ms regardless of how often the trigger fires. Two flavors: leading (fire immediately, then ignore until cooldown ends) and trailing (fire on the last call within the window). Track lastCall timestamp; compare to now; schedule a trailing call if needed.

3 min
JavaScript
Easy
How would you write a custom implementation of Function.prototype.bind?

`bind` returns a new function with `this` permanently bound and optionally some pre-applied arguments. Implementation: `Function.prototype.myBind = function(thisArg, ...preset) { const fn = this; return function (...rest) { return fn.apply(thisArg, [...preset, ...rest]); }; }`. Subtlety: bound function called with `new` should ignore thisArg and construct.

3 min
JavaScript
Easy
How would you write a polyfill for Function.prototype.bind that supports new?

`bind` returns a new function with `this` pre-set and optional args pre-applied. Polyfill: closure capturing thisArg + preset args, returning a function that calls the original via `apply`. Handle `new`: when called as constructor, ignore thisArg and use the freshly constructed `this`. Set `bound.prototype = Object.create(fn.prototype)` so instanceof checks work.

2 min
JavaScript
Easy
How would you implement a polyfill for Array.prototype.reduce?

Iterate the array applying the callback with an accumulator. If initial value supplied, start there; else use the first defined element as initial and start from index 1. Skip holes (sparse). Throw TypeError on empty array with no initial. Pass (acc, cur, i, arr) signature.

3 min
JavaScript
Easy
How would you implement a polyfill for Object.assign?

Object.assign(target, ...sources) copies enumerable own properties from sources onto target, left to right, and returns target. Polyfill: validate target isn't null/undefined, Object() it, loop sources, copy own enumerable keys (use hasOwnProperty), return target. Note it's a shallow copy.

4 min
JavaScript
Easy
How would you implement a polyfill for Object.create?

Object.create(proto) makes a new object whose [[Prototype]] is proto. Classic polyfill: a temp constructor function F whose prototype is set to proto, then return new F(). Handle null proto and the optional propertiesDescriptor second argument via Object.defineProperties.

4 min
JavaScript
Easy
How would you implement a polyfill for JSON.parse?

A recursive descent parser: tokenize the JSON string, then parse values by type (object, array, string, number, true/false/null). Handle whitespace, escape sequences, nesting, and throw SyntaxError on malformed input. The realistic answer is explaining the parser structure, not a flawless full implementation.

5 min
JavaScript
Easy
How would you implement a polyfill for JSON.stringify?

Recursively serialize by type: primitives (string→quoted, number/boolean→String, null→'null'), arrays → [...], objects → {...} with quoted keys. Skip undefined/functions/symbols in objects (→ omitted) but render them as null in arrays. Handle the gotchas: NaN/Infinity→null, toJSON(), circular refs throw.

5 min
JavaScript
Easy
How would you implement a polyfill for setTimeout?

There's no pure-JS way to create a real timer — setTimeout is a host API. The realistic 'polyfill' is a wrapper that adds features (cancellable handle, arg forwarding) or a custom scheduler built on requestAnimationFrame comparing timestamps. The interview is about understanding the event loop and that timers are host-provided.

4 min
JavaScript
Easy
How would you implement a polyfill for setInterval?

Implement setInterval using recursive setTimeout: schedule a timeout that runs the callback then reschedules itself. This is actually BETTER than native setInterval — it guarantees a full gap between executions and never stacks callbacks. Return a handle with a clear method.

4 min
JavaScript
Easy
How would you write a polyfill for Promise.all that handles both resolve and reject cases?

Return a new Promise. Track a results array and a fulfilled count. For each input promise, on fulfill: write the value at its index, increment count, resolve outer when count === length. On reject: reject the outer Promise immediately (short-circuit). Handle the empty-array case (resolve with []) and non-Promise inputs (wrap with Promise.resolve).

3 min
JavaScript
Easy
How would you implement a DOM like data structure in JavaScript?

A node tree: `{ tag, attrs, children, parent }`. Operations: `createNode`, `append`, `remove`, `find` (by tag/id/predicate via DFS), `traverse`, `toHTML` (serialize). Mirror the DOM's parent/child invariants — appending a node detaches it from its previous parent. Useful for templating engines, virtual DOM exercises, and tree manipulation problems.

4 min
JavaScript
Easy
How would you implement a chainable Driver class in JavaScript?

Method chaining with deferred async actions: each method enqueues an operation and returns `this` synchronously; an internal promise chain awaits each step. Common interview ask: `driver.start().drive(10).stop().wait(5).honk()` — each call appended to a queue, executed in order, with errors propagating cleanly.

4 min
JavaScript
Easy
How would you build React style class components from scratch in ES5?

Build a minimal class component model in plain ES5: a Component constructor with setState that re-renders, a tiny VDOM createElement/render pipeline, prototypal inheritance for user components. Demonstrates understanding of prototypes, state-update batching, and the render/diff/commit loop.

8 min
JavaScript
Easy
How would you implement an event emitter from scratch?

A `Map<eventName, Set<listener>>` with `on`/`off`/`emit`/`once`. `on` returns an unsubscribe function. `emit` calls listeners with the payload (synchronously by default; isolate errors so one bad listener doesn't break the rest). Supports wildcard or namespacing as extensions. Foundation for pub/sub, custom stores, and decoupled module communication.

4 min