ESC

Type to search the knowledge base.

Interview questions

Top 50 JavaScript & React Interview Questions (with answers)

Revision list of 50 javascript & react interview questions for frontend engineers, with concise answers and links to deeper Frontend Beauty guides. Composite list for practice—not a ranked survey.

Composite practice list based on common frontend interview themes and publicly discussed fundamentals. Ordering is editorial for learning, not a statistical “most asked” ranking from a single company.

How to use this list

  • Answer out loud in 60–90 seconds, then check the written answer.
  • Where a “Deeper guide” link appears, open it after you attempt the answer yourself.
  • Pair with DSA, machine coding, and playground drills.
  1. javascript

    1.What is the JavaScript event loop?

    A single JS agent has one call stack. Host APIs (timers, network, DOM) finish work and queue callbacks. The event loop runs a macrotask until the stack is empty, drains all microtasks, may render, then takes the next macrotask. Workers are separate agents with their own stacks.

    Deeper guide →

  2. react

    2.What is React’s core mental model?

    UI is a function of state. You describe trees of elements; React reconciles descriptions and updates the host tree (DOM or native). Prefer data → view over imperative DOM mutation.

    Deeper guide →

  3. javascript

    3.What is the difference between microtasks and macrotasks?

    Microtasks (promise reactions, queueMicrotask, await continuations, MutationObserver) run after the current stack and before the next macrotask or paint. Macrotasks include timers, many DOM events, and other host tasks. That is why Promise.then usually runs before setTimeout(0). Footgun: endless microtasks starve rendering.

    Deeper guide →

  4. react

    4.What is reconciliation in React?

    The process of comparing the previous tree to the next one to decide what to insert, update, or remove. Same type at a position updates; different type remounts. Keys give list items identity.

    Deeper guide →

  5. javascript

    5.What is a closure in JavaScript?

    A function bundled with its lexical environment—the outer bindings it can still reach. Closures capture bindings, not frozen snapshots of values. Footgun: a long-lived callback that closes over a large object keeps that object alive for GC.

    Deeper guide →

  6. react

    6.Why do list keys matter?

    Keys preserve identity across renders so state and DOM attach to the correct items. Index keys break when you reorder or insert—inputs and local state glitch. Prefer stable IDs from data.

    Deeper guide →

  7. javascript

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

    var is function-scoped and hoisted as undefined. let and const are block-scoped and stay in the temporal dead zone until initialized. const cannot rebind the identifier (object contents can still mutate). Prefer const by default, let when reassignment is needed.

  8. react

    8.What is the difference between props and state?

    Props are inputs from the parent (read-only for the child). State is data the component owns and can update over time. Lift state to the closest common owner that needs to coordinate children.

  9. javascript

    9.What is the temporal dead zone?

    From the start of a block until a let/const binding is initialized, accessing it throws ReferenceError. That gap is the TDZ. It prevents using bindings before their declaration runs.

  10. react

    10.What is a controlled input in React?

    The input’s value is driven by React state via value + onChange. Uncontrolled inputs keep value in the DOM and use refs. Controlled forms make validation and programmatic resets easier.

  11. javascript

    11.How does this binding work in JavaScript?

    this is set by the call site: default (undefined in strict, global in sloppy), method call (receiver), call/apply/bind, or new. Arrow functions do not have their own this—they capture lexical this. Footgun: extracting a method loses its receiver unless you bind it.

  12. react

    12.How does useState’s functional update work?

    setState(prev => next) uses the latest queued state, avoiding stale closures when the next value depends on the previous one. Prefer it inside async handlers and effects that schedule updates.

  13. javascript

    13.What is the difference between call, apply, and bind?

    call and apply invoke a function immediately with a chosen this; apply takes arguments as an array-like. bind returns a new function with bound this (and optional partial args) for later invocation.

  14. react

    14.What is useEffect for—and what is it not for?

    Effects synchronize with external systems (network, subscriptions, timers, non-React widgets). Do not use effects to transform data for render—compute during render. Put user-event logic in event handlers.

  15. javascript

    15.What is prototypal inheritance?

    Objects delegate property lookup along [[Prototype]]. If a property is missing, the engine walks the chain. class is syntactic sugar over constructor functions and prototypes. Footgun: mutating shared prototypes affects all instances.

  16. react

    16.How should you think about the useEffect dependency array?

    Include every reactive value the effect reads. Missing deps cause stale closures; unstable deps (new objects each render) cause loops. eslint-plugin-react-hooks exists for a reason.

  17. javascript

    17.What is the difference between ==, ===, and Object.is?

    === is strict equality without coercion. == applies type coercion and is usually avoided. Object.is is like === except NaN is equal to NaN and +0 is not equal to -0.

  18. react

    18.What is a stale closure in React?

    A function captured an old props/state value from a previous render. Fix with functional updates, correct effect deps, or refs for “latest value” when intentional.

    Deeper guide →

  19. javascript

    19.What is a Promise?

    An object for a value that may arrive later: pending, then fulfilled or rejected once. Handlers run as microtasks. async/await is sugar over promises. Footgun: fetch only rejects on network failure—check response.ok for HTTP errors.

    Deeper guide →

  20. react

    20.When should you use useMemo and useCallback?

    useMemo caches expensive derived values; useCallback stabilizes function identity for memoized children or effect deps. Measure first—blind memoization adds comparison cost and noise.

  21. javascript

    21.When do you use Promise.all versus Promise.allSettled?

    Promise.all fails fast on the first rejection and is right when any failure should abort the batch. allSettled waits for every promise and reports each status—better when partial success is useful. Neither cancels in-flight work; pair with AbortController when needed.

    Deeper guide →

  22. react

    22.What does React.memo do?

    It skips re-rendering a component when props are shallow-equal. New inline objects/functions every render defeat it. Fix prop stability before wrapping everything in memo.

    Deeper guide →

  23. javascript

    23.Does async/await block the main thread?

    No. await pauses that async function and schedules the continuation as a microtask when the promise settles; the call stack can run other work. Heavy CPU after await still blocks—chunk work or use a worker.

    Deeper guide →

  24. react

    24.What is useRef used for?

    A mutable box that survives renders without causing re-render, and a way to hold host DOM nodes. Do not use ref reads/writes as a substitute for state that should appear on screen.

  25. javascript

    25.What is AbortController and why does it matter?

    It provides a signal to cancel abortable operations like fetch. Essential when users type fast, navigate away, or race multiple requests—otherwise stale responses can overwrite newer UI state.

  26. react

    26.When do you use useLayoutEffect?

    When you must measure or mutate the DOM before the browser paints to avoid a visual flash. Prefer useEffect for most work—layout effects block paint.

  27. javascript

    27.What is the difference between debounce and throttle?

    Debounce waits until events stop for N ms, then runs once (search boxes). Throttle runs at most once per interval while events continue (scroll sampling). Pick based on whether you care about the trailing quiet moment or a steady sample rate.

    function debounce(fn, ms) {
      let t;
      return (...args) => {
        clearTimeout(t);
        t = setTimeout(() => fn(...args), ms);
      };
    }
  28. react

    28.What problems does Context solve, and what are the costs?

    It avoids prop drilling for low-frequency data (theme, locale, auth user). Any provider value change re-renders consumers—split contexts and memoize values for high-frequency data.

  29. javascript

    29.What is event delegation?

    Attach one listener on a parent and use bubbling (and closest) to handle events from dynamic children. Scales better than per-row listeners. Footgun: some events do not bubble (focus uses focusin; check the event).

  30. react

    30.When is useReducer a better fit than useState?

    When updates are multi-field, interdependent, or easier to reason about as named actions. Reducers centralize transitions and simplify tests of state logic.

  31. javascript

    31.What is the difference between preventDefault and stopPropagation?

    preventDefault stops the browser’s default action (e.g. form submit navigation). stopPropagation stops the event from reaching other nodes along the capture/bubble path; listeners on the same element still run unless you use stopImmediatePropagation.

  32. react

    32.What are error boundaries?

    Components that catch render errors in their child tree and show fallback UI. They do not catch event-handler or async errors outside render—handle those separately and report to monitoring.

  33. javascript

    33.How do localStorage, sessionStorage, and cookies differ?

    localStorage/sessionStorage are JS-readable string stores (session ends with the tab for sessionStorage). Cookies are sent on HTTP requests and can be HttpOnly (not readable by JS), Secure, and SameSite—use those for session tokens when appropriate. Never store secrets in web storage if XSS is possible.

  34. react

    34.What is the difference between composition and inheritance in React?

    React favors composition: children, slots, and wrappers. Inheritance hierarchies of components are rarely used; share behavior with hooks and utilities instead.

  35. javascript

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

    Map accepts any key type, has reliable size, and iterates in insertion order. Objects coerce keys to strings/symbols and inherit Object.prototype keys unless you are careful. Prefer Map for dynamic key-value collections.

  36. react

    36.How does code splitting work with React.lazy?

    React.lazy(() => import(...)) loads a component on demand; wrap with Suspense for a fallback. Use it for heavy routes/widgets to cut initial JS. Handle load failures.

  37. javascript

    37.What is a WeakMap used for?

    It holds object keys weakly so entries can be garbage-collected when the key is otherwise unreachable. Useful for private metadata or caches tied to DOM nodes without leaking them.

  38. react

    38.What is concurrent rendering at a high level?

    React may start, pause, abandon, or reuse render work. Keep render pure (no side effects). Use startTransition for non-urgent updates so typing stays responsive.

  39. javascript

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

    IEEE-754 doubles cannot represent many decimals exactly. For money, use integer cents or a decimal library—not raw floats for equality.

  40. react

    40.What is useTransition used for?

    It marks state updates as non-urgent so React can keep the UI responsive for urgent input. Pair with isPending for loading affordances on deferred UI.

  41. javascript

    41.What is the difference between null and undefined?

    undefined usually means “missing or not initialized.” null is an intentional empty value. Pick one convention for APIs and stick to it; prefer ?? over || when 0 and empty string are valid.

  42. react

    42.What causes hydration mismatches?

    Server HTML must match the client’s first render. Random IDs, Date.now(), locale-dependent formatting, or browser-only APIs during render cause mismatches. Guard client-only UI.

  43. javascript

    43.What are ES modules and how do they differ from classic scripts?

    Modules have their own scope, use import/export, are deferred by default, and run in strict mode. Classic scripts share the global scope and can block parsing without defer/async.

  44. react

    44.What are Server Components conceptually?

    Components that can render on the server by default in modern frameworks, shipping less client JS for non-interactive UI. Client components mark interactivity boundaries—“use client” should stay as low as practical.

  45. javascript

    45.What does dynamic import() enable?

    import() returns a Promise of the module namespace, so you can load code on demand (route-based splitting, rarely used features). Handle errors and loading UI.

  46. react

    46.Why can changing a key remount a component?

    React treats a different key as a different identity—state resets and effects re-run. Useful to reset forms when the entity ID changes; harmful when keys thrash accidentally.

  47. javascript

    47.What is the difference between for...of and for...in?

    for...of iterates values of iterables (arrays, strings, maps). for...in enumerates enumerable keys, including inherited ones—risky for arrays. Prefer for...of, map, or forEach for arrays.

  48. react

    48.What is derived state and why is it often an anti-pattern?

    Copying props into state without a clear reset strategy desyncs UI from props. Prefer computing during render, or fully control from the parent, or remount with a key when identity changes.

  49. javascript

    49.How does Array.prototype.sort work by default?

    It sorts as strings by default, so [10, 2, 1] becomes [1, 10, 2]. Always pass a comparator for numbers: (a, b) => a - b. Prefer toSorted when you need a copy.

  50. react

    50.How do portals help with modals?

    createPortal renders children into a different DOM node (e.g. document body) while keeping React context. Useful for stacking/overflow, but you still own focus trap and a11y.

Related lists

All interview question lists · Interview hub · Learn