Interview questions
Top 100 Frontend Interview Questions (with answers)
Revision list of 100 frontend 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.
- 100 questions
- javascript
- react
- html
- css
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.
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.
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.
html
3.What is semantic HTML and why does it matter?
Use elements that match meaning (nav, main, button, label) so browsers, assistive tech, and crawlers understand structure. CSS can fake appearance; it cannot replace missing semantics without extra ARIA and keyboard work.
css
4.What is the CSS box model?
Every box has content, padding, border, and margin. With content-box, width applies to content only; with border-box, width includes padding and border. Most layout systems set border-box globally.
javascript
5.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.
react
6.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.
html
7.When should you use a link versus a button?
Links navigate with href (open in new tab, bookmarkable, crawlable). Buttons perform actions on the page. Do not fake either with divs unless you reimplement keyboard and accessibility fully.
css
8.What is the difference between content-box and border-box?
content-box: specified width/height size the content area; padding and border add outside. border-box: specified width/height include content, padding, and border—usually easier for column math and components.
javascript
9.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.
react
10.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.
html
11.Why should a page have a single main landmark?
main identifies primary content and should appear once. It enables skip links and AT landmark navigation. Header/nav/footer sit outside main.
css
12.When do you use Flexbox versus Grid?
Flexbox is strong for one-dimensional distribution (rows or columns of components). Grid is strong for two-dimensional page/section layouts. Real UIs often combine both.
javascript
13.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.
react
14.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.
html
15.How do you correctly label form controls?
Associate a label via for/id or wrap the control. Placeholder is a hint, not a label. Unlabeled inputs fail accessibility and often fail Testing Library role queries.
css
16.What do flex-grow, flex-shrink, and flex-basis do?
flex-basis is the initial main size before free space is distributed. flex-grow shares positive free space. flex-shrink reduces items when space is tight. Defaults matter—know flex: 1 shorthand implications.
javascript
17.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.
react
18.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.
html
19.What are the rules of thumb for img alt text?
Informative images need meaningful alt. Decorative images use empty alt (alt=""). Do not stuff keywords. Provide width/height or CSS aspect-ratio to limit CLS.
css
20.What is the difference between align-items and justify-content in Flexbox?
justify-content distributes along the main axis; align-items aligns on the cross axis. Direction depends on flex-direction. Interviewers often swap axis names—draw it.
javascript
21.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.
react
22.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.
html
23.What is the difference between section, article, and div?
div is generic styling/hook with no semantics. section is a thematic grouping with a heading. article is self-contained content that could stand alone (post, card widget).
css
24.What is the fr unit in CSS Grid?
fr represents a fraction of available free space in the grid container. repeat(3, 1fr) builds equal columns after accounting for gaps and fixed tracks.
javascript
25.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.
react
26.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.
html
27.How should heading levels be structured?
Use logical h1–h6 order that reflects the outline. Do not skip levels just for visual size—style with CSS. Headings are navigation landmarks for screen-reader users.
css
28.What is the difference between auto-fit and auto-fill?
Both create as many tracks as fit. auto-fit collapses empty tracks so items can expand; auto-fill keeps empty track slots. Used with minmax for responsive grids without many breakpoints.
javascript
29.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.
react
30.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.
html
31.What is the accessibility tree?
A structure derived from the DOM, plus ARIA, that assistive technologies use. Broken semantics produce a poor accessibility tree even if the page “looks fine.”
css
32.How does position: sticky work?
The element acts relatively until a scroll threshold, then sticks within its containing block. Overflow hidden/auto on ancestors is a common reason sticky “fails.”
javascript
33.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.
react
34.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.
html
35.What do native HTML5 input types buy you?
Types like email, tel, url, number improve mobile keyboards and basic validation. They are progressive enhancement—not a substitute for server validation.
css
36.What is a stacking context?
A local stacking order for z-index. Properties like opacity < 1, transforms, filters, and positioned elements with z-index can create new contexts—so z-index only competes inside that context.
javascript
37.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.
react
38.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.
html
39.What is the purpose of fieldset and legend?
They group related controls (especially radio sets) and provide an accessible group name. Useful for screen-reader context on multi-control questions.
css
40.How does CSS specificity work?
Roughly: inline styles > IDs > classes/attributes/pseudo-classes > elements. Equal specificity falls to source order. Cascade layers can override raw specificity between layers.
javascript
41.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.
react
42.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.
html
43.When are HTML tables appropriate?
For tabular data with headers—not for page layout. Use th, scope or headers/id associations so assistive tech announces relationships.
css
44.What are cascade layers (@layer) for?
They let you order groups of styles (reset, base, components, utilities) so later layers win without escalating selector weight. Important rules reverse layer order—know that twist.
javascript
45.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.
react
46.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.
html
47.What are srcset and the picture element for?
srcset/sizes let the browser pick among candidates by density/width. picture adds art direction (different crops by media query). Do not lazy-load the LCP image.
css
48.What are CSS custom properties good for?
Tokens for color, space, and type that cascade and can change at runtime (theming). They are live in the cascade—unlike preprocessors variables that compile away.
javascript
49.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.
react
50.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.
html
51.How does the dialog element help accessibility?
Native dialog with showModal uses the top layer, handles Escape more sanely, and reduces custom modal bugs. You still manage focus return and labeled titles.
css
52.What is the difference between em and rem?
em is relative to the element’s computed font-size (and can compound). rem is relative to the root font-size—usually safer for spacing scales.
javascript
53.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); }; }react
54.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.
html
55.What is a skip link?
A first focusable link that jumps to main content so keyboard users can bypass repetitive nav. It should become visible on focus.
css
56.Why can 100vh be problematic on mobile?
Mobile browser chrome can make classic vh units jump. Prefer dvh/svh/lvh where supported, and test real devices for full-height layouts.
javascript
57.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).
react
58.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.
html
59.Why set the lang attribute on html?
It declares the document language for assistive tech pronunciation, hyphenation, and translation tools. Wrong lang harms accessibility.
css
60.What are container queries?
They let components respond to their container’s size rather than only the viewport—better for reusable cards in sidebars vs main columns.
javascript
61.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.
react
62.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.
html
63.What meta tags matter for SEO and sharing?
Unique title, meta description, canonical URL, and Open Graph/Twitter tags for previews. Structured data (JSON-LD) helps machines understand page type.
css
64.How does clamp() help fluid typography?
clamp(min, preferred, max) sets a responsive value that won’t go below min or above max—common for type and spacing without many breakpoints.
javascript
65.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.
react
66.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.
html
67.What is the difference between readonly and disabled on inputs?
readonly keeps the field focusable and typically still submits its value. disabled prevents interaction and excludes the value from submit. Pick based on UX and form data needs.
css
68.Why animate transform and opacity instead of top/left/width?
transform/opacity are more often compositor-friendly and avoid layout thrash. Changing geometry properties frequently triggers layout and paint more expensively.
javascript
69.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.
react
70.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.
html
71.What does autocomplete help with?
Hints browsers and password managers about the field’s meaning (email, current-password, etc.). Correct tokens improve checkout and login UX.
css
72.What is :focus-visible and why use it?
It styles focus for keyboard (and some other) modalities without forcing a ring on every mouse click. Never remove focus outlines without an accessible replacement.
javascript
73.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.
react
74.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.
html
75.What is progressive enhancement in HTML terms?
Core content and critical actions work with basic HTML; CSS/JS enhance. Avoid trapping essential text only inside client-rendered bundles when SEO/a11y matter.
css
76.What is the difference between :is() and :where()?
Both group selectors. :where() always contributes zero specificity; :is() takes the specificity of its most specific argument—easy footgun with IDs inside :is().
javascript
77.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.
react
78.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.
html
79.When is ARIA necessary versus harmful?
Prefer native elements first. ARIA can expose roles/states for custom widgets but wrong ARIA is worse than none. Follow ARIA Authoring Practices for patterns.
css
80.What does the :has() selector enable?
Selecting a parent based on descendants/state (e.g. form:has(:invalid)). Powerful; use carefully for performance and complexity.
javascript
81.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.
react
82.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.
html
83.What does the sandbox attribute on iframes do?
It restricts iframe capabilities (scripts, forms, top-navigation, etc.) to reduce risk from third-party or untrusted content. Open only the permissions you need.
css
84.How do you reduce layout shift from images and embeds?
Reserve space with width/height or aspect-ratio, avoid inserting banners above content without reserved space, and be careful with web font swaps.
javascript
85.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.
react
86.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.
html
87.What is the template element used for?
It holds inert DOM that is not rendered until cloned. Useful for client-side rendering patterns and Web Components.
css
88.What is prefers-reduced-motion for?
A user preference to minimize non-essential motion. Respect it by shortening or disabling decorative animations—important for vestibular accessibility.
javascript
89.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.
react
90.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.
html
91.Why can contenteditable be problematic?
Editing behavior is inconsistent across browsers, and raw HTML output is an XSS risk. Prefer established editor libraries for production rich text.
css
92.How do you implement dark mode thoughtfully?
Use tokens with prefers-color-scheme and/or a class strategy, ensure contrast, and avoid relying on color alone for state. Test form controls and shadows in both themes.
javascript
93.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.
react
94.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.
html
95.What is the difference between strong/em and b/i?
strong/em convey importance/emphasis semantics. b/i are primarily presentational without that emphasis meaning. Prefer semantic tags when meaning matters.
css
96.What is BFC (block formatting context) in practical terms?
A layout region that contains floats and prevents margin collapse in certain cases. Triggers include overflow values, flex/grid items, etc. Useful vocabulary for older float bugs.
javascript
97.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.
react
98.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.
html
99.How do you mark up a navigation region accessibly?
Use nav, and if there are multiple navs, label them (aria-label). Current page links can use aria-current="page". Keep lists of links structured.
css
100.Why might z-index appear to “not work”?
The element may not be positioned, or a parent stacking context isolates it. Fix the stacking context structure rather than inventing huge z-index numbers.