← JavaScript core concepts for interviews

Lesson 5 of 5

The DOM, events and the browser

2 min read

Selecting and changing elements

js
const list = document.querySelector("#jobs");
const items = document.querySelectorAll(".job");   // static NodeList
const li = document.createElement("li");
li.textContent = "Frontend intern";                  // safe: never parses HTML
list.append(li);

Prefer textContent over innerHTML with user data: innerHTML can execute injected scripts (XSS).

Event propagation

Events travel in three phases: capture (window down to the target), target, then bubble (back up). Listeners run in the bubble phase by default.

  • e.stopPropagation() stops the event going further up.
  • e.preventDefault() stops the browser's default action (following a link, submitting a form).

Event delegation

Attach one listener to a parent instead of one per child. It works for items added later and uses less memory.

js
document.querySelector("#jobs").addEventListener("click", (e) => {
  const btn = e.target.closest("button[data-id]");
  if (!btn) return;
  apply(btn.dataset.id);
});

Debounce vs throttle

  • Debounce: run after the user stops for N ms (search box, resize end).
  • Throttle: run at most once every N ms (scroll position, mouse move).
js
function throttle(fn, ms) {
  let last = 0;
  return (...args) => {
    const now = Date.now();
    if (now - last >= ms) { last = now; fn(...args); }
  };
}

Storage

SizeLifetimeSent to server?
Cookies~4 KBset by expiryyes, with every request
localStorage~5 MBuntil clearedno
sessionStorage~5 MBuntil the tab closesno

Never store secrets or auth tokens where page scripts can read them if you can use an HttpOnly cookie instead.

How a page loads (a favourite question)

  1. DNS lookup, TCP + TLS handshake, HTTP request.
  2. The browser parses HTML into the DOM and CSS into the CSSOM.
  3. Scripts block parsing unless marked defer (run after parsing, in order) or async (run when downloaded, any order).
  4. DOM + CSSOM → render tree → layout (sizes and positions) → paint → composite.

Changing layout properties (width, top) triggers layout again (expensive); transform and opacity can be animated cheaply on the compositor.

Modules

ES modules (import / export) are the standard. Named exports vs default export; modules run in strict mode, have their own scope and are loaded once. CommonJS (require, module.exports) is the older Node system.

Check yourself

  • What is event delegation and why is it useful?
  • defer vs async on a script tag?
  • Why is innerHTML with user input dangerous?

Sign up free to save your progress.