Irbisa · Cheatsheet

Web Platform & Security

How the browser renders a page, the DOM and events, CSS layout, accessibility, HTTP and caching, XSS, CSP and CORS, cookies, tokens and OAuth, storage

Middle Developer · 23 questions

  1. 01

    How does event propagation work in the DOM, and what is event delegation?

    A DOM event travels in three phases: capture (from window down to the target), target, and bubble (back up to window).

    const list = document.querySelector<HTMLUListElement>('#todos')!; // One listener for every current and future rowlist.addEventListener('click', (event) => {  const button = (event.target as Element).closest<HTMLButtonElement>('button[data-id]');  if (!button || !list.contains(button)) return;…
  2. 02

    What is the difference between <script>, <script async> and <script defer>?

    A plain <script> stops HTML parsing until it downloads and runs.

    <head>  <!-- blocks parsing: avoid in head -->  <script src="/legacy.js"></script>   <!-- run after parsing, in this order -->  <script defer src="/vendor.js"></script>…
  3. 03

    How does the browser decide which CSS rule wins when several rules match an element?

    The cascade compares, in order: origin and !important, cascade layers (@layer), specificity, and finally source order, where the later rule wins.

    @layer reset, vendor, app; @layer vendor {  #sidebar .button { color: gray; } /* (1,1,0), but in an earlier layer */}…
  4. 04

    When do you use Flexbox and when CSS Grid?

    Flexbox lays items out in one dimension (a row or a column) and lets the content size drive the layout; Grid lays out rows and columns at once, with the tracks defined by the container.

    /* One dimension: a toolbar */.toolbar {  display: flex;  align-items: center;  gap: 8px;}…
  5. 05

    What is the difference between localStorage, sessionStorage, cookies and IndexedDB?

    localStorage and sessionStorage are small synchronous string stores per origin (about 5 MB); localStorage persists, sessionStorage lives with the tab.

  6. 06

    What is the difference between GET, POST, PUT, PATCH and DELETE, and which of them are safe and idempotent?

    GET reads, POST creates or triggers an action, PUT replaces a resource with the body, PATCH changes part of it and DELETE removes it.

  7. 07

    Which HTTP status codes does a frontend developer meet most, and what is the difference between 401 and 403, or 301, 302 and 304?

    The first digit is the class: 2xx success, 3xx redirect, 4xx a problem with the request, 5xx a failure on the server.

  8. 08

    What changed from HTTP/1.1 to HTTP/2 and HTTP/3, and how does it affect bundling and domain sharding?

    HTTP/2 sends many requests in parallel over one TCP connection with compressed headers, and HTTP/3 moves the same model to QUIC over UDP, so one lost packet no longer stalls every stream.

  9. 09

    Given these response headers, which responses does the browser reuse without a request, which does it revalidate, and which does it never store?

    GET /assets/index-3f9c1a.jsCache-Control: public, max-age=31536000, immutable GET /index.htmlCache-Control: no-cacheETag: "v42" GET /api/meCache-Control: no-store GET /api/products?page=1Cache-Control: max-age=60, stale-while-revalidate=300

    The script is reused for a year without any request; index.html is stored but revalidated before every use, which costs only a 304; /api/me is never stored; the product list is reused for 60 s, then served stale for up to 300 s more while a background request refreshes it.

  10. 10

    What happens when you type a URL into the browser and press Enter?

    The browser resolves the domain through DNS, opens a TCP or QUIC connection, negotiates TLS, sends an HTTP request and receives HTML.

  11. 11

    How does the browser turn HTML and CSS into pixels (the critical rendering path)?

    The browser parses HTML into the DOM and CSS into the CSSOM, combines them into a render tree of visible nodes, computes each box's size and position (layout), draws the pixels of each layer (paint) and lets the GPU combine the layers into the final frame (composite).

  12. 12

    What is the difference between reflow and repaint, and what is layout thrashing?

    Reflow (layout) recalculates the size and position of elements and is the expensive one; repaint redraws pixels without changing geometry.

    const items = document.querySelectorAll<HTMLElement>('.item'); // wrong: each write invalidates layout, the next read forces it againitems.forEach((el) => {  el.style.height = `${el.offsetWidth / 2}px`;});…
  13. 13

    In what order does this code log when the user clicks the button?

    const outer = document.querySelector('#outer')!;const button = document.querySelector('#outer button')!; outer.addEventListener('click', () => console.log('outer bubble'));outer.addEventListener('click', () => console.log('outer capture'), { capture: true });button.addEventListener('click', () => console.log('button'));document.addEventListener('click', () => console.log('document'));

    outer capture, button, outer bubble, document: capture listeners run on the way down from window to the target, then the target's own listeners, then bubble listeners on the way back up.

  14. 14

    Why does z-index: 9999 sometimes fail to put an element on top?

    z-index only orders elements inside the same stacking context.

    .card {  transform: translateY(0); /* creates a stacking context */} .card .tooltip {  position: absolute;…
  15. 15

    What does it take to make a React app accessible?

    Semantic HTML first (button, a, label, headings, landmarks), everything usable from the keyboard with a visible focus, text alternatives for images and icon buttons, enough colour contrast, and focus management whenever the UI changes without a page load.

  16. 16

    Find the bug: keyboard and screen reader users cannot open the menu.

    function MenuTrigger({ onOpen }: { onOpen: () => void }) {  return (    <div className="menu-trigger" onClick={onOpen}>      <img src="/icons/menu.svg" />    </div>  );}

    A <div> with onClick is not focusable, ignores Enter and Space and has no role, and the icon has no text alternative, so keyboard users cannot reach it and a screen reader announces nothing useful.

  17. 17

    What is ARIA, and when should you not use it?

    ARIA is a set of HTML attributes (role, aria-*) that tell assistive technology what an element is, its state and its relations when HTML alone cannot.

  18. 18

    What is XSS, how does React protect you from it, and where does that protection end?

    Cross-site scripting (XSS) is attacker-controlled content running as script on your page, with the user's session.

    import DOMPurify from 'dompurify'; function Comment({ html, website }: { html: string; website: string }) {  const safeHtml = DOMPurify.sanitize(html);  // Allow-list the protocol: escaping does not make a URL safe  const safeUrl = /^https?:/i.test(website) ? website : undefined;…
  19. 19

    What is CORS, what is a preflight request, and how do you fix a CORS error?

    CORS is how a server tells the browser that JavaScript from another origin may read its responses: the browser enforces the same-origin policy and exposes the response only if it has a matching Access-Control-Allow-Origin.

    // Frontend: send cookies to another originconst res = await fetch('https://api.example.com/orders', {  method: 'POST',  credentials: 'include',  headers: { 'Content-Type': 'application/json' }, // not a simple request: preflight first  body: JSON.stringify({ productId: 42 }),…
  20. 20

    What is a Content Security Policy, and how would you roll one out on an existing React app without breaking it?

    CSP is a response header that tells the browser which scripts, styles, frames and connections a page may use, so injected markup cannot run even if it reaches the DOM.

    import { randomBytes } from 'node:crypto'; // Called for every HTML response: the nonce must be new each timeexport function cspFor() {  const nonce = randomBytes(16).toString('base64');  const policy = […
  21. 21

    What is CSRF, and how do SameSite cookies and CSRF tokens protect against it?

    Cross-site request forgery makes the user's browser send a request to your site from another site, with the user's cookies attached.

  22. 22

    Where should a single-page app store its auth token: localStorage, a cookie or memory?

    The safest common setup is a short-lived access token in memory plus a refresh token in an HttpOnly, Secure, SameSite cookie, or only a session cookie with a backend-for-frontend holding the tokens.

  23. 23

    How does signing in with an external provider work in a single-page app (the OAuth 2.0 authorization code flow with PKCE)?

    The app sends the user to the provider with the hash of a one-time secret, the provider sends the user back with a short-lived code, and the app exchanges the code plus the original secret for tokens.

    const AUTH = 'https://auth.example.com';const client = { client_id: 'web', redirect_uri: `${location.origin}/callback` };const b64url = (bytes: Uint8Array) =>  btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); export async function signIn() {…