Skip to main content
CodeOath
← All posts

JavaScript140 min total · 15 parts

JavaScript Core Concepts: Scope, Closures, `this`, and the Event Loop

Part 1 of 15 · ~2 min

Overview

Here is a small confession about JavaScript: most of the behavior that makes people mutter "wait, why did it do that" is not really about JavaScript being strange. It is about five mechanisms — scope, hoisting, closures, this, and the event loop — that you learned one at a time, in isolation, from five unrelated examples. Then you sat down to write real code, where all five fire at once in the same twelve lines, and the tidy separate boxes stopped helping.

So we are not going to do it that way here.

Instead, we are going to build one thing, together, from the first paragraph to the last: the search box at the top of this site. You know the one. You click it, start typing clos, and a little list drops down with matching articles in it. That is the whole project. It is deliberately unglamorous, and it is perfect for our purposes, because building it properly — not the demo version, the one that survives contact with real users — forces you through every single mechanism in this reference, in the order you would genuinely hit them.

Here is the version we start with. Twelve lines, and almost everything about it is subtly wrong:

function setupSearch() {
  const input = document.querySelector("#search-input");
  const resultsList = document.querySelector("#search-results");

  input.addEventListener("input", function () {
    const matches = ARTICLES.filter((a) => a.title.includes(input.value));
    resultsList.innerHTML = matches.map((a) => `<li>${a.title}</li>`).join("");
  });
}

setupSearch();

It works, in the way a paper airplane works. By the end of this reference it will remember what you typed, stop hammering the server on every keystroke, cache repeats, survive being torn down and rebuilt on navigation, hand each result row the right article, and keep the dropdown animation smooth while all of that happens. Each chapter takes one more bite out of the gap between those two versions, and the mechanism that closes the gap is the chapter's actual subject.

Work through it in order if you can — the search box genuinely accumulates, and a later chapter often fixes a bug an earlier one left sitting there on purpose. If you already know what you are looking for, the sidebar will drop you straight into it; each chapter names which version of the search box it is working on, so you can pick up the thread from anywhere.