Junior (0-2 years)HTML & CSS

What is the difference between cookies, localStorage and sessionStorage?

Quick answer

Cookies are sent to the server with every matching request and can expire; localStorage persists until cleared and stays in the browser; sessionStorage lasts for the current tab only.

Use cookies for authentication when the server must see the value (prefer HttpOnly, Secure and SameSite). Use localStorage for non-sensitive UI preferences that should survive a restart. Use sessionStorage for a wizard or draft that should die when the tab closes.

Both storage APIs are readable by JavaScript, so they are the wrong place for access tokens if you have XSS. Cookies set without HttpOnly have the same problem. All three are origin-scoped. localStorage has a typical quota of about 5 MB; cookies should stay tiny because they travel on every request.

  • What is the difference between em, rem, %, vh and vw in CSS?

    em is relative to the parent font size, rem is relative to the root font size, % is relative to the parent’s relevant size, and vh/vw are 1% of the viewport height or width.

  • What is the difference between async and defer on script tags?

    Both download the script without blocking HTML parsing. defer waits until parsing finishes and runs scripts in document order; async runs a script as soon as it is downloaded, which can be before or after parsing and in any order.

  • How does CSS specificity work?

    Specificity is the score the browser uses to decide which rule wins: inline styles beat IDs, IDs beat classes/attributes/pseudo-classes, and those beat elements. When scores tie, the last rule in the source wins.

  • How does the browser render a web page?

    The browser parses HTML into a DOM and CSS into a CSSOM, combines them into a render tree, computes layout (reflow), paints pixels and composites layers onto the screen.