Frontend Developer Interview Questions with Answers
The questions cover the language, the browser and user interfaces. Check the explanations on small examples and connect them to real tasks: loading data, forms, accessibility and maintaining an application.
A modern browser, Node.js 22 for the language examples, React 19. The TypeScript version is pinned by the project's test environment.
Questions and answers
Junior: fundamentals
JavaScriptHow is const different from let?
Both declarations are block-scoped. const forbids rebinding the variable, but it does not make an object deeply immutable: properties and array elements can still change. let is used when reassignment is part of the algorithm. It is also important to understand the temporal dead zone: such a variable cannot be accessed before its declaration runs. Choosing const by default reduces the number of changing bindings, but it does not replace designing the state.
- Example
- You can call items.push(1) on const items = [], but you cannot then assign another array to items.
- Common mistake
- Treating const as a guarantee that all of an object's data is immutable.
- Interviewer follow-up
- How do you forbid or control changes to nested objects?
JavaScriptWhy is === usually used?
Strict equality does not coerce different types according to the rules of loose comparison. This makes a condition clearer, especially when handling user input. Objects, however, are compared by identity, and NaN is not equal to itself with ===. For special cases there is Object.is, which behaves differently for NaN and signed zero. Comparing structured data requires semantics you choose separately.
- Example
- The string '0' and the number 0 are not equal with ===; two objects with the same fields do not become equal automatically either.
- Common mistake
- Using JSON.stringify as a universal equality check for any objects.
- Interviewer follow-up
- When is comparing objects by reference useful in React?
JavaScriptWhat is a closure?
A function keeps access to the lexical environment of the place where it was created. This lets you build handlers, factories and private state. A closure keeps access to variables, not necessarily a snapshot of all their values. In UI this matters for asynchronous handlers: code may work with the state of a specific render or with a mutable ref. To understand the behavior, determine when the function was created and which environment it refers to.
- Example
- A counter factory can return a function that increments a local variable between calls.
- Common mistake
- Expecting any deferred function to automatically see the latest React state.
- Interviewer follow-up
- How does a functional state update help you avoid a stale value?
JavaScriptHow is map different from forEach?
map creates an array of transformation results, while forEach performs an action for each element and does not collect the returned values. If the result of the transformation is needed later, map expresses that intent explicitly. For side effects, a loop or forEach is usually clearer. Do not confuse map with waiting for asynchronous operations: an array of promises is not an array of ready results. Order and error handling must be defined separately.
- Example
- items.map(load) returns promises; await Promise.all(...) waits for them together.
- Common mistake
- Writing await items.forEach(async ...) and assuming all operations have finished.
- Interviewer follow-up
- When is a sequential for...of preferable to Promise.all?
HTMLWhy use semantic elements if everything can be built with div?
A semantic element tells the browser and assistive technologies what a block is for and often provides built-in behavior. button supports keyboard activation and states, a with href denotes navigation, and headings form the document structure. Using div means reproducing these contracts by hand, which easily leads to an incomplete interface. Semantics also let you test a page by roles instead of arbitrary CSS classes.
- Example
- details and summary fit revealing additional information, as long as their behavior matches the task.
- Common mistake
- Adding a click handler to a div and forgetting about the keyboard and the accessible name.
- Interviewer follow-up
- When should a control be a button, and when a link?
CSSWhen do you choose Flexbox, and when Grid?
Flexbox conveniently distributes items mostly along one axis, while Grid describes the rows and columns of a shared grid. This is a guideline, not a ban on wrapping lines in flex. For a card with an icon and text, flex is often enough; for consistent panel columns, grid is convenient. Whatever you choose, check the minimum content size, the wrapping of long lines and the behavior on a narrow screen.
- Example
- A wide pre inside a grid may need min-width: 0 on the grid item and separate scrolling for the code.
- Common mistake
- Fixing the width of every column in pixels and hiding the overflow of the whole page.
- Interviewer follow-up
- Why does content in flex sometimes refuse to shrink even though there is free space?
HTTPHow is an HTTP status different from a fetch error?
fetch usually returns a Response even for HTTP errors such as 404 or 500; the code must check ok or status. The promise is rejected on some network errors and on abort, but that does not replace checking the application response. The body format is also part of the contract: the server may return HTML instead of the expected JSON. So it helps to separate a transport error, an HTTP failure, a parsing error and business validation.
- Example
- Before response.json() you can check response.ok and the expected Content-Type.
- Common mistake
- Treating a resolved fetch as proof that the server operation succeeded.
- Interviewer follow-up
- How do you show the user a field error separately from the service being unavailable?
ReactHow are props different from state?
Props are passed to a component from outside, while state belongs to a specific component instance. Both should be treated as a snapshot of the current render and never mutated directly. If a value is computed from props and state, it often does not need to be stored in yet another state: otherwise you get two sources that drift apart. When several components depend on the same state, it is lifted to a suitable common owner.
- Example
- A filtered list can be computed from the source list and the search string.
- Common mistake
- Copying every prop into state and syncing it with an extra effect.
- Interviewer follow-up
- When is it justified for local input state to differ from the saved data?
Middle: putting them into practice
JavaScriptHow are tasks and microtasks related?
JavaScript runs the current work to completion; after that, the environment processes the microtask queue before moving on to the next task. Promise callbacks usually go to the microtask queue, and timers to the task queue. The exact timing of rendering depends on the browser, so a zero-delay timer cannot be considered instant. A long synchronous section blocks the handling of input. Creating microtasks endlessly can also block further work.
- Example
- After synchronous console.log calls, the handler of a resolved promise usually runs before setTimeout(..., 0).
- Common mistake
- Assuming an async function immediately runs in a separate thread.
- Interviewer follow-up
- How do you offload long computations while keeping the interface responsive?
TypeScriptHow is narrowing different from a type assertion?
Narrowing refines a type based on checks the analyzer understands: typeof, the presence of a property, a discriminant or a correct type guard. An as assertion tells the compiler the author's opinion but does not check the data at runtime. External JSON needs runtime parsing. A good discriminated union lets you handle the loading, success and error states explicitly instead of carrying a set of contradictory flags.
- Example
- For an object { kind: 'success', data }, the data field is available after checking kind.
- Common mistake
- Writing payload as User and assuming the server data has been validated.
- Interviewer follow-up
- How do you check that every variant of a union is handled?
ReactWhen do you need useEffect?
An effect synchronizes a component with an external system: a subscription, a timer, a third-party widget or network interaction. Computing a value from props you already have usually belongs in rendering, and a user action belongs in an event handler. An effect's dependencies must match the reactive values it reads. Cleanup cancels a subscription or undoes the consequences of the previous synchronization. In development, the extra calls in Strict Mode help detect asymmetric setup.
- Example
- An event subscription is added in an effect and removed by its cleanup function.
- Common mistake
- Disabling the dependency check to hide the effect running again.
- Interviewer follow-up
- How do you make an effect resilient to setup → cleanup → setup?
ReactWhy shouldn't key be random?
key helps React match a list item with the previous item among its siblings. A stable ID keeps state attached where you expect it. A random key on every render forces the elements to be recreated. An index is acceptable only in limited situations, when the order and composition do not change in a way that moves state to another object. An editable or sortable list usually needs an ID from the data.
- Example
- After the tasks are sorted, an input field must stay tied to the same task, not to its former position.
- Common mistake
- Using Math.random() to make the warning go away.
- Interviewer follow-up
- How can key be used deliberately to reset state?
NetworkHow do you avoid showing a stale search response?
When the query changes quickly, responses can arrive out of order. You need to cancel the previous operation if the transport supports it, and separately guard applying the result with the ID of the current request. Cancellation saves resources, while the freshness check protects the state even where cancellation did not work. An abort error is usually not shown as a service failure. Loading and error states must also refer to the current operation.
- Example
- The search result for “py” must not overwrite the result for “python” that is already on screen.
- Common mistake
- Treating debounce as sufficient protection against any reordering of responses.
- Interviewer follow-up
- How do you test a race with a deterministic test?
AccessibilityWhat should you check in a dialog?
A dialog must have an accessible name, a clear way to close it and managed focus. When it opens, focus moves inside in a suitable way, and after it closes, focus returns to the element that opened it, if that element still exists. In modal mode, the background must not remain accidentally available for interaction. Check the keyboard, Escape, how the heading is announced and scrolling on a small screen. ARIA attributes do not replace actual behavior.
- Example
- A keyboard user can open the dialog, perform an action and return to the original button.
- Common mistake
- Adding role='dialog' while leaving focus outside the window.
- Interviewer follow-up
- When is a non-modal block preferable to a dialog?
PerformanceHow do images affect LCP and CLS?
A large image in the first screen can become the LCP element, so its size, format and timely loading matter. Set aspect ratios or dimensions reserve space and reduce layout shifts. Lazy loading is useful for images below the fold, but it can delay the key image of the first screen. Responsive variants let you avoid sending an oversized image to a phone. The decision is verified by measurement, not just by the presence of the loading attribute.
- Example
- Cards below the fold load lazily, while the hero image gets a suitable size and a reserved area.
- Common mistake
- Enabling lazy loading for every image and calling the optimization done.
- Interviewer follow-up
- How do you tell a delay in loading a resource from a delay in rendering it?
TestingHow do you test a component without tying the test to markup?
Start with accessible behavior: find an element by role and name, perform an action and check the visible result. CSS classes and the tree of internal components change more often than the contract with the user. Asynchronous changes should be awaited by observable state, not by a fixed sleep. A component unit test does not replace a browser check of layout, focus and real network interaction. Different test levels should cover different risks.
- Example
- Find the “Save” button, click it and wait for the message that the data has been saved.
- Common mistake
- Checking private state instead of what the user sees.
- Interviewer follow-up
- What does jsdom not prove about the behavior of a real browser?
Senior: trade-offs and reliability
ArchitectureHow do you choose the boundary between server and client UI?
The server is convenient for fetching data and producing the initial HTML, while the client is needed for interaction with browser state. The boundary affects the amount of JavaScript and which data gets serialized to the outside. Secrets and internal objects must not end up in a client component's props. A large client shell can quietly pull extra dependencies into the bundle. It helps to start with a minimal interactive island around a specific action.
- Example
- The article text is rendered by the server, while the copy-code button works in a small client component.
- Common mistake
- Marking the whole page with use client just for one button.
- Interviewer follow-up
- How do you check which dependencies ended up in the client bundle?
DataWhat matters when you cache data in the interface?
You need to define the key, the lifetime, the conditions for refreshing and the acceptable staleness. A cache of authorized data must take the user into account or be isolated from the shared cache. After a mutation, exactly the dependent views must be refreshed, otherwise the user sees lists and cards that contradict each other. A loading error does not always mean the old data should be wiped. For SEO pages it is especially important to keep the published content, navigation and the sitemap consistent.
- Example
- After an article is unpublished, it must disappear both from the list and from the public route.
- Common mistake
- Caching a personal response under a shared URL key.
- Interviewer follow-up
- How do you combine an optimistic update with a rejection from the server?
SecurityWhy doesn't HTML escaping solve every UI risk?
Escaping text prevents data from being interpreted as markup, but other contexts remain: URLs, CSS, inserted HTML and messages between windows. For links you need to restrict the allowed schemes, for rich text the allowed nodes, and for postMessage the origin and structure. Data from a CMS or an external API also counts as input. Protection must match the place where data is used, not the name of its source.
- Example
- Plain text is safer rendered as text; inserting HTML requires separate handling of the allowed content.
- Common mistake
- Treating any authorized editor as a reason to allow an arbitrary script.
- Interviewer follow-up
- How is protection against XSS different from protection against CSRF?
PerformanceHow do you investigate a slow interaction?
Pick a specific action and measure it in the browser profiler on a device similar to your users'. Separate the handler, computation, React rendering, layout, paint and waiting for the network. Memoization helps only when it addresses the actual cause, and it has a cost of its own. Long work can be split up or moved to a worker; extra updates can be reduced by changing state boundaries. The result is verified by measuring the same scenario again, including errors and a slow network.
- Example
- Heavy filtering on every keystroke may require changing the algorithm, not wrapping every component in useMemo.
- Common mistake
- Optimizing by the number of renders without measuring time and the effect on the user.
- Interviewer follow-up
- What accessibility risk does virtualizing a long list add?
Practical tasks
1. Group without mutating the input
Group records by the string field role, keeping the order within each group. Handle the __proto__ key correctly.
Expected result. Two python records stay in their original order; an empty input gives an empty result.
Solution and explanation
Map does not use user-supplied keys as prototype properties. We create new arrays without changing the original list.
export function groupByRole(items) {
const result = new Map();
for (const item of items) {
const group = result.get(item.role) ?? [];
group.push(item);
result.set(item.role, group);
}
return result;
}2. Apply only the latest result
Create a search controller that cancels the previous load and ignores its late response.
Expected result. If the second request finishes before the first one, the UI keeps the second result; cancellation is not shown as an error.
Solution and explanation
AbortController saves work, and the run number protects against a transport that ignored the signal. load takes the query and the signal; apply and onError are the functions that update the UI.
export function createSearch(load, apply, onError) {
let version = 0;
let controller;
return async (query) => {
const current = ++version;
controller?.abort();
controller = new AbortController();
try {
const result = await load(query, controller.signal);
if (current === version) apply(result);
} catch (error) {
if (current === version && error?.name !== 'AbortError') onError(error);
}
};
}3. An accessible answer disclosure
Create a React 19 component with a question and an expandable answer. It must work from the keyboard, and its text must be in the server HTML.
Expected result. Summary receives focus; Enter or Space toggles the disclosure; the answer is in the document before any interaction.
Solution and explanation
Native details/summary provide the needed behavior without a custom key handler or hidden network loading. Do not put extra conflicting buttons inside summary.
export function Answer({ question, children }) {
return (
<details>
<summary>{question}</summary>
<div>{children}</div>
</details>
);
}Seven-day preparation plan
- Write down the job requirements and mark the topics you know and the ones you don't.
- Answer the Junior questions out loud, then check yourself against the explanations.
- Work through the Middle questions. For every mistake, write a small example of your own.
- Solve the practical tasks without hints and check the edge cases.
- Work through the Senior questions and explain the trade-offs as they apply to your project.
- Run a mock interview: clarify the conditions, reason out loud and check your conclusions.
- Go over your mistakes, prepare real stories from your experience and check your equipment.