Practice exam
For each question, think first or write your answer. Then open the answer and mark yourself honestly. The result stays only in your browser.
/ 32
1. A div used as a button
Question: On the product page of our online shop, the “Add to cart” control is written like this:
<div class="add-to-cart" onclick="addToCart(42)">
Add to cart
</div>
.add-to-cart {
padding: 12px 24px;
background: #0a7d32;
color: white;
cursor: pointer;
}
It looks like a button, and it works with the mouse. You see this in code review. What do you think? Is there a problem?
Short answer: It is a div, not a real button. A div cannot get keyboard focus, it does not react to Enter or Space, and screen readers do not announce it as a button. So people who use a keyboard or a screen reader cannot add products to the cart. The fix is the button tag, which gives all of this for free.
Hint (if the candidate says there is no problem): A user who cannot use a mouse presses Tab on the product page. The focus jumps over “Add to cart”. A blind user with a screen reader hears only the text “Add to cart”. Nothing tells them it can be pressed. Why?
Why does this happen? (step by step)
- A div is a generic box. It has no meaning and no role.
- The browser puts only interactive elements (links, buttons, form fields) in the Tab order. A div is not one of them, so the keyboard never reaches it.
- The onclick handler runs on a mouse click or a tap. A real button also fires the click event when you press Enter or Space. A div does not.
- Screen readers read each element’s role from the accessibility tree. The div has no button role there, so the user does not know it is a control.
- Mouse users never notice any of this. That is why the bug passes a quick manual test.
The fix:
<button type="button" class="add-to-cart" data-product-id="42">
Add to cart
</button>
document.querySelector('.add-to-cart').addEventListener('click', (event) => {
addToCart(Number(event.currentTarget.dataset.productId));
});
- The button tag is in the Tab order by default.
- Enter and Space fire the click event, so one click handler covers mouse, touch and keyboard.
- Screen readers say something like “Add to cart, button”.
- It supports the disabled attribute, for example when the product is out of stock.
- The type=“button” attribute matters inside a form. There the default type is submit, so a click would submit the form.
- The cost: the browser adds default button styles. Reset them in CSS (border, font, and so on). Keep a clear focus style, for example with the :focus-visible selector, so keyboard users can see where they are.
Follow-up question: Can we keep the div and just add role=“button”?
Follow-up answer:
- The role only changes what the screen reader announces. It adds no behavior.
- You also need tabindex=“0” to make it focusable, and a keydown handler for Enter and Space.
- You must build the disabled state yourself (for example with aria-disabled) and add focus styles.
- That is a lot of code that copies what the button tag already does, and it is easy to get wrong. The first rule of ARIA says: if a native HTML element already does the job, use it instead of ARIA.
Red flag: Says “It works, I clicked it”, and tests only with the mouse. Or adds only role=“button” and thinks keyboard support comes with it.
2. A checkout form without labels
Question: This is the checkout form of our online shop. Most users buy on their phones.
<form id="checkout">
<input type="text" placeholder="Full name">
<input type="text" placeholder="Email">
<input type="text" placeholder="Phone">
</form>
<button onclick="submitCheckout()">Pay</button>
function submitCheckout() {
const inputs = document.querySelectorAll('#checkout input');
sendOrder({
name: inputs[0].value,
email: inputs[1].value,
phone: inputs[2].value,
});
}
You see this in code review. What do you think? Is there a problem?
Short answer: There are several problems. The fields have no label, only a placeholder. The placeholder disappears when you type, and it is not a reliable name for screen readers. The Pay button is outside the form and is not a submit button, so pressing Enter does nothing, and the browser cannot validate the form. All fields are type=“text”, so the phone shows the wrong keyboard and autofill does not help. The fix is real labels, the right input types, name and autocomplete attributes, and a submit button inside the form.
Hint (if the candidate says there is no problem): A user types the email, then presses Enter. Nothing happens. A screen reader user moves to the second field and is not sure what it asks for. On the phone, the email field shows a keyboard without the @ key on the first screen. Autofill does not fill the fields. Why?
Why does this happen? (step by step)
- A placeholder is a hint, not a label. It disappears as soon as the user types. The user cannot check later what a field was for.
- Placeholder text is usually light gray, so it is hard to read. Screen reader support for it as a name is not reliable.
- The label tag connects text to a field. Screen readers read it, and a click on the label moves focus to the field, which gives a bigger tap target on phones.
- Enter submits a form only in some cases. This form has no submit button and has more than one text field, so the browser does not submit it when you press Enter.
- The button is outside the form and only runs a click handler. The form never fires a submit event, so the required attribute and the email check of the browser never run.
- Every field is type=“text” and has no name or autocomplete. So the phone shows the normal keyboard, and autofill has to guess what to put in each field. The script also depends on the order of the inputs, which breaks when someone adds a field.
The fix:
<form id="checkout">
<label for="name">Full name</label>
<input id="name" name="name" autocomplete="name" required>
<label for="email">Email</label>
<input id="email" name="email" type="email" autocomplete="email" required>
<label for="phone">Phone</label>
<input id="phone" name="phone" type="tel" autocomplete="tel">
<button type="submit">Pay</button>
</form>
const form = document.querySelector('#checkout');
form.addEventListener('submit', (event) => {
event.preventDefault(); // we send it with JavaScript
const data = Object.fromEntries(new FormData(form));
sendOrder(data);
});
- Each field has a visible label, linked with the for and id attributes.
- The submit button is inside the form. Enter works, and a click works.
- Before the submit event, the browser checks required and type=“email”. If a field is wrong, it shows a message and does not submit.
- The type=“email” and type=“tel” attributes give the right keyboard on phones.
- The autocomplete attribute lets the browser fill name, email and phone.
- The name attribute puts each value into FormData, so the script does not depend on the order of the fields.
- If the design needs the button outside the form, give it type=“submit” and form=“checkout”. Then a click still submits that form.
- The trade-off: visible labels take more space on a small screen. That is a fair price, because the form is easier and faster to fill.
Follow-up question: The designer wants no visible labels, only placeholders, “to keep it clean”. What do you do?
Follow-up answer:
- Explain the cost: the hint disappears while typing, the gray text has low contrast, and users make more mistakes.
- Offer a middle way, for example a label that sits inside the field and moves above it when the field gets focus (“floating label”). The label stays visible all the time.
- If the label must be hidden, keep a real label tag in the HTML and hide it only visually with a “visually hidden” CSS class. Screen readers still read it. The aria-label attribute also gives a name, but sighted users still lose the hint.
- A visible label is the best choice for everyone, not only for people with disabilities.
Red flag: Thinks the placeholder is enough as a label. Or does not know that a button outside the form, without the form attribute, does not submit it.
3. Product images without size and alt
Question: This is one card in the product list of our online shop. A page shows 24 cards. Many users are on phones with a slow mobile network.
<article class="product-card">
<img src="/images/shoe-42.jpg">
<h3>Running shoes</h3>
<p class="price">$89</p>
<button type="button">Add to cart</button>
</article>
.product-card img {
width: 100%;
}
You see this in code review. What do you think? Is there a problem?
Short answer: The image has no width and height attributes. Until the image file arrives, the browser does not know how tall it is, so it gives it no space. When the image loads, everything below it jumps down. This hurts the CLS metric (Cumulative Layout Shift). The image also has no alt attribute, so screen reader users do not know what the product looks like, and some screen readers read the file name instead. The fix is to add width, height and alt, and keep height: auto in CSS.
Hint (if the candidate says there is no problem): On a slow phone, the user wants to tap “Add to cart”. Just then an image above loads, the button moves down, and the user taps another product by mistake. PageSpeed Insights shows a poor CLS score for this page. A screen reader reads “shoe-42.jpg”. Why?
Why does this happen? (step by step)
- The browser builds the layout before the images download.
- Without width and height, the browser does not know the image’s aspect ratio. It reserves a height of zero.
- The title, price and button are drawn right under that empty space.
- When the image arrives, the browser now knows its real height. It moves everything below it down. This is a layout shift.
- With 24 cards loading at different times, the page jumps many times. CLS adds these shifts up. A good CLS is 0.1 or less.
- The alt attribute is the text alternative of the image. Without it, a screen reader has no description. It is also the text shown if the image fails to load.
The fix:
<article class="product-card">
<img
src="/images/shoe-42.jpg"
width="600"
height="600"
alt="Blue running shoes, side view"
loading="lazy">
<h3>Running shoes</h3>
<p class="price">$89</p>
<button type="button">Add to cart</button>
</article>
.product-card img {
width: 100%;
height: auto;
}
- The width and height attributes give the aspect ratio (here 1 to 1). Modern browsers use them to reserve the right space before the image arrives.
- In CSS, width: 100% and height: auto keep the image responsive. The ratio from the attributes still applies, so the image does not stretch.
- The alt text describes the product shortly. Do not start it with “Image of”; the screen reader already says it is an image.
- A purely decorative image gets an empty alt (alt=“”). Then screen readers skip it. Do not leave alt out completely.
- The loading=“lazy” attribute delays images that are far below the screen. It saves data on slow networks. Do not use it on images in the first screen (for example the first row of products), because one of them is often the LCP element (Largest Contentful Paint), which must load right away.
- The trade-off: we must know the image size in advance. Usually the image service or the CMS stores it, or all product images use the same ratio.
Follow-up question: Sellers upload product photos in different shapes: some square, some wide. We want every card image to have the same size, and the page must not jump. What do you do?
Follow-up answer:
- Give the image a fixed ratio with the aspect-ratio property in CSS, for example 1 to 1. Now every card keeps the right space, even before the photo arrives.
- The object-fit property with the value cover scales the photo until it fills the whole box, and cuts off the extra edges. The value contain shows the whole photo and leaves empty space.
.product-card img {
width: 100%;
height: auto;
aspect-ratio: 1 / 1;
object-fit: cover;
}
- The trade-off: cover can cut off an important part of the photo, and contain leaves empty bands. Another option is to let the image service crop all photos to one ratio in advance.
Red flag: Says “The images load fast on my computer, so there is no problem”, and tests only on a fast network. Or thinks alt is only for SEO.
4. The !important war
Question: Our online shop has a growing CSS codebase. Three people changed the product price style over the last months. Today the stylesheet has this:
/* components/product-card.css */
.product-card .price {
color: #222;
}
/* pages/sale.css */
#shop .product-list .product-card .price {
color: #c00 !important;
}
/* pages/product.css */
body #shop div.product-card span.price {
color: #222 !important;
font-size: 1.25rem !important;
}
A new ticket says: “On the sale page, make the price of out-of-stock products gray.” You see this in code review. What do you think? Is there a problem?
Short answer: The team is fighting the cascade. Each person used a longer selector or !important to beat the rule before. Now nobody can predict which rule wins without counting specificity, and every new change needs an even stronger selector. The fix is to keep specificity low and flat (one class per rule), use modifier classes for variants, and control the order with cascade layers (@layer) instead of !important.
Hint (if the candidate says there is no problem): The developer adds .out-of-stock .price with color gray. Nothing changes. Then they try an ID, then !important, and the price on the product page breaks. Why is a simple color change so hard?
Why does this happen? (step by step)
- When two rules set the same property, the browser first looks at importance. A declaration with !important beats every normal declaration.
- If both are important (or both are normal), it compares specificity. Specificity counts IDs first, then classes, attributes and pseudo-classes, then element names.
- The first rule has two classes. The sale rule has one ID and three classes. The product page rule has one ID, two classes and three element names. Who wins depends on this counting.
- Only when specificity is equal does the order in the file decide: the later rule wins.
- So the new .out-of-stock .price rule (two classes, not important) loses to both important rules. To win, it must be important and have even higher specificity.
- Each fix makes the next fix harder. Long selectors are also fragile: if someone changes div to section in the HTML, the product page rule stops matching.
The fix:
/* Order of layers: later layers win, whatever the specificity. */
@layer base, components, pages;
@layer components {
.price {
color: #222;
}
.price--sale {
color: #c00;
}
.price--out-of-stock {
color: #888;
}
}
@layer pages {
.product-page .price {
font-size: 1.25rem;
}
}
<p class="price price--sale price--out-of-stock">$89</p>
- Each rule uses one or two classes. The specificity stays low and almost the same everywhere.
- Variants are modifier classes. When specificity is equal, the later rule wins, so out-of-stock (written last) beats sale.
- Cascade layers set the order between groups of styles. A normal rule in the pages layer beats a normal rule in the components layer, even if its selector is weaker.
- Base styles can use the :where() pseudo-class. It has zero specificity, so any other rule can override it.
- No !important is needed. Keep it for rare cases, for example a utility class that must always win, or overriding inline styles you cannot change.
- The trade-off: this cleanup touches many files and needs a visual check of the pages. Do it step by step: first stop adding new !important rules, then move old ones.
Follow-up question: A third-party date picker library brings its own CSS with strong selectors. How do you override it without !important?
Follow-up answer:
- First declare the layer order once. Then import the library’s CSS into the first layer, vendor:
@layer vendor, base, components, pages;
@import url("datepicker.css") layer(vendor);
- Now your normal rules in later layers win over the library’s normal rules, even if the library uses IDs.
- Be careful: for !important declarations the layer order is reversed. An important rule in an earlier layer beats an important rule in a later layer. So if the library uses !important, it will still win.
- Also note: styles that are not in any layer beat all layered normal styles.
Red flag: Says “Just add !important” or “Add an ID to the selector”. Or cannot explain how the browser decides which rule wins.
5. A flex row that does not shrink
Question: This is one row in the cart of our online shop: a small image, the product name with its size, and the price. Long names should end with “…”.
<li class="cart-row">
<img src="/images/shoe-42.jpg" width="64" height="64" alt="">
<div class="info">
<h3 class="name">Ultra light running shoes for long distance, waterproof edition</h3>
<p class="variant">Size 42</p>
</div>
<span class="price">$89</span>
</li>
.cart-row {
display: flex;
align-items: center;
gap: 12px;
}
.info {
flex: 1;
}
.name {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
On a wide desktop screen it looks fine. You see this in code review. What do you think? Is there a problem?
Short answer: On a narrow screen the row does not shrink. The long name does not get “…”, and the row becomes wider than the screen, so the price is pushed out. The reason is that a flex item has min-width: auto by default. The info box cannot become narrower than its content, and its content is the full name on one line. The fix is min-width: 0 on the info box.
Hint (if the candidate says there is no problem): On a phone 390 pixels wide, the cart page scrolls sideways. The price is outside the screen. The ellipsis never appears, even though the name has text-overflow: ellipsis. Why?
Why does this happen? (step by step)
- The flex: 1 shorthand lets the info box grow and shrink. Its starting size is zero.
- But a flex item also has a minimum size. By default it is min-width: auto.
- For a normal flex item, auto means: not smaller than its content’s minimum width (the min-content size).
- The name has white-space: nowrap, so its minimum width is the whole name on one line. That can be 500 pixels or more.
- So the info box stays at least that wide. The row overflows, and the price moves out of the screen.
- The ellipsis works only when the name’s box is narrower than its text. Here the box is never narrow, so there is nothing to cut.
The fix:
.cart-row {
display: flex;
align-items: center;
gap: 12px;
}
.cart-row img,
.cart-row .price {
flex-shrink: 0; /* keep image and price at full size */
}
.info {
flex: 1;
min-width: 0; /* allow shrinking below the content width */
}
.name {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
- With min-width: 0, the info box can become narrower than the name.
- Now the name’s box is narrower than its text, so overflow: hidden cuts it and text-overflow: ellipsis adds “…”.
- With flex-shrink: 0, the image and the price keep their size. Only the info box gives up space.
- Another option is overflow: hidden on the info box. A flex item that is a scroll container (for example with overflow: hidden) has an automatic minimum size of zero. But min-width: 0 says the intent more clearly.
- The trade-off: the full name is now hidden. Show it on the product page, or let the name wrap to two lines instead, if the design allows.
Follow-up question: We change the row to CSS Grid with grid-template-columns: 64px 1fr auto. Is the problem gone?
Follow-up answer:
- Not by itself. Grid items also have min-width: auto by default.
- Also, 1fr really means minmax(auto, 1fr). The minimum is auto, so the column can grow to fit the long nowrap name.
- The fix is minmax(0, 1fr) for that column, or min-width: 0 on the grid item.
.cart-row {
display: grid;
grid-template-columns: 64px minmax(0, 1fr) auto;
align-items: center;
gap: 12px;
}
Red flag: Tries to fix it with a fixed width like width: 200px on the name, or with overflow-x: hidden on the whole page, which only hides the bug. Or does not know that flex items have a minimum size.
6. A dropdown with z-index 9999 under the header
Question: The product list page of our online shop has a sticky header. Below it is a toolbar with a “Sort by” dropdown menu. A teammate added a small slide animation to the toolbar. Here is the CSS:
.site-header {
position: sticky;
top: 0;
z-index: 10;
}
.toolbar {
position: relative;
transform: translateY(0); /* for the slide animation */
transition: transform 200ms;
}
.sort-menu {
position: absolute;
z-index: 9999;
}
<header class="site-header">...</header>
<main>
<div class="toolbar">
<button type="button">Sort by</button>
<ul class="sort-menu">...</ul>
</div>
<!-- product grid -->
</main>
You see this in code review. What do you think? Is there a problem?
Short answer: The transform on the toolbar creates a new stacking context. The z-index of 9999 on the menu now counts only inside the toolbar. The toolbar itself has no z-index, so as a whole it is painted below the header, which has z-index 10. So the menu goes under the header, whatever number we give it. The fix is to remove the transform when it is not animating, to give the toolbar a z-index on the right level, or to move the menu out of the toolbar (for example, into the top layer with the popover attribute).
Hint (if the candidate says there is no problem): The user opens “Sort by” and scrolls down a little. The menu slides under the header and is cut off. A developer changes 9999 to 999999. Nothing changes. Without the transform line, the menu is above the header. Why?
Why does this happen? (step by step)
- The z-index only compares elements inside the same stacking context. The root element (the html tag) makes the first one.
- Some CSS properties create a new stacking context on an element. Examples: a transform other than none, opacity below 1, filter, position fixed or sticky, and position with a z-index other than auto.
- Here the toolbar has transform: translateY(0). That is not none, so the toolbar becomes a stacking context, even though it does not move.
- Now the menu’s z-index of 9999 is compared only with other things inside the toolbar.
- In the root stacking context, the toolbar has no z-index of its own, so it is painted at level 0. The sticky header has z-index 10. So the header is painted above the whole toolbar, including the menu.
- Think of it like folders: a page inside a folder cannot be above another folder, whatever its own number is.
The fix:
Option 1: use the transform only while animating.
.toolbar {
position: relative; /* containing block for the menu */
transition: transform 200ms;
}
.toolbar.is-entering {
transform: translateY(-8px);
}
Option 2: put the menu in the top layer with the popover attribute. The top layer is above everything, so z-index is not needed.
<button type="button" popovertarget="sort-menu">Sort by</button>
<ul id="sort-menu" popover>...</ul>
- With option 1, the toolbar has no transform at rest. So the menu belongs to the root stacking context again, and 9999 is above 10. The position: relative line only keeps the menu next to the toolbar; without a z-index it does not create a stacking context.
- Option 2 removes the problem completely. A popover is also closed by the Escape key and by a click outside, for free.
- The cost of option 2: the popover is no longer positioned next to the button by the toolbar’s layout. We must position it ourselves, for example with a few lines of JavaScript.
- Giving the toolbar z-index: 11 also “works”, but then the whole toolbar is above the sticky header when the page scrolls. Usually that is not what we want.
- In general, keep a small, written scale of z-index values (for example header 10, dropdown 20, modal 30) instead of random big numbers.
Follow-up question: How do you find which ancestor created the stacking context, on a big page?
Follow-up answer:
- Start from the element and walk up its ancestors in DevTools. In the Computed styles, look for the properties that create a stacking context: transform, opacity, filter, will-change, position with z-index, position fixed or sticky, isolation, contain, mix-blend-mode.
- Also check flex and grid children: a flex or grid item with a z-index other than auto creates a stacking context even without position.
- Chromium DevTools has a Layers panel that shows composited layers. That helps, but layers and stacking contexts are not exactly the same thing.
- The isolation: isolate property creates a stacking context on purpose. It is a clean way to keep a component’s z-index values inside the component.
Red flag: Raises the z-index to a bigger number again and again. Or says “z-index is global, the biggest number always wins”.
7. A product grid with fixed pixel widths
Question: This is the product grid of our online shop. The designer made it for a 1200 pixel wide desktop screen: four cards in a row. More than half of our visitors use phones.
.product-grid {
display: flex;
flex-wrap: wrap;
width: 1200px;
}
.product-card {
width: 280px;
margin: 10px;
}
You see this in code review. What do you think? Is there a problem?
Short answer: Every size is a fixed number of pixels. On a phone about 390 pixels wide, the grid is still 1200 pixels wide, so the page scrolls sideways or the browser shrinks the whole page. The layout must adapt to the space it has. The simple fix is CSS Grid with repeat(auto-fill, minmax(…)), a max-width instead of a width, and relative units.
Hint (if the candidate says there is no problem): On a phone, the user sees one product card and part of the next one and has to scroll sideways to see the rest. Or, if the viewport meta tag is missing, the whole page is tiny and the user must zoom in. Why?
Why does this happen? (step by step)
- The width: 1200px line makes the grid exactly 1200 pixels, on every screen.
- The phone screen is about 390 CSS pixels wide. The grid does not fit, so it overflows to the right.
- Each card is also exactly 280 pixels. Even if the grid could shrink, the number of columns would not change in a smart way.
- Without the viewport meta tag, many phone browsers draw the page as if it were about 980 pixels wide and shrink it. Then the text is too small to read.
- The design was checked only on the designer’s screen, so nobody saw this.
The fix:
<meta name="viewport" content="width=device-width, initial-scale=1">
.product-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(100%, 220px), 1fr));
gap: 1rem;
max-width: 1200px;
margin-inline: auto;
padding-inline: 1rem;
}
- The viewport meta tag tells the phone browser to use the real screen width.
- With max-width, the grid is at most 1200 pixels, but it can be smaller on small screens.
- The repeat(auto-fill, minmax(220px, 1fr)) pattern means: make as many columns as fit, each at least 220 pixels, and share the extra space equally.
- So the browser chooses the number of columns: 1 on a phone, 2 or 3 on a tablet, 4 or more on a desktop. We write no media queries.
- The min(100%, 220px) part protects very narrow screens. If the container is narrower than 220 pixels, a column is never wider than the container.
- The gap property makes space between cards. Then margins on the cards are not needed.
- The rem unit follows the user’s font size setting, so spacing grows with the text.
- The trade-off: we do not control the exact number of columns at each width. If the design needs exactly 2 columns on tablets, use media queries for that case.
Follow-up question: The same product card is used in the wide main grid and in a narrow “You may also like” sidebar. In the wide place, the image should be next to the text. In the narrow place, the image should be above. How?
Follow-up answer:
- Media queries look at the screen width, not at the space the card has. On a desktop the screen is wide, but the sidebar is narrow.
- Container queries solve this. The card reacts to the width of its container.
.card-slot {
container-type: inline-size;
}
.product-card {
display: flex;
flex-direction: column;
}
@container (min-width: 400px) {
.product-card {
flex-direction: row;
}
}
- Each place that holds a card is a container. The card changes its layout based on that container’s width.
- Container queries work in all current major browsers.
Red flag: Wants to add a media query for every phone model, or to build a separate mobile site. Or does not know what the viewport meta tag does.
8. A cart drawer animated with left and width
Question: When the user adds a product, our online shop opens a cart drawer from the right side. The drawer shows the cart items and the total. Here is the CSS. JavaScript only toggles the open class.
.cart-drawer {
position: fixed;
top: 0;
left: 100%;
width: 0;
height: 100%;
overflow: hidden;
transition: left 300ms ease-out, width 300ms ease-out;
}
.cart-drawer.open {
left: calc(100% - 360px);
width: 360px;
}
On the developer’s laptop it looks smooth. You see this in code review. What do you think? Is there a problem?
Short answer: The animation changes left and width. These are layout properties. On every frame, the browser must calculate layout again (the text and items inside the drawer reflow, because the width changes), then paint again. On a slow phone this does not fit in one frame, so the animation stutters. The fix is to animate only transform (and opacity if needed). The browser can usually do those on the compositor, without layout and paint.
Hint (if the candidate says there is no problem): On a mid-range Android phone, the drawer opens in jumps. It is worse when the cart has many items, or when JavaScript is busy at the same moment. In the DevTools Performance panel, we see many purple “Layout” blocks during the animation. Why?
Why does this happen? (step by step)
- To show a frame, the browser runs a pipeline: style, then layout (sizes and positions), then paint (pixels), then composite (put layers together).
- A smooth animation needs a new frame about every 16 milliseconds on a 60 Hz screen.
- Changing left changes the position, so layout runs on every frame.
- Changing width is even worse. The content inside the drawer has a new width on each frame, so every line of text and every cart item is laid out again, and then painted again.
- Layout and paint run on the main thread. JavaScript runs there too. If both need time, frames are dropped and the user sees jumps.
- A fast laptop hides the problem. A phone CPU can be several times slower.
The fix:
.cart-drawer {
position: fixed;
top: 0;
right: 0;
width: min(360px, 100vw);
height: 100%;
transform: translateX(100%); /* hidden off screen */
transition: transform 300ms ease-out;
}
.cart-drawer.open {
transform: translateX(0);
}
@media (prefers-reduced-motion: reduce) {
.cart-drawer {
transition: none;
}
}
- The drawer always has its final width. So its content is laid out only once, not on every frame.
- Only transform changes. A transform moves the drawer as a ready picture (a layer). It does not change layout.
- Browsers can usually run transform and opacity animations on the compositor thread. Then the animation stays smooth even if the main thread is busy for a moment.
- Users who asked the system for less motion get the drawer without animation.
- One more point: when the drawer is closed, it is only moved off screen. Its buttons can still get keyboard focus. Set the inert attribute on it while it is closed (or use visibility: hidden), so Tab does not go into a hidden drawer.
- The trade-off: each layer uses GPU memory. Do not add will-change: transform to many elements “just in case”. Use it only where you measured a need.
Follow-up question: How do you prove that the new version is better, not just “it feels smoother”?
Follow-up answer:
- Open the DevTools Performance panel and turn on CPU throttling (for example 4x slowdown) to act like a phone.
- Record opening the drawer. In the old version you see Layout and Paint work on every frame. In the new version, those blocks during the animation should mostly disappear.
- In the Rendering tab, “Paint flashing” shows green areas that are painted again. With transform, the drawer should not flash on every frame.
- Best of all, test on a real mid-range phone, because throttling is only an estimate.
Red flag: Says “Add will-change to everything” or “Use a JavaScript animation library” without understanding layout and paint. Or tests only on a fast laptop.
9. var in a loop with setTimeout
Question: In our online shop, a developer wants to log each product of the cart a moment later. What does this code print, and why?
const products = ['Shoes', 'Hat', 'Bag'];
for (var i = 0; i < products.length; i++) {
setTimeout(() => {
console.log(i, products[i]);
}, 0);
}
Short answer: It prints “3 undefined” three times. A variable declared with var is not created again for each loop round. There is only one i for the whole function. The callbacks run after the loop has finished, when i is already 3, and products[3] does not exist. With let instead of var, each round gets its own i, and it prints 0 Shoes, 1 Hat, 2 Bag.
3 undefined
3 undefined
3 undefined
Why does this happen? (step by step)
- The var keyword makes a variable that belongs to the whole function (or the whole script), not to the loop block.
- So all three arrow functions close over the same single variable i. A closure keeps a reference to the variable, not a copy of its value.
- The setTimeout call does not run the callback now. It only schedules it, even with a delay of 0.
- The loop runs to the end first. It stops when i becomes 3, because 3 is not less than 3.
- Only after the current code has finished, the three callbacks run. Each one reads i, which is 3 now.
- products[3] is outside the array, so it is undefined.
The fix:
const products = ['Shoes', 'Hat', 'Bag'];
for (let i = 0; i < products.length; i++) {
setTimeout(() => {
console.log(i, products[i]);
}, 0);
}
0 Shoes
1 Hat
2 Bag
- A for loop with let creates a new binding of i for each round. Each callback closes over its own i.
- In modern code, use const and let, never var.
- The same bug appears in real pages. For example, a loop with var that adds a click listener to each “Add to cart” button: every button would add products[3], which is undefined.
- Often the forEach method is even clearer, because the index is a parameter of each call.
products.forEach((product, i) => {
setTimeout(() => console.log(i, product), 0);
});
Follow-up question: In old code you cannot change var to let. How can you fix it without let?
Follow-up answer:
- Pass the value at the moment you schedule it. The setTimeout function sends extra arguments to the callback.
for (var i = 0; i < products.length; i++) {
setTimeout((index) => {
console.log(index, products[index]);
}, 0, i);
}
- Or wrap the body in a function that is called right away (an IIFE) and receives i as a parameter. Each call has its own parameter, so each callback sees its own value.
- Both work because a function parameter is a new variable for each call.
Red flag: Says “It prints 0, 1, 2 because the delay is 0”. Or knows that let fixes it but cannot explain why.
10. A class method as an event listener
Question: Our online shop keeps the cart in a small class. The “Add to cart” button on the product page is wired like this:
<button type="button" id="add-to-cart" data-product-id="42">Add to cart</button>
class Cart {
items = [];
add(event) {
const id = event.currentTarget.dataset.productId;
this.items.push(id);
console.log('Items in cart:', this.items.length);
}
}
const cart = new Cart();
document.querySelector('#add-to-cart').addEventListener('click', cart.add);
You see this in code review. What do you think? Is there a problem?
Short answer: The method is passed alone, without its object. In JavaScript, the value of this is decided by how a function is called, not where it is written. The browser calls the listener with this set to the button element, not to the cart. The button has no items property, so this.items is undefined and the push call throws a TypeError. The fix is an arrow function wrapper, the bind method, or a class field arrow function.
Hint (if the candidate says there is no problem): The user clicks “Add to cart”. Nothing is added. The console shows an error like “Cannot read properties of undefined (reading ‘push’)”. Calling cart.add(fakeEvent) in a unit test works fine. Why?
Why does this happen? (step by step)
- The expression cart.add only reads the function from the object. It does not keep any link to cart.
- The value of this is set at call time. With cart.add(event), the object before the dot is cart, so this is cart.
- Here, we gave the bare function to addEventListener. Later the browser calls it by itself. For event listeners, the browser sets this to the element the listener is on, here the button.
- The button has no items property. So this.items is undefined, and calling push on undefined throws a TypeError.
- In other callbacks, this is often undefined instead. For example, if you pass cart.add to a promise’s then method. Class bodies always run in strict mode, so a plain call gives undefined as this.
- The unit test called cart.add(…) with the dot, so it never showed the bug.
The fix:
Option 1: wrap it in an arrow function.
const button = document.querySelector('#add-to-cart');
button.addEventListener('click', (event) => cart.add(event));
Option 2: make the method an arrow function class field.
class Cart {
items = [];
add = (event) => {
const id = event.currentTarget.dataset.productId;
this.items.push(id);
console.log('Items in cart:', this.items.length);
};
}
- In option 1, we call cart.add with the dot again, so this is the cart.
- Option 2 uses an arrow function. An arrow function has no own this. It uses the this of the place where it was created, which is the new object. So cart.add can be passed anywhere.
- The bind method also works: cart.add.bind(cart) returns a new function where this is always cart.
- The trade-off of option 2: each Cart object gets its own copy of the function, instead of one shared function on the prototype. For a few objects that does not matter. It also cannot be called with super from a subclass.
Follow-up question: Later we want to remove the listener. A developer writes this. Does it work?
button.addEventListener('click', cart.add.bind(cart));
// later
button.removeEventListener('click', cart.add.bind(cart));
Follow-up answer:
- No. Each call to bind returns a new function. The removeEventListener method needs the exact same function object that was added, so it removes nothing.
- Keep the reference in a variable and use it for both calls.
const onAdd = (event) => cart.add(event);
button.addEventListener('click', onAdd);
// later
button.removeEventListener('click', onAdd);
- Another clean way is an AbortController. Pass its signal when you add the listener, and call abort to remove it. This is handy when one component adds many listeners.
const controller = new AbortController();
button.addEventListener('click', (event) => cart.add(event), { signal: controller.signal });
// later
controller.abort();
Red flag: Says “this always points to the object where the method is written”. Or “fixes” it by using a global cart variable inside the method.
11. Default values with || and the number zero
Question: Our online shop calculates the total of each cart line in the browser. The API sends the price, the quantity, and the discount percent. If the API does not send a discount, a default campaign discount of 10% applies. Products that are excluded from the campaign come with a discount of 0.
function lineTotal(item) {
const qty = item.qty || 1;
const discount = item.discountPercent || 10; // default campaign discount
return item.price * qty * (1 - discount / 100);
}
console.log(lineTotal({ price: 200, qty: 2, discountPercent: 25 })); // 300
You see this in code review. What do you think? Is there a problem?
Short answer: The || operator gives the right side for every falsy value, not only for a missing value. Zero is falsy. So a quantity of 0 becomes 1, and a discount of 0% becomes 10%. The fix is the ?? operator (nullish coalescing). It uses the default only when the value is null or undefined.
Hint (if the candidate says there is no problem): A product excluded from the campaign still shows a 10% discount. A user sets the quantity to 0 before removing the line, but the line still costs money. For lineTotal with price 200, qty 0 and discount 0, the result is 180, not 0. Why?
Why does this happen? (step by step)
- The expression a || b returns a if a is truthy. Otherwise it returns b.
- Falsy values in JavaScript are: false, 0, -0, 0n, the empty string, null, undefined and NaN.
- So item.qty || 1 with qty 0 returns 1. The code cannot tell “no value” from “the value is zero”.
- In the same way, discountPercent 0 becomes 10.
- The result for price 200, qty 0, discount 0 is 200 × 1 × 0.9 = 180. The right answer is 0.
- Before the ?? operator existed (ES2020), || was the usual way to write defaults. That is why this bug is so common in older code.
The fix:
function lineTotal(item) {
const qty = item.qty ?? 1;
const discount = item.discountPercent ?? 10;
return item.price * qty * (1 - discount / 100);
}
console.log(lineTotal({ price: 200, qty: 0, discountPercent: 0 })); // 0
console.log(lineTotal({ price: 200, qty: 2, discountPercent: 0 })); // 400
console.log(lineTotal({ price: 200 })); // 180
- The expression a ?? b returns b only if a is null or undefined. Zero, false and the empty string stay as they are.
- Now 0 means 0, and a missing value gets the default.
- There is also an assignment form: settings.pageSize ??= 20 sets the value only if it is null or undefined.
- Keep || for cases where every falsy value really means “use the default”, for example an empty search text that should show “All products”.
- One more point: values from form fields are strings. An empty field gives the empty string, not undefined. So convert and validate the input first (for example with the Number function), and do not trust a default to fix bad input.
Follow-up question: We use default parameters instead: function lineTotal({ price, qty = 1, discountPercent = 10 }). Is it the same as the ?? operator?
Follow-up answer:
- Not exactly. A default parameter (or a default in destructuring) is used only when the value is undefined.
- If the API sends qty: null, the default is not used. qty stays null, and price × null becomes 0.
- The ?? operator treats null and undefined the same way.
- Also, you cannot mix ?? with || or && without parentheses. For example, a || b ?? c is a syntax error. You must write (a || b) ?? c.
Red flag: Says “|| and ?? are the same”. Or does not know which values are falsy, especially 0 and the empty string.
12. Copying the cart with spread
Question: Our online shop has an “Undo” button in the cart. Before each change, we save the current cart in a history array. To change a quantity, a developer wrote this function. It “copies the cart first, so the old one stays the same”.
function setQty(cart, productId, qty) {
const next = { ...cart };
const item = next.items.find((i) => i.productId === productId);
item.qty = qty;
return next;
}
const history = [];
let cart = { id: 'c1', items: [{ productId: 7, name: 'Shoes', qty: 1 }] };
history.push(cart);
cart = setQty(cart, 7, 3);
You see this in code review. What do you think? Is there a problem?
Short answer: The spread syntax makes a shallow copy. It creates a new outer object, but the items array and the item objects inside it are the same ones. So item.qty = qty changes the old cart too, and the saved history is changed. Undo does nothing. The fix is to copy every level we change: a new items array (with map) and a new item object.
Hint (if the candidate says there is no problem): The user changes the quantity of shoes from 1 to 3 and presses Undo. The quantity stays 3. In the console, history[0].items[0].qty is 3, not 1. Also, a UI part that compares the old and new items array by reference thinks nothing changed. Why?
Why does this happen? (step by step)
- Objects and arrays in JavaScript are stored by reference. A variable holds a pointer to the object, not the object itself.
- The spread syntax copies the top-level properties into a new object. For items, it copies the pointer, not the array.
- So next.items and cart.items point to the same array, and the same item objects.
- The find method returns that shared item object. Setting item.qty changes it for everyone who points to it.
- The history holds the old cart, but the old cart’s items are the same objects. So history[0].items[0].qty becomes 3 too.
- Also, history[0].items === cart.items is true. Code that checks “did items change?” by reference (common in UI libraries and memo logic) sees no change.
The fix:
function setQty(cart, productId, qty) {
return {
...cart,
items: cart.items.map((item) =>
item.productId === productId ? { ...item, qty } : item
),
};
}
- The map method returns a new array, so the items array is new.
- Only the changed item gets a new object with its own qty. The old item object is not touched.
- Items that did not change are reused. This is called structural sharing. It is cheap, and unchanged parts keep the same reference, so UI code can skip them.
- Now history[0].items[0].qty stays 1, and Undo works.
- Another option is structuredClone(cart), which makes a full deep copy. It is simpler to write, but it copies everything on every change, and every item gets a new reference even if it did not change. It also throws an error for functions.
- The trade-off: copying by hand at each level is more code when the data is deeply nested. Then a helper library, or keeping the data flatter, can help.
Follow-up question: Can Object.freeze protect the history from this kind of bug? And why not use JSON.parse(JSON.stringify(cart)) for a deep copy?
Follow-up answer:
- Object.freeze is also shallow. It freezes only the outer object. The items array and the item objects can still be changed. You would need to freeze every level.
- In strict mode, writing to a frozen property throws an error. In sloppy mode the write is silently ignored. Freezing every level is mostly useful in development, to find such bugs early.
- The JSON trick loses data: a Date becomes a string, undefined values and functions disappear, and Map or Set become empty objects.
- The structuredClone function keeps Date, Map and Set, and it handles circular references. But it throws a DataCloneError for functions, and class instances lose their class (they become plain objects).
Red flag: Says “the spread syntax makes a copy, so the original is safe”, without saying the copy is shallow. Or uses JSON.parse(JSON.stringify(…)) for everything without knowing what it loses.
13. Sorting prices with the default sort
Question: The product list of our online shop has a “Sort by price: low to high” option. The prices come from the API as numbers. A developer tests the sort with three prices. What does this code print, and why?
const prices = [25, 100, 9];
const sorted = prices.sort();
console.log(sorted);
console.log(prices);
Short answer: It prints [ 100, 25, 9 ] two times (this is Node’s output format). Without a compare function, the sort method converts the values to strings and compares them as text. As text, “100” comes before “25”, and “25” comes before “9”. It also sorts the array in place and returns the same array, so the original prices are changed too. The fix is a compare function, (a, b) => a - b, and the toSorted method if you need to keep the original.
[ 100, 25, 9 ]
[ 100, 25, 9 ]
Why does this happen? (step by step)
- The default sort order is for strings. Each number is converted to a string first: “25”, “100”, “9”.
- Strings are compared character by character, from the left, by UTF-16 code units.
- “100” starts with “1”, “25” starts with “2”, and “9” starts with “9”. “1” is less than “2”, and “2” is less than “9”.
- So the order is “100”, “25”, “9”. The numbers are in text order, not number order.
- The sort method changes the array itself and returns that same array. So sorted and prices are one array, and sorted === prices is true.
- In the shop, that means the original list from the API is lost. A “Reset sort” button that shows the original order would show the sorted order instead.
The fix:
const prices = [25, 100, 9];
const sorted = prices.toSorted((a, b) => a - b);
console.log(sorted); // [ 9, 25, 100 ]
console.log(prices); // [ 25, 100, 9 ]
- The compare function returns a negative number if a should come first, a positive number if b should come first, and 0 if they are equal.
- For numbers, a - b does exactly that. For high to low, use b - a.
- The toSorted method (ES2023) returns a new sorted array and leaves the original as it is. It works in all current major browsers.
- In older code, […prices].sort((a, b) => a - b) does the same: copy first, then sort the copy.
- For product objects, compare the property: products.toSorted((a, b) => a.price - b.price).
- The trade-off: toSorted makes a new array, so it uses a little more memory. For a product list this is not a problem.
Follow-up question: Now we sort product names, for example “Zebra hat”, “apple watch”, “Émile bag”. The default sort gives a strange order. Why, and what do you use?
Follow-up answer:
- The default sort compares UTF-16 code units. All capital letters come before small letters, and letters with accents like É come after the normal letters. So the default result is “Zebra hat”, “apple watch”, “Émile bag”.
- For text that people read, use a compare function that knows the language: a.localeCompare(b), or an Intl.Collator object.
const collator = new Intl.Collator('en', { sensitivity: 'base' });
const names = ['Émile bag', 'Zebra hat', 'apple watch'];
console.log(names.toSorted(collator.compare));
// [ 'apple watch', 'Émile bag', 'Zebra hat' ]
- Create the Intl.Collator object once and reuse it. It is faster than calling localeCompare on every comparison for long lists.
- Also good to know: since ES2019, sort is stable. Items that compare as equal keep their original order.
Red flag: Expects [ 9, 25, 100 ] from the default sort. Or does not know that sort changes the original array.
14. forEach with an async callback
Question: The admin page of our online shop has a “Save all” button. A staff member edits several orders (usually 5 to 50) and saves them together. Each order is saved with one API call. After saving, the page shows a message and goes back to the order list.
async function saveAll(orders) {
try {
orders.forEach(async (order) => {
await api.saveOrder(order);
});
showToast('All orders saved');
goToOrderList();
} catch (error) {
showToast('Saving failed');
}
}
You see this in code review. What do you think? Is there a problem?
Short answer: The forEach method does not wait for async callbacks. It calls each callback, ignores the promise it returns, and finishes at once. So “All orders saved” is shown before any order is saved, and the page leaves too early. If one save fails, the try/catch does not catch it, because the error happens later, in a promise nobody waits for. The fix is a for…of loop with await (one by one), or Promise.all or Promise.allSettled with map (in parallel).
Hint (if the candidate says there is no problem): The toast “All orders saved” appears immediately, even when the network is slow. Sometimes one order is not saved, but the user still sees “All orders saved”. The console shows an “Uncaught (in promise)” error. The “Saving failed” message never appears. Why?
Why does this happen? (step by step)
- An async function always returns a promise. The await inside it pauses only that function, not the code that called it.
- The forEach method calls the callback for each order and throws away the return value. It does not know about promises, and it returns undefined.
- So all saves start almost at the same time, and forEach returns at once. The next line, showToast, runs while the requests are still in flight.
- When a save fails later, its promise is rejected. Nobody waits for that promise, so the error is not caught by the try/catch around forEach. The try block has already finished.
- The browser reports it as an unhandled rejection. The user sees a success message for a failed save.
We can see the order with a small script in Node, with a fake API where order 2 fails:
All orders saved
saved 1
unhandled: fail 2
saved 3
The fix:
Option 1: one by one, with for…of.
async function saveAll(orders) {
try {
for (const order of orders) {
await api.saveOrder(order);
}
showToast('All orders saved');
goToOrderList();
} catch (error) {
showToast('Saving failed');
}
}
Option 2: in parallel, and report each failure.
async function saveAll(orders) {
const results = await Promise.allSettled(
orders.map((order) => api.saveOrder(order))
);
const failed = results.filter((result) => result.status === 'rejected');
if (failed.length === 0) {
showToast('All orders saved');
goToOrderList();
} else {
showToast(`${failed.length} of ${orders.length} orders were not saved`);
}
}
- In option 1, await inside a for…of loop really pauses the loop. The toast runs only after the last save. An error goes to the catch block. The cost: the total time is the sum of all requests, and the loop stops at the first error.
- In option 2, map returns an array of promises, and Promise.allSettled waits for all of them. The total time is about the slowest request.
- The Promise.allSettled method never rejects. It gives a result for each order, so we can tell the user exactly how many failed.
- Promise.all is also an option, but it rejects as soon as the first promise rejects. Then we do not know about the others.
- The trade-off of option 2: 50 parallel requests can overload the server or hit a rate limit. Then send them in small batches, or use a small concurrency limit.
Follow-up question: With Promise.all, when one save fails, are the other requests stopped?
Follow-up answer:
- No. Promise.all only stops waiting. It rejects with the first error, but the other requests keep running, and some of them may still succeed on the server.
- So after a failure, the data may be partly saved. The UI should not assume “nothing was saved”.
- To really cancel the other fetch requests, pass the signal of an AbortController to each request, and call abort when one fails. Even then, a request that has already reached the server may still be processed there.
- This is one more reason for the save API to be idempotent, so that a retry does not create duplicates.
Red flag: Says “There is an await inside, so it waits”. Or does not know that forEach ignores the promises returned by its callback.
15. Event loop order: timeout, promise and microtask
Question: In our online shop, the click handler of the “Pay” button does a few things. Some of them are scheduled for later. What does this code print, and why?
console.log('1: click on Pay');
setTimeout(() => {
console.log('2: timeout: show survey');
}, 0);
Promise.resolve().then(() => {
console.log('3: then: update cart badge');
});
queueMicrotask(() => {
console.log('4: microtask: log analytics');
});
console.log('5: end of click handler');
Short answer: It prints 1, 5, 3, 4, 2. First all normal (synchronous) code runs: 1 and 5. Then the event loop empties the microtask queue: the promise callback (3) and the queueMicrotask callback (4), in the order they were added. Only then does it run the next task from the task queue, the setTimeout callback (2). A delay of 0 does not mean “now”. It means “as a task, after the current work and all microtasks”.
1: click on Pay
5: end of click handler
3: then: update cart badge
4: microtask: log analytics
2: timeout: show survey
Why does this happen? (step by step)
- JavaScript runs on one thread. The current code always runs to the end before anything else can run.
- Line 1 prints right away.
- The setTimeout call puts its callback in the task queue (also called the macrotask queue). It will run later, at the earliest after the timer (here 0 ms) has passed.
- The Promise is already resolved, so its then callback goes into the microtask queue.
- The queueMicrotask call also puts its callback into the microtask queue, after the promise callback.
- Line 5 prints. Now the current code is finished, and the call stack is empty.
- The event loop now runs all microtasks, in order: 3, then 4. If a microtask adds another microtask, that one also runs before any task.
- Only after the microtask queue is empty does the event loop take the next task: the timeout callback prints 2.
- In a browser, the page can also be rendered between tasks. That is why a long chain of microtasks can block rendering, but a setTimeout gives the browser a chance to draw.
Why this matters in the shop:
- Code after an await, or in a then callback, runs as a microtask. It runs before any timer or the next user event.
- If we want the browser to show “Processing payment…” before heavy work, a microtask is not enough. The heavy work must wait for a new task (for example a setTimeout) or for the next frame, so the browser can paint first.
- The opposite is also true: a microtask that keeps adding microtasks can freeze the page, because tasks and rendering never get a turn.
Follow-up question: What does this print?
setTimeout(() => console.log('A'), 0);
Promise.resolve().then(() => {
console.log('B');
setTimeout(() => console.log('C'), 0);
Promise.resolve().then(() => console.log('D'));
});
console.log('E');
Follow-up answer:
E
B
D
A
C
- E is synchronous, so it prints first.
- B is a microtask, so it runs right after the synchronous code.
- Inside B, a new microtask (D) and a new task (C) are added. The microtask queue must be empty before any task runs, so D runs next.
- Then the tasks run in the order they were added: A was added first (in the main code), C was added later (inside B).
Red flag: Says “setTimeout with 0 runs immediately”. Or thinks the promise callback runs before line 5, because “the promise is already resolved”.
16. Three awaits, one after another
Question: In our online shop, the product page loads three things from three API endpoints. Each call needs only the product id. Here is the code:
async function loadProductPage(id: string) {
const product = await getProduct(id); // about 300 ms
const reviews = await getReviews(id); // about 400 ms
const stock = await getStock(id); // about 300 ms
render(product, reviews, stock);
}
Most of our users open this page on a phone. You see this in code review. What do you think? Is there a problem?
Short answer: Each await pauses the function until that request is done. So the three requests run one after another, and the times add up: about 300 + 400 + 300 = 1000 ms. The calls do not depend on each other, so we should start all three at once and wait for them together with Promise.all. Then the total is about the time of the slowest one, about 400 ms. If one part may fail and the page can live without it (for example the reviews), use Promise.allSettled, so one failure does not break the whole page.
Hint (if the candidate says there is no problem): In the Network panel of DevTools, the three requests look like stairs: the second request starts only when the first one ends. On a slow mobile network, the page needs more than a second before it shows anything.
Why does this happen? (step by step)
- The await keyword waits for a Promise. The rest of the function does not run until that Promise is settled.
- So the getReviews function is called only after the product has arrived. Its request starts late.
- The getStock function is called even later.
- The times add up: 300 + 400 + 300 = 1000 ms.
- This is not about threads. JavaScript runs our code on one thread, but the browser can wait for many network requests at the same time. Here we simply do not ask for them at the same time.
The fix:
Start all three requests first, then wait for all of them together.
async function loadProductPage(id: string) {
const [product, reviews, stock] = await Promise.all([
getProduct(id),
getReviews(id),
getStock(id),
]);
render(product, reviews, stock);
}
- All three functions are called right away, so all three requests start right away.
- Promise.all waits until all of them are done. The total time is about 400 ms, the slowest request.
- The results come back in the same order as the array, not in the order they finished.
But Promise.all has a catch:
- Promise.all rejects as soon as one of the Promises rejects, with that error.
- The other requests are not cancelled. Their results are just thrown away.
- So if only the reviews service is down, the whole product page fails, even though the product and the stock arrived.
When one part may fail, use Promise.allSettled:
async function loadProductPage(id: string) {
const [productResult, reviewsResult, stockResult] = await Promise.allSettled([
getProduct(id),
getReviews(id),
getStock(id),
]);
// Without the product we cannot show the page
if (productResult.status === 'rejected') {
throw productResult.reason;
}
const reviews = reviewsResult.status === 'fulfilled' ? reviewsResult.value : [];
const stock = stockResult.status === 'fulfilled' ? stockResult.value : null;
render(productResult.value, reviews, stock);
}
- Promise.allSettled never rejects. It waits for all of them and gives an object for each one: status “fulfilled” with a value, or status “rejected” with a reason.
- We decide per part: the product is required, the reviews and the stock are optional.
- The page can show “Reviews are not available right now” instead of a full error page.
Trade-off: Run things in parallel only when they really do not depend on each other. Three requests at once is fine. Hundreds at once can overload the server, so then we limit how many run at the same time.
Follow-up question: Now we also want “related products”. That call needs the categoryId field of the product, so it must wait for the product. The stock call still needs only the id. How do you write it so nothing waits longer than needed?
Follow-up answer:
async function loadProductPage(id: string) {
const productPromise = getProduct(id);
const [product, stock, related] = await Promise.all([
productPromise,
getStock(id),
productPromise.then((p) => getRelated(p.categoryId)),
]);
render(product, stock, related);
}
- The product and the stock start at the same time.
- The related products start as soon as the product arrives. They do not wait for the stock.
- Every Promise is inside Promise.all, so an error in any of them is handled in one place. If we started a Promise and awaited it only much later, a failure in the meantime could show up as an “unhandled rejection”.
Red flag: Thinks that async functions run “in the background on another thread”, or that three awaits already run in parallel. Or uses Promise.all but does not know that one failure rejects the whole thing.
17. Search box: old answer wins
Question: Our online shop has about 20,000 products. The search box shows results while the user types. Many users are on phones with a mobile network. Here is the code:
const input = document.querySelector('#search');
const list = document.querySelector('#results');
input.addEventListener('input', async () => {
const res = await fetch(`/api/search?q=${encodeURIComponent(input.value)}`);
const products = await res.json();
list.replaceChildren(
...products.map((p) => {
const li = document.createElement('li');
li.textContent = p.name;
return li;
}),
);
});
You see this in code review. What do you think? Is there a problem?
Short answer: There are two problems. First, the code sends a request on every key press: typing “laptop” sends 6 requests. Second, the responses can come back in a different order. A slow response for “lap” can arrive after the response for “laptop” and draw the wrong list. This is a race condition. The fix is to debounce (wait about 300 ms after the last key press) and to cancel the old request with an AbortController, so only the latest search can draw the list.
Hint (if the candidate says there is no problem): A user types “laptop” quickly. The box says “laptop”, but the list shows results for “lap”, like laptop bags and lap trays. It happens more on slow mobile networks. On the developer’s laptop it never happens.
Why does this happen? (step by step)
- Each input event starts a new fetch. All these requests run at the same time.
- The server time depends on the query. A short query like “lap” matches many products, so it is slower. “laptop” matches fewer, so it is faster.
- So the response for “laptop” arrives first and draws the right list.
- Then the response for “lap” arrives and draws the list again. The last response to arrive wins, not the last query the user typed.
- Nothing in the code asks: “Is this response still the latest one?”
The fix:
const input = document.querySelector('#search');
const list = document.querySelector('#results');
let controller = null;
let timer = null;
input.addEventListener('input', () => {
clearTimeout(timer);
timer = setTimeout(() => search(input.value.trim()), 300);
});
async function search(query) {
controller?.abort(); // cancel the previous request
controller = new AbortController();
if (!query) {
list.replaceChildren();
return;
}
try {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
signal: controller.signal,
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const products = await res.json();
list.replaceChildren(
...products.map((p) => {
const li = document.createElement('li');
li.textContent = p.name;
return li;
}),
);
} catch (err) {
if (err.name === 'AbortError') return; // a newer search replaced this one
list.textContent = 'Search failed. Please try again.';
}
}
- Debounce: every key press resets the timer. The search runs only when the user stops typing for 300 ms. “laptop” now sends one request, not six.
- Abort: before a new search, we abort the old request. The fetch of the old request rejects with an error named “AbortError”, so its old result never reaches the list.
- We need both. Debounce alone is not enough: a user can pause, a slow request starts, then the user types again, and the old request is still on the way. Abort alone still sends a request for every key.
- We also check the ok property of the response, because fetch does not reject on a 404 or a 500.
Trade-off: The debounce adds a small delay. Around 200 to 300 ms usually feels fine. Longer feels slow. Also, aborting stops the browser from waiting. It does not always stop the work on the server, which may already be running.
Follow-up question: We use a helper function from a library that does not accept an AbortSignal. How do you still make sure an old response never draws over a new one?
Follow-up answer:
Give each request a number and ignore every response that is not from the latest one:
let lastRequestId = 0;
async function search(query) {
const requestId = ++lastRequestId;
const products = await searchApi(query); // cannot be cancelled
if (requestId !== lastRequestId) return; // an old response, ignore it
showResults(products);
}
- The old requests still use the network, but they cannot change the screen anymore.
- This check is useful even with an AbortController, as a second safety net.
Red flag: Says “debounce fixes it” and does not see the ordering problem. Or believes HTTP responses always come back in the order the requests were sent. Or “fixes” it by disabling the input while a request is loading.
18. A 404 is not an error for fetch
Question: This is the “Add to cart” button handler of our online shop:
async function addToCart(productId) {
try {
await fetch('/api/cart', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ productId, quantity: 1 }),
});
showToast('Added to cart');
} catch (err) {
showToast('Could not add to cart');
}
}
The server answers with 409 when the product is out of stock, 401 when the session has expired, and 500 when something breaks. You see this in code review. What do you think? Is there a problem?
Short answer: The fetch function rejects only when there is no HTTP response at all: the network is down, the request was blocked (for example by CORS), or it was aborted. A 404, 409 or 500 is a normal HTTP response, so the Promise resolves and the code shows “Added to cart”. We must check the ok property of the response (true only for status 200 to 299) or the status property, and handle errors ourselves.
Hint (if the candidate says there is no problem): Support gets complaints: “The page said Added to cart, but my cart is empty.” The server logs show a 409 “out of stock” answer for exactly those requests.
Why does this happen? (step by step)
- The fetch function gives back a Promise of a Response.
- If the server answers at all, with any status code, the Promise is fulfilled. The status code is just data inside the Response.
- So for a 409 the code goes straight to showToast with “Added to cart”. The catch block never runs.
- The catch block runs only for network errors, blocked requests or an abort.
- Some people expect a 404 to throw because the axios library rejects for non-2xx status codes by default. The built-in fetch does not.
The fix:
async function addToCart(productId) {
try {
const res = await fetch('/api/cart', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ productId, quantity: 1 }),
});
if (res.status === 409) {
showToast('Sorry, this product is out of stock');
return;
}
if (res.status === 401) {
redirectToLogin();
return;
}
if (!res.ok) {
throw new Error(`Add to cart failed: HTTP ${res.status}`);
}
showToast('Added to cart');
} catch (err) {
console.error(err);
showToast('Could not add to cart. Please try again.');
}
}
- We read the response and check the status first.
- The errors the user can act on (out of stock, login again) get their own message.
- Every other non-ok status becomes an error, so it goes to the same catch block as network errors.
- Small extra point: on a 500, the body is often an HTML error page. If we call the json method on it, it throws a parse error. So check the status before reading the body as JSON.
Trade-off: Checking the status in every call is repeated work. Most teams write one small wrapper (for example an apiFetch function) that checks the ok property and throws an error with the status. Then every call gets the same rule.
Follow-up question: On a bad mobile network, the request sometimes hangs for a minute and the button looks dead. How do you add a timeout?
Follow-up answer:
const res = await fetch('/api/cart', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ productId, quantity: 1 }),
signal: AbortSignal.timeout(8000), // give up after 8 seconds
});
- The fetch function has no timeout option, but it accepts an AbortSignal.
- The AbortSignal.timeout method makes a signal that aborts after the given time. The fetch then rejects with an error named “TimeoutError”, so it lands in our catch block.
- Careful: the server may still have added the item. So after a timeout, show “We are not sure it worked” and reload the cart, instead of saying “Failed”.
Red flag: Says “try and catch catch every error”, or believes fetch throws on a 404. Or shows the same “Added” message no matter what the server said.
19. API data typed as any
Question: Our online shop is written in TypeScript with “strict” turned on. The product page uses this code:
interface Product {
id: number;
name: string;
price: number;
}
async function loadProduct(id: number): Promise<Product> {
const res = await fetch(`/api/products/${id}`);
const data: any = await res.json();
return data;
}
function priceText(product: Product): string {
return product.price.toFixed(2) + ' EUR';
}
The product data comes from another team’s API. You see this in code review. What do you think? Is there a problem?
Short answer: The type any turns off type checking for that value. So the data is returned as a Product without any check. The Product type is only a promise that nobody verifies. TypeScript types are removed when the code is compiled, so nothing checks JSON from the network at runtime. We should type the data as unknown and validate it at the edge of our app (with a type guard or a schema library like Zod). Then wrong data fails early, in one place, with a clear message.
Hint (if the candidate says there is no problem): The TypeScript build is green. But in production the product page crashes with “product.price.toFixed is not a function”. Last week the backend team started sending the price as a string, like “19.99”.
Why does this happen? (step by step)
- The json method of a Response returns a Promise of any. Even if we do not write any ourselves, the value is any.
- A value of type any can be assigned to every type. So returning it as a Product is allowed, with no check.
- From now on, the compiler believes that the price property is a number.
- TypeScript types do not exist at runtime. The JavaScript that runs in the browser has no idea about the Product interface.
- The API sends “19.99”, a string. A string has no toFixed method, so the call crashes far away from the place where the bad data came in.
The fix: unknown plus validation
function isProduct(value: unknown): value is Product {
return (
typeof value === 'object' &&
value !== null &&
'id' in value && typeof value.id === 'number' &&
'name' in value && typeof value.name === 'string' &&
'price' in value && typeof value.price === 'number'
);
}
async function loadProduct(id: number): Promise<Product> {
const res = await fetch(`/api/products/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data: unknown = await res.json();
if (!isProduct(data)) {
throw new Error(`Bad product data from /api/products/${id}`);
}
return data; // now the compiler and the runtime agree
}
- The type unknown means “we do not know yet”. The compiler does not let us use it until we check it.
- The isProduct function is a type guard. It checks the real value at runtime. If it returns true, the compiler treats the value as a Product.
- If the API changes, we get one clear error at the edge, with the URL in the message. We do not get a strange crash deep inside the UI.
The same with a schema library (Zod):
import { z } from 'zod';
const ProductSchema = z.object({
id: z.number(),
name: z.string(),
price: z.number(),
});
type Product = z.infer<typeof ProductSchema>;
async function loadProduct(id: number): Promise<Product> {
const res = await fetch(`/api/products/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return ProductSchema.parse(await res.json()); // throws if the shape is wrong
}
The schema is written once, and the type comes from the schema. So the check and the type cannot drift apart.
Trade-off: Validation is more code and costs a little CPU time. For normal API responses this cost is very small. The win is big: bad data is stopped at the door.
Follow-up question: How do you stop any from coming back into the codebase?
Follow-up answer:
- The “strict” option includes noImplicitAny, but it still allows an any that is written on purpose, and it allows the any that comes from the json method or the JSON.parse method.
- Lint rules from typescript-eslint help: no-explicit-any, and the no-unsafe rules (for example no-unsafe-assignment, no-unsafe-member-access, no-unsafe-return) that catch an any value flowing into typed code.
- Types generated from an OpenAPI file help at compile time, but they still do not check the real response at runtime.
Red flag: Says “TypeScript checks the types, so the data is a Product.” Or fixes it only at the place of the crash, for example with Number(product.price), and leaves the any in place.
20. The compiler is quiet because of as
Question: This is part of the guest checkout in our online shop. The project uses TypeScript with “strict” turned on, and the build has no errors.
interface User {
id: number;
name: string;
email: string;
}
interface Order {
id: number;
items: { productId: number; quantity: number }[];
total: number;
}
const guest = {} as User;
guest.name = 'Guest';
sendReceipt(guest); // uses guest.email
const saved = localStorage.getItem('lastOrder');
const order = JSON.parse(saved ?? '{}') as Order;
console.log(`You have ${order.items.length} items`);
You see this in code review. What do you think? Is there a problem?
Short answer: The as keyword is a type assertion. It tells the compiler “trust me”. It does not convert or check anything at runtime. So the guest object really has no id and no email, but the compiler now thinks they are a number and a string. And the JSON.parse method returns any, so “as Order” accepts any data, even an empty object. We should build objects with a type annotation (then a missing field is a compile error), make the types honest, and validate parsed JSON instead of asserting it.
Hint (if the candidate says there is no problem): Some guests never get their receipt email. The request body to the receipt API has no email field at all. Also, new visitors who open the cart page see an empty page and the error “Cannot read properties of undefined (reading ‘length’)”.
Why does this happen? (step by step)
- TypeScript types exist only at compile time. They are removed from the JavaScript that runs.
- The as keyword changes only what the compiler believes. The value stays the same.
- TypeScript allows an assertion when the two types are related. An empty object type and User are related (every User is also an object), so “{} as User” is allowed.
- So guest.email is undefined at runtime. When the object is sent as JSON, the JSON.stringify method drops fields that are undefined, so the email is simply missing.
- When nothing is saved, the code parses the text “{}”. The result has no items property. “as Order” hides this, so reading the length of undefined crashes.
- In short: the error moved from compile time, where it is cheap, to production, where users see it.
The fix:
interface Guest {
name: string;
email: string;
}
function createGuest(name: string, email: string): Guest {
return { name, email }; // a missing field is a compile error here
}
function readLastOrder(): Order | null {
const saved = localStorage.getItem('lastOrder');
if (saved === null) return null;
try {
const data: unknown = JSON.parse(saved);
return isOrder(data) ? data : null;
} catch {
return null; // broken JSON
}
}
- Honest types: a guest has no id yet, so we use a Guest type instead of pretending it is a User.
- Annotation instead of assertion: when we return an object literal as a Guest, the compiler checks every field. If we forget the email, the build fails.
- Validate, do not assert: the result of JSON.parse is unknown. The isOrder function is a type guard that checks the fields at runtime (or we use a schema library like Zod).
- The return type says “maybe”: the type Order or null forces the caller to handle “no saved order”.
Trade-off: This is a little more code than one as keyword. But each line removes a crash that the compiler cannot see.
Follow-up question: Is the as keyword ever OK? And what about “as const” and the satisfies operator?
Follow-up answer:
- Rarely, when we really know more than the compiler and cannot prove it with a check. Even then, a runtime check is often easy. For example, after a DOM query we can check with instanceof HTMLInputElement instead of asserting.
- A double assertion, like “as unknown as Order”, is a big warning sign. It forces any type into any other type.
- “as const” is different and safe. It does not lie about a type. It only makes a literal value readonly and keeps its exact values.
- The satisfies operator checks that a value matches a type, without changing the value’s own type. It is a good replacement for many assertions on object literals.
Red flag: Says “as converts the object to a User”, or “the compiler is quiet, so it is safe”. Or fixes the crash with optional chaining everywhere instead of fixing the type.
21. A new payment kind nobody handles
Question: Our online shop shows the payment method on the checkout summary, in the order email and in the order history. All three places use this function:
type PaymentKind = 'card' | 'paypal';
interface Payment {
kind: PaymentKind;
cardLast4?: string;
paypalEmail?: string;
}
function paymentLabel(p: Payment): string {
switch (p.kind) {
case 'card':
return `Card ending in ${p.cardLast4}`;
case 'paypal':
return `PayPal (${p.paypalEmail})`;
default:
return '';
}
}
Next sprint, the team will add gift cards: a new kind ‘gift-card’ with a giftCardCode field. You see this in code review. What do you think? Is there a problem?
Short answer: There are two weak points. First, one interface with optional fields allows impossible states: a ‘card’ payment without cardLast4 compiles fine and shows “Card ending in undefined”. Second, the default branch returns an empty string, so when ‘gift-card’ is added, the compiler says nothing and the label is silently empty in three places. The fix is a discriminated union (each kind has its own required fields) plus an exhaustive check with the never type in the default branch. Then adding a new kind is a compile error in every switch that forgets it.
Hint (if the candidate says there is no problem): After the gift card release, order emails for gift card orders show an empty “Paid with:” line. There is no error in the logs and the build was green.
Why does this happen? (step by step)
- With optional fields, the type says “a card payment may or may not have cardLast4”. So the compiler cannot help when it is missing.
- A template string accepts undefined, so “Card ending in undefined” is valid TypeScript.
- The team adds ‘gift-card’ to the PaymentKind type.
- The switch has no case for it, but the default branch catches it and returns an empty string.
- The code still compiles. Nothing tells the developer that three places need a new case.
The fix:
type Payment =
| { kind: 'card'; cardLast4: string }
| { kind: 'paypal'; paypalEmail: string }
| { kind: 'gift-card'; giftCardCode: string };
function assertNever(value: never): never {
throw new Error(`Unhandled value: ${JSON.stringify(value)}`);
}
function paymentLabel(p: Payment): string {
switch (p.kind) {
case 'card':
return `Card ending in ${p.cardLast4}`; // p is the card type here
case 'paypal':
return `PayPal (${p.paypalEmail})`;
default:
return assertNever(p); // compile error: 'gift-card' is not handled
}
}
- Each member of the union has a literal kind field. This field is the discriminant.
- Inside each case, TypeScript narrows p to that one member. So cardLast4 is a required string there, and reading paypalEmail in the card case is a compile error.
- In the default branch, after all kinds are handled, p has the type never.
- When ‘gift-card’ is added, p in the default branch is the gift card type, not never. Passing it to the assertNever function is a compile error. The build tells us exactly where to add a case.
- If the server ever sends an unknown kind at runtime, we get a clear error, not an empty label.
Trade-off: Throwing in a label function can break a whole page for one unknown value. In a place like an email, you may prefer to log the error and show a safe text like “Other”. The compile-time check still stays.
Follow-up question: Not all our code uses switch. We also map each payment kind to an icon. How do you make that exhaustive too?
Follow-up answer:
const paymentIcons: Record<Payment['kind'], string> = {
card: '/icons/card.svg',
paypal: '/icons/paypal.svg',
'gift-card': '/icons/gift-card.svg', // remove this line and the build fails
};
- The Record type needs one key for every kind. A missing key is a compile error.
- The typescript-eslint project also has a lint rule, switch-exhaustiveness-check, that reports a switch which does not cover all members of a union.
Red flag: Says “the default branch makes it safe”. Or plans to “remember” to update all switches, or to add a comment. Or keeps one big interface with optional fields for every kind.
22. One 3 MB bundle for the whole shop
Question: Our online shop is a single-page app. About 70% of visitors use mid-range Android phones. The build makes one JavaScript file:
dist/assets/index-a1b2c3.js 3.1 MB (before compression)
The entry file and the home page look like this:
// main.js
import { renderHome } from './pages/home.js';
import { renderProduct } from './pages/product.js';
import { renderCheckout } from './pages/checkout.js';
import { renderAdmin } from './pages/admin.js';
const routes = {
'/': renderHome,
'/product': renderProduct,
'/checkout': renderCheckout,
'/admin': renderAdmin,
};
routes[location.pathname]?.();
// pages/home.js
import moment from 'moment';
import Chart from 'chart.js/auto';
export function renderHome() {
document.querySelector('#updated').textContent = moment().format('D MMM YYYY');
drawDealsChart(Chart); // a small chart at the bottom of the page
}
You see this in code review. What do you think? Is there a problem?
Short answer: Every visitor downloads, parses, compiles and runs the JavaScript of all pages, including admin and checkout, before the home page can respond. On a mid-range phone this is seconds of main-thread work. The fix: split the code by route with dynamic import, load heavy libraries only when they are needed (the chart only when it scrolls into view), replace libraries with built-in browser features when we can (the Intl API for dates), and measure the bundle with an analyzer and a size budget.
Hint (if the candidate says there is no problem): Lighthouse on mobile shows a slow LCP, a high Total Blocking Time and the advice “Reduce unused JavaScript”. Users say: “I tap Add to cart on the home page and nothing happens for a moment.”
Why does this happen? (step by step)
- The browser must download 3.1 MB. Compression makes the transfer smaller, but after unpacking, the browser still has to parse and compile all 3.1 MB.
- Parsing, compiling and running JavaScript use the main thread. While it is busy, the page cannot react to taps. This hurts INP.
- A mid-range phone has a much slower CPU than a developer laptop. The same work takes several times longer.
- A static import at the top of a file puts that code in the same bundle. The bundler cannot know that the admin page is needed only by a few staff members.
- The moment library is large and does not work well with tree shaking. We use it for one date.
- The chart.js/auto entry registers every chart type and every plugin, and the chart is at the bottom of the page where many users never scroll.
The fix:
- Split by route. Each dynamic import becomes its own file (a “chunk”). Vite, webpack, Rollup and esbuild all do this.
// main.js (each page module now exports a render function)
const routes = {
'/': () => import('./pages/home.js'),
'/product': () => import('./pages/product.js'),
'/checkout': () => import('./pages/checkout.js'),
'/admin': () => import('./pages/admin.js'),
};
routes[location.pathname]?.().then((page) => page.render());
- Use the platform for dates. The Intl API is built into the browser, so it costs zero bytes.
const updated = document.querySelector('#updated');
updated.textContent = new Intl.DateTimeFormat('en-GB', { dateStyle: 'medium' }).format(new Date());
- Load the chart only when it is needed.
const chartBox = document.querySelector('#deals-chart');
const observer = new IntersectionObserver(async (entries) => {
if (!entries[0].isIntersecting) return;
observer.disconnect();
const { default: Chart } = await import('chart.js/auto');
drawDealsChart(Chart, chartBox);
});
observer.observe(chartBox);
Chart.js also lets you import and register only the chart types you use, instead of chart.js/auto. That makes the chunk smaller again.
-
Help tree shaking. The bundler removes exports that nobody imports. This works with ES modules (import and export), and when the package says it has no side effects. A library that is one big object, like moment, cannot be shaken. Prefer libraries with small named imports, for example the format function from date-fns.
-
Measure and guard. Look inside the bundle with an analyzer (for example rollup-plugin-visualizer or webpack-bundle-analyzer). Add a size budget to CI so the bundle cannot quietly grow again.
Trade-off: More chunks mean an extra request when the user goes to another page, so there is a small delay. Do not split into hundreds of tiny files. Split by route and by heavy feature.
Follow-up question: After the split, opening a product page waits about 400 ms for its chunk on a slow network. What can you do?
Follow-up answer:
- Start loading the chunk before the user needs it. For example, call the import function when the user’s pointer enters a product link, or when the browser is idle.
- The browser keeps loaded modules in a map. When the real navigation calls the same import later, the module is already there, so it is instant.
- For chunks that the current page will surely need, a modulepreload link in the head lets the browser fetch them early.
Red flag: Says “gzip makes it small, so it is fine”, or “our users have fast internet”. Or measures only on a fast laptop with a fast network.
23. Read, write, read, write: 500 product cards
Question: The category page of our online shop shows up to 500 product cards in a grid. Product titles have different lengths, so a teammate wrote this code to make each card tall enough. It runs when the page loads and on every resize event of the window:
function fixCardHeights() {
const cards = document.querySelectorAll('.product-card');
for (const card of cards) {
const title = card.querySelector('.product-title');
card.style.height = `${title.offsetHeight + 240}px`;
}
}
fixCardHeights();
window.addEventListener('resize', fixCardHeights);
The 240 px is room for the image, the price and the button. You see this in code review. What do you think? Is there a problem?
Short answer: This is layout thrashing (forced synchronous layout). In every loop step we read offsetHeight, which needs an up-to-date layout. But in the step before, we wrote a new height, which made the layout out of date. So the browser has to calculate the layout again on every step: about 500 layouts in one task instead of one. The fix is to do all reads first and then all writes. Even better, remove the JavaScript: CSS Grid and Flexbox already size cards to their content.
Hint (if the candidate says there is no problem): In the DevTools Performance panel, page load has one long task full of purple “Layout” blocks, with the warning “Forced reflow”. When the user rotates a phone or resizes the window, the page freezes for a moment. With 20 test cards nobody noticed.
Why does this happen? (step by step)
- Normally the browser is lazy in a good way. JavaScript can change many styles, and the browser calculates style and layout once, later, before it paints the next frame.
- But some properties must return a correct size or position right now: offsetHeight, offsetTop, clientWidth, scrollHeight, the getBoundingClientRect method and others.
- If a style changed since the last layout, reading one of them forces the browser to do the layout now, in the middle of our JavaScript. This is a forced layout (also called forced reflow).
- Step 1 of the loop reads a title height, then writes a card height. The layout is now out of date.
- Step 2 reads the next title height. The browser must run layout again, because the card above changed and may have moved everything after it.
- This repeats about 500 times. Each layout works on a big page, so the total work grows much faster than the number of cards.
- All of this happens on the main thread, in one long task. The page cannot scroll or react to taps, so INP gets worse. And the resize event can fire many times per second, so the whole thing runs again and again.
Fix 1: read everything, then write everything
function fixCardHeights() {
const cards = [...document.querySelectorAll('.product-card')];
// 1. Read all sizes: one layout
const heights = cards.map((card) => card.querySelector('.product-title').offsetHeight);
// 2. Write all sizes: no reads in between
cards.forEach((card, i) => {
card.style.height = `${heights[i] + 240}px`;
});
}
- The first read forces one layout. All other reads use the same fresh layout, so they are cheap.
- The writes only mark the layout as out of date. The browser calculates it once, before the next paint.
- So we go from about 500 layouts to about 2.
Fix 2 (better): let CSS do it
The code sets each card to “title height plus the rest”. That is the normal height of a card that grows with its content. CSS already does this, and Grid can also make all cards in one row the same height:
.product-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 16px;
}
.product-card {
display: flex;
flex-direction: column;
}
.product-card .buy-button {
margin-top: auto; /* push the button to the bottom of the card */
}
- Grid items stretch to the height of their row by default, so cards in one row are equal.
- No JavaScript runs on load or on resize. The browser does the layout once, in its normal pipeline.
- The magic number 240 is gone, so a bigger image or a longer price text cannot break the design.
- For a very long list, the content-visibility property with the value auto can also let the browser skip the rendering work of cards that are far off screen.
Trade-off: Fix 1 keeps the JavaScript and is a quick safe change. Fix 2 needs a small CSS refactor, but it removes the whole problem and the resize handler.
Follow-up question: In a bigger app the reads and the writes are in different modules, which you cannot simply merge. How do you avoid thrashing then?
Follow-up answer:
- Separate the phases. Do all reads now, and schedule all writes together in a requestAnimationFrame callback, which runs before the next paint. Some teams use a small read-and-write queue for this (the fastdom library is one example).
- Never read a size inside a requestAnimationFrame callback right after a write in the same callback. That forces the layout again.
- If you need to react to size changes, use a ResizeObserver. Its callback gets the new sizes from the browser’s own layout step, so you do not have to read them and force a layout.
Red flag: Says “500 is not many, computers are fast”. Or wraps the same read and write loop in requestAnimationFrame and thinks it is fixed. Or only adds a debounce to the resize handler and keeps the read-write mix.
24. A lazy hero image
Question: The home page of our online shop starts with a big banner image (the “hero”). On a phone, it fills most of the first screen. Marketing changes the banner every week through an API. Here is the code:
<section class="hero">
<img id="hero-img" alt="Autumn sale: up to 50% off" loading="lazy" width="1200" height="600">
</section>
<script src="/js/app.js" defer></script>
// app.js
const hero = document.querySelector('#hero-img');
fetch('/api/banner')
.then((res) => res.json())
.then((banner) => {
hero.src = banner.imageUrl; // a 400 KB JPEG
});
You see this in code review. What do you think? Is there a problem?
Short answer: The hero image is the biggest thing on the first screen, so it is almost surely the LCP element. But the browser cannot start downloading it until a long chain of steps is done: parse the HTML, download and run app.js, wait for the API, then (because of lazy loading) wait for layout to confirm the image is on screen. The fix: put the image URL directly in the HTML that the server sends, remove the lazy loading, give the image high fetch priority, and serve a right-sized modern format. Lazy loading is for images below the first screen.
Hint (if the candidate says there is no problem): Field data shows an LCP of about 5 seconds on mobile, at the 75th percentile. A good LCP is 2.5 seconds or less. In the network waterfall, the banner request starts very late, after app.js and after the banner API call. Lighthouse also warns that the LCP image was lazily loaded.
Why does this happen? (step by step)
- Browsers have a preload scanner. It reads the raw HTML very early and starts downloading the images, scripts and styles it finds. Our image tag has no src, so the scanner finds nothing.
- The app.js script has the defer attribute, so it runs only after the HTML is fully parsed. Before that, it must be downloaded.
- Then the script calls the banner API. That is another full round trip, often hundreds of milliseconds on mobile.
- Only now is the src set. Because of the loading attribute with the value lazy, the browser first needs layout to know whether the image is near the screen.
- Then the 400 KB JPEG downloads over a slow network.
- Each step waits for the step before it. The LCP is roughly the sum of all of them.
The fix:
The server (or the build) reads the current banner and writes it into the HTML:
<section class="hero">
<img
src="/images/banners/autumn-sale-800.avif"
srcset="/images/banners/autumn-sale-800.avif 800w,
/images/banners/autumn-sale-1200.avif 1200w"
sizes="100vw"
alt="Autumn sale: up to 50% off"
width="1200"
height="600"
fetchpriority="high">
</section>
- URL in the HTML: the preload scanner sees it in the first bytes of the page and starts the download at once. No JavaScript and no API call in the way. The weekly change still works, because the server writes the current banner into the page.
- No lazy loading: without the loading attribute, the browser loads the image right away (the default is eager).
- The fetchpriority attribute with the value high: tells the browser this image is more important than other images.
- The srcset and sizes attributes: the browser picks the file that fits the screen width and pixel density. So a small phone can get the 800 px version instead of the 1200 px one.
- A modern format: AVIF or WebP is usually much smaller than JPEG for the same quality.
- The width and height attributes: the browser keeps the right space before the image arrives, so the layout does not jump (no CLS).
If the hero must be a CSS background image, the preload scanner cannot see it in the HTML. Then add a preload link in the head:
<link rel="preload" as="image" href="/images/banners/autumn-sale-800.avif" fetchpriority="high">
Trade-off: High priority only works if you use it for one or two images. If every image is “high”, none of them is special. Keep lazy loading for the product images further down the page. There it saves data and bandwidth.
Follow-up question: The hero is now a carousel with 5 slides, but only the first slide is visible at the start. How do you load them?
Follow-up answer:
- The first slide is the LCP candidate: its URL in the HTML, no lazy loading, high fetch priority.
- The other 4 slides are not visible at the start: give them the loading attribute with the value lazy, or load them after the page is ready.
- Check which element really is the LCP: the DevTools Performance panel marks it, and the web-vitals library can report it from real users.
Red flag: Says “lazy loading always makes pages faster”. Or suggests a loading spinner on the banner. Or only says “compress the image” and does not see the chain of waiting steps.
25. Search title with innerHTML
Question: The search page of our online shop has an address like https://shop.example.com/search?q=laptop. At the top of the page we show what the user searched for:
const params = new URLSearchParams(location.search);
const query = params.get('q') ?? '';
document.querySelector('#search-title').innerHTML = 'Results for: ' + query;
You see this in code review. What do you think? Is there a problem?
Short answer: This is a DOM-based XSS (cross-site scripting) hole. The innerHTML property parses the string as HTML. The query comes from the URL, and anyone can make a URL. An attacker sends a link with HTML in the q parameter, and that HTML runs JavaScript inside our shop, in the victim’s session. The fix is the textContent property, which always treats the string as plain text. As a second layer, add a Content Security Policy.
Hint (if the candidate says there is no problem): A security researcher sends us this link. When we open it, an alert box shows our own domain name:
https://shop.example.com/search?q=<img src=x onerror="alert(document.domain)">
Why does this happen? (step by step)
- The innerHTML property gives the string to the HTML parser, which turns it into real elements.
- The attacker’s string becomes an image element with a broken src. The image fails to load, so its onerror handler runs the attacker’s JavaScript.
- A script tag that is inserted with innerHTML does not run. But event handler attributes like onerror do run. So “we block script tags” is not a defense.
- The attacker’s code runs as part of our page. It can read the page, read localStorage, call our API with the user’s cookies, or show a fake login form.
- The attacker only needs the victim to click a link: in an email, an ad or a chat message.
The fix:
const params = new URLSearchParams(location.search);
const query = params.get('q') ?? '';
const title = document.querySelector('#search-title');
title.textContent = `Results for: ${query}`;
If we want the query in bold, we build the elements ourselves:
const strong = document.createElement('strong');
strong.textContent = query;
title.replaceChildren('Results for: ', strong);
- The textContent property never parses HTML. The attacker’s string is shown as harmless text.
- Other dangerous places work the same way as innerHTML: outerHTML, the insertAdjacentHTML method and the document.write method. Also a link whose href comes from user input can be a “javascript:” URL.
Second layer: Content Security Policy
Content-Security-Policy: script-src 'self'; object-src 'none'; base-uri 'none'
- With this header, the browser runs only script files from our own origin.
- Inline scripts and inline event handlers like onerror are blocked. So even if one innerHTML bug slips through, the attack fails.
- Browsers that support Trusted Types can go further: the directive require-trusted-types-for with the value ‘script’ makes them refuse plain strings in innerHTML.
- CSP is a safety net, not the fix. The fix is still textContent.
Follow-up question: Product descriptions are written by sellers, and they must keep bold text and lists. So we really need to insert HTML. What do you do?
Follow-up answer:
- Sanitize the HTML with a well-tested library such as DOMPurify. Allow only a short list of tags (for example bold, italic, lists, paragraphs) and no attributes like event handlers.
- Sanitize on the server when the seller saves the text, and again in the browser before inserting. The stored data may come from older versions or other tools.
- Never write your own regular expression to “remove bad tags”. There are too many tricks.
- Keep the CSP as a second layer.
Red flag: Says “we replace the less-than and greater-than signs with our own code”, or “script tags do not run with innerHTML, so it is safe”, or “the value is in our own URL, so it is trusted”.
26. Login token in localStorage
Question: In our online shop, users can see their saved addresses and order history, and they can buy again with a saved card. After login, the frontend does this:
// after login
const { accessToken } = await res.json(); // a JWT, valid for 30 days
localStorage.setItem('token', accessToken);
// every API call
fetch('/api/orders', {
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
});
Every page also loads a support chat widget from another company. The script URL always gives the vendor’s latest version:
<script src="https://cdn.chat-widget.example/widget.js"></script>
You see this in code review. What do you think? Is there a problem?
Short answer: Any JavaScript that runs on our page can read localStorage, and a third-party script runs with exactly the same power as our own code. If the vendor’s file is changed by an attacker, or if our page has any XSS bug, the attacker can read the token and send it to their own server. Then they can use it from their own computer for up to 30 days. Better: the server keeps the session in an HttpOnly, Secure, SameSite cookie that JavaScript cannot read, with a short lifetime. And we limit what third-party code can reach (an iframe on another origin, or a pinned version with Subresource Integrity, plus a Content Security Policy).
Hint (if the candidate says there is no problem): The chat vendor emails all customers: “Our CDN was compromised for six hours last night.” During those hours our users loaded the widget as usual.
Why does this happen? (step by step)
- Storage like localStorage belongs to an origin (for example https://shop.example.com). Every script running in that page shares it.
- A script tag that loads a file from another domain still runs in our origin. What matters is the page, not where the file came from.
- So the widget code, or anyone who changes it, can call localStorage.getItem with the key “token” and send the value away with a simple fetch.
- A bearer token works for anyone who holds it. It is not tied to the user’s browser.
- It is valid for 30 days. Logging out in the browser only deletes the local copy. The stolen copy still works, unless the server can revoke it.
The fix:
- The server sets the session in a cookie:
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=3600
- HttpOnly: JavaScript cannot read the cookie, so a script cannot send it away.
- Secure: the cookie is sent only over HTTPS.
- SameSite=Lax: the cookie is not sent with most requests that come from other sites. This helps against CSRF.
- Short lifetime: for example one hour, renewed while the user is active. The server can also end a session at any time.
- The frontend does not touch the token at all. For same-origin requests, fetch sends the cookie by default:
const res = await fetch('/api/orders');
- Reduce the power of third-party code:
- Best: load the chat inside an iframe that is served from the vendor’s own origin. Code in that iframe cannot read our page or our storage.
- If it must be a script, load a fixed version and add an integrity hash (Subresource Integrity). If the file changes, the browser refuses to run it.
<script src="https://cdn.chat-widget.example/widget.4.2.1.js"
integrity="sha384-HASH_OF_THIS_FILE"
crossorigin="anonymous"></script>
- Add a Content Security Policy that lists the few script origins we trust.
To be honest about HttpOnly: it does not make XSS harmless. Bad code in the page can still send requests while the page is open, and the browser adds the cookie. But it cannot steal the session and use it later from another computer. So we still prevent XSS first. HttpOnly limits the damage.
Trade-off: Cookies bring CSRF back as a risk, and they need more setup if the API lives on a different site. For most shops, the cookie session is still the safer default.
Follow-up question: We move to HttpOnly cookies. What new risk do we have to handle, and how?
Follow-up answer:
- CSRF: another site makes the user’s browser send a request to our API, and the browser adds our cookie.
- The SameSite attribute with the value Lax blocks the cookie on cross-site POST requests. It still sends it when the user follows a normal link to us, so a GET request must never change data.
- For actions that change data, also check the Origin header on the server, or use a CSRF token.
- Set SameSite yourself. Do not count on each browser’s default.
Red flag: Says “we encrypt the token in localStorage” (the key is in the same JavaScript). Or “sessionStorage is safer” (every script can read it too). Or “the vendor is a big company, so its script is safe”.
27. Fixing CORS with a star
Question: The frontend of our online shop runs on https://shop.example.com. The API runs on https://api.example.com. Login uses a session cookie. The cart page does this:
const res = await fetch('https://api.example.com/cart', { credentials: 'include' });
The browser console showed a CORS error. A teammate “fixed” it by adding this header to every API response:
Access-Control-Allow-Origin: *
He also says: “If it still fails, I will make the server copy the Origin header of each request into Access-Control-Allow-Origin, and add Access-Control-Allow-Credentials: true.” What do you think of both steps? And what is CORS, really?
Short answer: CORS is not a wall that protects the server. It is how a server tells the browser: “this other origin may read my responses”. The browser enforces the Same-Origin Policy and reads these headers. With credentials (cookies), the browser refuses the wildcard star, so step one still fails. Step two (copy any Origin and allow credentials) works, but it is dangerous: then other websites can read a logged-in user’s cart, orders and address, as long as the browser sends the cookie. The right fix is an allowlist of exact origins with Allow-Credentials true and the Vary: Origin header. Or even simpler: serve the API from the same origin (for example shop.example.com/api), so CORS is not needed at all.
Hint (if the candidate says there is no problem): After step one, the console still shows this error:
The value of the 'Access-Control-Allow-Origin' header in the response must not be
the wildcard '*' when the request's credentials mode is 'include'.
What CORS really is (step by step)
- An origin is scheme + host + port. The addresses shop.example.com and api.example.com have different hosts, so they are different origins.
- The Same-Origin Policy: a script from one origin may send requests to another origin, but it may not read the response, unless the other origin allows it.
- The server allows it with response headers. The browser checks them. If they are missing or wrong, the browser hides the response from our JavaScript and shows a CORS error. Note: the request may still have reached the server and run.
- For some requests the browser first sends a preflight: an OPTIONS request that asks for permission. For example a JSON body with the Content-Type header set to application/json, a custom header, or the PUT and DELETE methods. The server must answer it with the allowed methods and headers.
- With credentials the rules are stricter: Access-Control-Allow-Origin must be the exact origin, not the star, and Access-Control-Allow-Credentials must be true.
- CORS protects users in their browser. Tools like curl or Postman ignore it completely. So it is not access control for the API.
Why step two is dangerous:
- A logged-in user visits an evil page. That page runs a fetch to https://api.example.com/orders with credentials included.
- If the cookie is sent with that request, the API gets a request that looks like the real user. This happens if the cookie has SameSite=None, or if the evil page runs on another subdomain of example.com (for example an old, hacked blog.example.com), which counts as the same site.
- The server copies the evil Origin into Allow-Origin and says credentials are allowed.
- So the browser lets the evil page read the answer: names, addresses, orders.
The fix:
# Response to a request with Origin: https://shop.example.com
Access-Control-Allow-Origin: https://shop.example.com
Access-Control-Allow-Credentials: true
Vary: Origin
# Response to the preflight (OPTIONS) request
Access-Control-Allow-Origin: https://shop.example.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type
Access-Control-Max-Age: 600
Vary: Origin
- The server keeps a short list of allowed origins and compares the Origin header with exact string equality. A check like “ends with example.com” is a bug: evil-example.com also ends with it.
- The Vary: Origin header tells caches that the answer depends on the Origin, so one origin’s answer is not reused for another.
- The Max-Age header lets the browser remember the preflight answer for a while (browsers may use a lower limit).
- Simpler option: put the API behind the same origin with a reverse proxy, at https://shop.example.com/api. Same origin means no CORS and no preflight. In local development, the dev server’s proxy (for example in Vite) does the same.
- For truly public data with no cookies (for example a public product catalog), the star is fine.
Follow-up question: Does CORS protect our API from CSRF?
Follow-up answer:
- No. CORS controls who can read the response. It does not stop the request from being sent.
- A “simple” request, like a normal form POST, is sent with cookies without any preflight. The server runs it, for example “change the delivery address”, even if the evil page cannot read the answer.
- A preflight does block some non-simple requests, but do not build security on that side effect.
- Real CSRF protection: SameSite cookies, checking the Origin header on the server, and CSRF tokens for actions that change data.
Red flag: Says “CORS is a server security feature; Postman works, so the server is fine”. Or suggests a browser extension that turns CORS off. Or says the star is fine for everything, including requests with cookies.
28. A cart modal made of divs
Question: When the user clicks the cart icon in our online shop, a cart window opens over the page with a dark background. Here is the code:
<button id="open-cart" type="button">Cart (2)</button>
<div class="modal" id="cart-modal" hidden>
<div class="modal-box">
<h2>Your cart</h2>
<!-- cart items -->
<div class="close" onclick="closeCart()">×</div>
<a href="/checkout">Checkout</a>
</div>
</div>
.modal {
position: fixed;
inset: 0;
background: rgb(0 0 0 / 0.5);
}
document.querySelector('#open-cart').addEventListener('click', () => {
document.querySelector('#cart-modal').hidden = false;
});
function closeCart() {
document.querySelector('#cart-modal').hidden = true;
}
It looks right with a mouse. You see this in code review. What do you think? Is there a problem?
Short answer: It looks like a modal, but for keyboard and screen reader users it is not one. Focus stays on the page behind. The Tab key moves through links hidden behind the dark layer. The Escape key does nothing. A screen reader does not announce a dialog and can still read the page behind. And the close “button” is a div: it cannot get focus, it has no name, and the keyboard cannot press it. The fix is the native dialog element opened with its showModal method. It makes the rest of the page inert, moves focus inside, closes on Escape, and tells assistive technology that a dialog is open. The close control must be a real button with an accessible name.
Hint (if the candidate says there is no problem): A keyboard user opens the cart and presses Tab. The focus goes to the links of the page behind the dark layer, and the user cannot see where it is. A screen reader user clicks “Cart” and hears nothing new. Escape does not close the cart.
Why does this happen? (step by step)
- A div with a dark background is only a picture. The browser does not know that it is a modal.
- Focus stays on the “Cart” button. The next Tab goes to the next element in the page, which is often behind the overlay.
- Screen readers use the accessibility tree. The page behind is still there and still active, and nothing says that a dialog opened.
- The close × is a div. It is not focusable, the Enter and Space keys do nothing, and it has no name. A screen reader may read only the × symbol, or skip it.
- There is no Escape key handler.
- So keyboard users cannot use the cart properly. This fails WCAG success criteria like 2.1.1 Keyboard and 2.4.3 Focus Order.
The fix:
<button id="open-cart" type="button">Cart (2)</button>
<dialog id="cart-dialog" aria-labelledby="cart-title">
<h2 id="cart-title">Your cart</h2>
<!-- cart items -->
<form method="dialog">
<button aria-label="Close cart">×</button>
</form>
<a href="/checkout">Checkout</a>
</dialog>
dialog::backdrop {
background: rgb(0 0 0 / 0.5);
}
const dialog = document.querySelector('#cart-dialog');
document.querySelector('#open-cart').addEventListener('click', () => {
dialog.showModal();
});
What the showModal method gives us for free:
- The dialog goes to the top layer, above everything else. No z-index fights.
- The rest of the page becomes inert: it cannot be clicked, reached with Tab, or read by a screen reader.
- Focus moves into the dialog (to the first focusable element, or to an element with the autofocus attribute).
- The Escape key closes the dialog. The browser fires a cancel event first, so we can react if needed.
- Screen readers announce a dialog, with the name taken from the heading through the aria-labelledby attribute.
- A button inside a form whose method is “dialog” closes the dialog with no JavaScript.
- When the dialog closes, browsers return focus to the element that had focus before, here the “Cart” button.
- The dark background is styled with the backdrop pseudo-element.
Note: the show method (without “Modal”) opens a non-modal dialog, and the page behind stays active. For a cart overlay we want showModal.
Trade-off: The dialog element has its own default styles (border, padding, centered position), so you need a little CSS to reset them. All current major browsers support it, so there is no reason to build a modal from divs anymore.
Follow-up question: The designer wants a click on the dark background to close the cart. How do you do that?
Follow-up answer:
dialog.addEventListener('click', (event) => {
if (event.target === dialog) dialog.close();
});
- A click on the backdrop is delivered to the dialog element itself.
- But a click on the dialog’s own padding is also delivered to the dialog. So give the dialog no padding and put the content in an inner wrapper. Then a click inside the content never has the dialog as its target.
- Keep the visible close button and the Escape key too. A backdrop click is an extra, not the only way out.
Red flag: Says “add tabindex to the div and it is accessible”. Or “add the dialog role” and stops there; a role alone does not move focus, trap Tab or handle Escape. Or “raise the z-index”.
29. An end-to-end test that sleeps
Question: This Playwright test checks the most important flow of our online shop: adding a product to the cart. It runs in CI on every pull request:
import { test, expect } from '@playwright/test';
test('user can add a product to the cart', async ({ page }) => {
await page.goto('/products/42');
await page.click('.product-actions > .btn.btn-primary');
await page.waitForTimeout(3000);
const count = await page.textContent('.header .badge');
expect(count).toBe('1');
});
You see this in code review. What do you think? Is there a problem?
Short answer: The fixed sleep is a guess. On a slow CI machine, 3 seconds is sometimes not enough, so the test fails. On a fast machine it wastes 3 seconds on every run. The value is read once, and a plain expect on a value does not retry. And the CSS class selectors break when the design changes, and they do not check what the user really sees. The fix: use user-facing locators (the getByRole method with the button’s name) and web-first assertions like toHaveText, which retry until the page is ready or a timeout is reached. Remove the waitForTimeout call.
Hint (if the candidate says there is no problem): On every developer’s laptop the test always passes. In CI it fails about once in ten runs with ‘Expected: “1”, Received: “0”’. Last week it also failed for a whole day because the designer renamed the btn-primary class.
Why does this happen? (step by step)
- After the click, the app sends a request to the cart API. The badge changes only when the answer comes back.
- That time is not fixed. The CI machine may be busy, the test server may be cold, and many tests run in parallel.
- The waitForTimeout method waits exactly 3 seconds, whatever happens. If the answer needs 3.2 seconds, the test reads “0”.
- The textContent method reads the text once. Then the expect call compares two plain values and does not retry.
- The selector depends on CSS classes and on the DOM structure. Both change for design reasons. It also does not prove that the user sees a button called “Add to cart”.
The fix:
import { test, expect } from '@playwright/test';
test('user can add a product to the cart', async ({ page }) => {
await page.goto('/products/42');
await page.getByRole('button', { name: 'Add to cart' }).click();
await expect(page.getByTestId('cart-count')).toHaveText('1');
});
- The getByRole method finds the button the way users and screen readers do: by its role and its visible name. If the button loses its name, the test fails, which is a small accessibility check for free.
- The click action waits automatically until the button is visible, enabled and stable.
- The toHaveText assertion retries until the text is “1” or until the timeout (5 seconds by default). So the test passes as soon as the badge updates, and waits longer only when it must.
- The getByTestId method uses a data-testid attribute. Use it for elements that have no good role or name, like a small counter badge.
- The test is now faster on fast machines and stable on slow ones.
Trade-off: Test IDs are extra attributes in the HTML, and they say nothing about accessibility. Prefer getByRole and getByLabel, and use test IDs only where those do not fit. Retries in the CI config (for example retries: 2) are fine for collecting traces with the “on-first-retry” trace option, but they must not hide a flaky test. Track flaky tests and fix the cause.
Follow-up question: The test passes when it runs alone, but sometimes fails when the whole suite runs in parallel: the badge shows “2”. Why, and what do you do?
Follow-up answer:
- Playwright gives each test a fresh browser context (new cookies and storage). But the cart lives on the server. If all tests log in as the same test user, another test may add to the same cart at the same time.
- Make the data isolated: create a new user (or a new guest cart) for each test, for example in a fixture that calls the API.
- Or mock the cart API for this UI test with the page.route method, so it does not depend on shared server data.
- Never make tests depend on the order in which they run.
Red flag: Says “increase the timeout to 10 seconds” or “add retries: 5”. Or blames CI: “it works on my machine, CI is just slow”.
30. Design an accessible product autocomplete
Question: Design the search box of our online shop with suggestions that appear while the user types. Each suggestion shows the product name, a small image and the price. The shop has about 200,000 products. About 60% of users are on phones, and some of them are on slow networks. The search box must work well with a keyboard and with screen readers. Explain your design step by step: behavior, network, accessibility, the different states, performance and mobile.
Short answer: Build it as the ARIA combobox pattern: a text input with the combobox role that controls a listbox of options. Focus stays in the input, and the aria-activedescendant attribute points to the highlighted option. The arrow keys, Enter and Escape work. On the network side: start after 2 characters, debounce about 250 ms, abort the old request, cache answers by query, and ask the server for a small answer (about 8 items) that it can cache too. Show clear loading, empty and error states, and announce the number of results in a polite live region. On mobile: the right input attributes, large touch targets, and a list that the on-screen keyboard does not hide.
Requirements and numbers:
- With 200,000 products we cannot send the catalog to the browser. The search runs on the server (or a search service), and each answer has only the top 8 suggestions.
- Without debounce, typing “headphones” sends 10 requests. With debounce, a normal typist sends 1 or 2.
- On a slow network a request can take a second or more. Answers can arrive out of order, so an old answer must never replace a newer one.
- The suggestions must feel quick: they appear soon after the user stops typing, and typing itself never feels slow.
The parts:
- Markup with roles
<label for="search">Search products</label>
<div class="combo">
<input id="search" type="search" role="combobox"
aria-expanded="false" aria-controls="search-list"
aria-autocomplete="list" autocomplete="off" enterkeyhint="search">
<ul id="search-list" role="listbox" aria-label="Product suggestions" hidden></ul>
</div>
<p id="search-status" class="visually-hidden" aria-live="polite"></p>
Each suggestion is a list item with the option role and its own id, for example opt-3. The highlighted one gets the aria-selected attribute with the value true.
- Keyboard
- Arrow Down and Arrow Up: move the highlight. Set aria-activedescendant on the input to the id of the highlighted option. Real focus stays in the input, so the user can keep typing.
- Enter: open the highlighted product. With no highlight, go to the full search results page.
- Escape: close the list and set aria-expanded to false. If the list is already closed, it may clear the input.
- A click or tap on an option does the same as Enter.
- Network: debounce, abort, cache
const input = document.querySelector('#search');
const cache = new Map();
let controller = null;
let timer = null;
input.addEventListener('input', () => {
clearTimeout(timer);
const query = input.value.trim().toLowerCase();
if (query.length < 2) {
controller?.abort();
closeList();
return;
}
timer = setTimeout(() => suggest(query), 250);
});
async function suggest(query) {
controller?.abort(); // an older request must never draw over this one
if (cache.has(query)) {
render(query, cache.get(query));
return;
}
controller = new AbortController();
showLoading();
try {
const res = await fetch(`/api/suggest?q=${encodeURIComponent(query)}&limit=8`, {
signal: controller.signal,
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const items = await res.json();
cache.set(query, items);
render(query, items);
} catch (err) {
if (err.name !== 'AbortError') showError();
}
}
- The cache makes Backspace instant: “headp” was already asked. Keep it small, for example the last 50 queries. A Map keeps insertion order, so the first key is the oldest one to delete.
- The server answer is the same for every user and has no personal data, so the server can send a short Cache-Control lifetime (for example 60 seconds) and a CDN can cache popular queries.
- The answer is small: id, name, price and a small thumbnail URL. No full product objects.
- States
- Loading: keep the old list visible and show a small “Searching…” row. Do not clear the list on every key, or it will flicker.
- Empty: “No products for ‘xyz’”, plus a link to the full search page.
- Error: “Suggestions are not available right now.” Enter still opens the full search page, so search works even when suggestions fail.
- Live region: after each render, write a short message like “8 suggestions” or “No suggestions” into the polite live region. Debounce already keeps these messages from coming on every key.
- Rendering and safety
- Build options with the createElement method and the textContent property. Product names come from sellers, so innerHTML would be an XSS risk.
- To highlight the typed part, split the name into pieces and wrap the matching piece in a mark element that you create in code, still without innerHTML.
- At most 8 rows means rendering is cheap. The input handler only resets a timer, so typing stays fast and INP stays good.
- Mobile
- The input has type “search” and the enterkeyhint attribute with the value search, so the keyboard shows a search key. The autocomplete attribute with the value off stops the browser’s own suggestions from covering ours.
- Use a font size of at least 16 px in the input. Smaller text makes iOS Safari zoom in when the input gets focus.
- Make each row tall enough to tap easily, around 44 px.
- The on-screen keyboard takes about half of the screen. Limit the list height, or on small screens open the search as a full-screen panel with the input at the top.
Trade-offs:
- Debounce time: shorter feels faster but sends more requests. 200 to 300 ms is a common range. Measure it.
- Cache: prices in suggestions can be a little old. That is fine, because the product page shows the real price. Keep the cache lifetime short.
- Client-side search: for a small catalog of a few thousand products, you could download all names once and filter in the browser, with no requests at all. For 200,000 products, no.
Follow-up question: How do you test this component?
Follow-up answer:
- Unit tests (for example Vitest): test the debounce with fake timers, and test that an aborted or older request never renders.
- Component tests (Testing Library): find the input by its combobox role, type with the user-event library, press the arrow keys and Enter, and check aria-expanded and aria-activedescendant.
- API mocks (MSW): return answers with a delay, return errors and empty lists, and send two answers in the wrong order to prove the race is handled.
- End-to-end (Playwright): one or two real flows in a real browser, plus an automated accessibility scan. Then test once by hand with a real screen reader, because automated tools do not catch everything.
Red flag: Only says “add debounce” and ignores old answers, states and accessibility. Builds the list from divs with click handlers and no roles. Moves real focus into the list, so the user cannot keep typing. Uses innerHTML to highlight the matching text.
31. The shop works offline, but users stay on an old version
Question: Our online shop added a service worker so it opens without a network. Since then, the support team gets messages like “I still see the old prices” and “the new checkout button is not there”, days after a release. This is the service worker:
// sw.js
const CACHE = 'shop';
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE).then((cache) =>
cache.addAll(['/', '/index.html', '/app.js', '/app.css']),
),
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then((hit) => hit || fetch(event.request)),
);
});
You see this in code review. What is wrong, and how do you fix it?
Short answer: Everything is cache first, forever. index.html, app.js and app.css have fixed names, so the cached copy is always used and the network is never asked. sw.js itself never changes between releases, so the browser never installs a new worker and never refills the cache. Even when sw.js does change, the new worker waits until all old tabs are closed, and the old cache is never deleted. Any GET to the API that reaches the cache would also be served stale. The fix: network first for pages with an offline page as fallback, cache first only for hashed file names, a build version in the cache name, delete old caches in activate, leave API and money data to the network, and show “A new version is ready” with skipWaiting when the user agrees.
Hint (if the candidate only talks about clearing the cache): The browser checks sw.js for changes when a page loads. What happens if sw.js is byte for byte the same after a release?
Why does this happen? (step by step)
- The first visit installs the worker and caches index.html, app.js and app.css.
- A new release changes app.js on the server. The URL is still /app.js.
- The user opens the shop. The fetch handler finds /index.html and /app.js in the cache and returns them. The network is never asked.
- The browser compares sw.js with the installed one. It is the same, so no new worker is installed and the cache is never refilled.
- The user stays on the old version until they clear the site data by hand.
The fix:
// sw.js
const VERSION = 'v42'; // the build writes this
const STATIC = `static-${VERSION}`;
const FILES = ['/offline.html', '/app.3f9a1c.js', '/app.8b2e7d.css'];
self.addEventListener('install', (event) => {
event.waitUntil(caches.open(STATIC).then((c) => c.addAll(FILES)));
});
self.addEventListener('activate', (event) => {
event.waitUntil(caches.keys().then((keys) => Promise.all(
keys.filter((k) => k !== STATIC).map((k) => caches.delete(k)),
)));
});
self.addEventListener('fetch', (event) => {
const req = event.request;
if (req.mode === 'navigate') {
// pages: network first, offline page as fallback
event.respondWith(
fetch(req).catch(() => caches.match('/offline.html')),
);
return;
}
if (FILES.includes(new URL(req.url).pathname)) {
// hashed files never change: cache first is safe
event.respondWith(
caches.match(req).then((hit) => hit || fetch(req)),
);
}
// everything else (the API, payment) goes to the network
});
self.addEventListener('message', (event) => {
if (event.data === 'skip-waiting') self.skipWaiting();
});
- Each build writes a new VERSION and new hashed names, so sw.js changes and the browser installs a new worker.
- Pages always come from the network when it is there, so a new index.html with new file names is loaded.
- activate deletes old caches.
- The page listens for a waiting worker, shows “A new version is ready. Reload?”, sends skip-waiting, and reloads once on controllerchange.
- The server should send sw.js with Cache-Control: no-cache, so CDNs do not keep an old copy.
Follow-up question: The business also wants “add to cart” to work offline. How would you do it?
Follow-up answer:
- Save each action in IndexedDB with its own id (an idempotency key), and show it as “waiting to send”.
- Send the queue on the online event. Background Sync can help, but only in Chromium-based browsers.
- The server uses the id to ignore a second copy of the same action.
- When the queue is sent, the product may be sold out or the price may have changed. Show the user the real result.
Red flag: “Tell the users to clear their cache”, or removing the service worker instead of fixing the cache rules.
32. Should we split the shop into micro frontends?
Question: Our online shop is one React app. One frontend team of 6 people works on it. The build takes 15 minutes and there are merge conflicts in the router and the store almost every week. The new tech lead proposes this plan:
- Split the app into 5 micro frontends: header, products, cart, checkout and account.
- Each one gets its own repo and its own pipeline.
- They are joined in the browser at run time with Module Federation.
- Each part may choose its own framework and library versions.
What do you ask first, and what do you advise? When would you say yes?
Short answer: Micro frontends solve a team problem: several teams that block each other’s releases. Here there is one team, so the plan adds cost (5 repos, 5 pipelines, shared library versions, harder end-to-end tests, a slower page) and does not remove the real pain. Ask first what really hurts: build time, conflicts, release waiting, or team growth. Fix those directly: faster builds (cache, build only what changed), clear modules with owners and import rules, split the big router and store files. Say yes only when there are several teams with clear business areas that need to release alone, and then start by splitting by page, with one framework, React shared as a singleton and a shared design system. Point 4 is a no in any case.
Hint (if the candidate just says yes): Who will release the header part, and who will release the checkout part? How many people will be on each “team”?
Questions to ask first:
- How many teams are there now, and how many next year?
- What exactly is slow or painful: the build, code review, waiting for releases, or bugs between areas?
- How often do we release, and how often does one area block another?
- How fast must the product page be on a cheap phone? (Every duplicated library makes it slower.)
What to do now (one team):
- One app, clear modules: a folder per business area (products, cart, checkout, account) with an owner and a public entry file. A lint rule stops imports into another area’s inner files.
- Split the conflict hot spots: each area registers its own routes and its own state, so the shared router and store files stay small.
- Faster build and tests: build cache, and in CI only run tests for areas that changed.
- Feature flags so unfinished work can be merged without blocking a release.
When to say yes (later):
- There are several teams, each owning a business area, and they really wait for each other.
- First split by page: /checkout becomes its own app behind the same domain. This is simple, and the sign-in cookie still works.
- Run-time composition (Module Federation) only for parts that must share one page, like the cart widget in the header.
- One framework. React and React DOM shared as singletons with one agreed version range. A versioned design system package.
- Small contracts: the URL, props and versioned browser events. No global store shared by all parts.
- Every remote has a fallback (an error boundary with a simple link), a size budget in CI and its own error monitoring.
Follow-up question: A year later the checkout team (4 people) wants to release on its own. The checkout page also shows a small “recommended products” box from the products team. How do you build it?
Follow-up answer:
- Checkout becomes its own app on /checkout, behind the same domain and reverse proxy.
- The recommended box is the only run-time part. It is loaded with Module Federation or as a web component, with a fallback that simply hides the box if it fails.
- The box must never block paying. Load it after the main checkout content, and give it a timeout.
- Contract tests between the two teams check the props and events of the box.
Red flag: “Micro frontends because big companies use them”, or letting each part pick its own framework and React version.