▚ The Software Engineer's Field Manual
Chapter E11 · Standalone language track

JavaScript Primer — From Zero to Working Code

"Ten hours from a blank file to a browser that does what you tell it — no installs, no frameworks, no copying."

~10 hours For: freshers and anyone new to JavaScript — no prior JS assumed Runs in any browser — nothing to install

01 · The hookThe Blank-File Test

Field report · Campus placement season

"My resume had three projects: a weather app, a to-do list, a portfolio site. All three worked — I'd followed the tutorials carefully, typed every line. In the machine round, the interviewer didn't open my GitHub. He opened an empty file and said: 'Make a button that counts how many times it's been clicked. Take your time.' I knew it was simple — that's what made it worse. I couldn't remember how a file becomes a page, how the page finds the button, how the button hears the click. Fifteen minutes of fumbling for syntax I had only ever pasted. The feedback email said: strong resume, could not build from a blank file."

— Tanvi R., fresh graduate — three weeks before she could

Tutorials build recognition — "yes, I've seen that line before." Interviews, jobs, and real projects demand recall — producing the line from nothing, because you know what each piece is for. This chapter is engineered for recall: every concept arrives as a runnable example you type yourself, every section ends with a predict-the-output exercise, and the lab is the blank-file test itself, scaled up. The Tanvi of ten hours later writes the twelve lines — not from memory, but because she knows what a variable, an event listener, and the DOM each do, so the lines reconstruct themselves.

Why JavaScript first? Cold math: it is the most widely deployed language on Earth — every browser tab on every phone and laptop is running a JavaScript engine right now, so your programs run on billions of machines with zero installation. It's the only language browsers speak natively, so every product with a screen eventually needs it. And it compounds with the rest of this track: TypeScript — JavaScript with type annotations — is the language of the admin UIs, dashboards, internal tools and BFF services that sit next to every backend estate, so a backend engineer who can read and write it stops being blocked at the edge of their own service.

Honest prerequisite check: this chapter assumes general computing literacy — you know what files and folders are, and you've used a browser. It does not assume you've programmed before. If you have (in any language), the early sections will go quickly; skim the prose, run the code, do the predict blocks anyway.

02 · Getting set upTwo Minutes, Honestly — The Browser Is the Runtime

Most languages make you install things before "hello world". JavaScript doesn't, because the browser you're reading this in is a JavaScript runtime. There are two ways in, and you'll use both constantly:

Way 1 — the console. Press F12 (Windows/Linux) or Cmd+Option+J (Mac) and click the Console tab. That's a live JavaScript prompt wired into the current page. Type a line, press Enter, see the result instantly. It's where you'll test every idea in this chapter:

console — your first three linesruns offline
// Open DevTools (F12) -> Console. Type each line, press Enter.
2 + 2                  // 4 -- the console echoes every result back
"java" + "script"      // "javascript" -- + joins strings together
document.title         // the tab's title -- you just reached into a live page

Way 2 — a file. Open any text editor (Notepad works; VS Code is nicer), save the block below as first.html, and double-click the file. Your browser opens it as a page and runs the script inside. This is the whole deployment story for everything in this chapter — a file and a double-click:

first.htmlruns offline
<!doctype html>
<meta charset="utf-8">
<title>My first page</title>

<h1 id="headline">Hello?</h1>

<script>
  // Everything between the script tags is JavaScript.
  // The browser runs it, top to bottom, the moment it reaches this tag.
  const headline = document.querySelector("#headline");
  headline.textContent = "Hello from JavaScript!";
  console.log("this line shows up in the console (F12)");
</script>
first.html a file on disk double-click browser parses HTML builds the page, top to bottom meets <script> JS engine runs your code line by line document.querySelector(…) — your code reaches back and edits the live page
Fig. E11.1 — The whole loop: the browser builds the page from your file, hands your script to the JS engine, and your code edits the page it lives in.

One paragraph on the second home, then we won't mention it again: Node.js (nodejs.org) is the same JavaScript engine lifted out of the browser, so JS can also run servers, command-line tools, and build scripts — it's how the language escaped the tab. Worth installing eventually; needed for exactly nothing here. Every example in this primer runs in a plain browser, because instant visual feedback is the best teacher a beginner can hire, and it's free.

03 · Core JavaScriptValues & Variables — The Nouns

A program is mostly nouns (values) and verbs (functions). The nouns come first. JavaScript's everyday values are numbers (one kind — no integer/decimal split), strings (text in quotes), booleans (true / false), and two flavors of "nothing" that trip up everyone once. You name values with const — or let when the name will be reassigned. You will also meet var in old code: never write it — it's the 1995 version that ignores { } blocks and causes bugs let was invented to fix (the full story is in Under the hood).

values_tour.js — paste into the consoleruns offline
// Paste the whole block into the console (or between <script> tags in any page).
const name = "Ada";        // const: this name is never reassigned -- your default
let score = 0;             // let: this one will be
score = score + 10;        // reassignment -- only legal because it's `let`

// One number type. Decimals and whole numbers are the same thing.
const price = 19.99;
const items = 3;
console.log(price * items);            // 59.97

// Template literals: backticks + ${...} -- how you'll build every string
console.log(`Hi ${name}, your total is ${(price * items).toFixed(2)}`);
// Hi Ada, your total is 59.97

// Two flavors of "nothing"
let unset;                 // declared but never given a value
console.log(unset);        // undefined -- "nobody ever assigned this"
const empty = null;        // null -- "deliberately empty", assigned on purpose

// typeof tells you what kind of value you're holding
console.log(typeof "hi", typeof 42, typeof true, typeof unset);
// string number boolean undefined

// Comparison: ALWAYS three equals signs.
console.log(5 === 5);      // true
console.log("5" === 5);    // false -- different types, honestly reported
console.log("5" == 5);     // true?! -- == silently CONVERTS types first.
// That conversion follows rules nobody should memorize. Rule for life: never ==.

Two habits to install on day one. First, const is the default and let is the exception — most values in well-written JS are named once and never reassigned, and const makes the intent visible. Second, === always, == never. The double-equals version coerces types before comparing (0 == "" is true), which turns typos into silent wrong answers. You've now seen the trap once; that's the last time this chapter writes ==.

🧠 Brain power

Predict all three outputs before pasting this into the console:

predict_1.js
const a = 10;
const b = "10";
console.log(a === b);
console.log(typeof (a + b));
console.log(`${a + 1}`);
Reveal the answer

false — a number and a string are never ===. Then string — when either side of + is a string, + means "join", so 10 + "10" is "1010". Then "11" — inside ${…} the math runs first (both numbers), and the template literal turns the result into text. The asymmetry to remember: + joins if a string is anywhere near it; -, *, / always do math.

04 · Core JavaScriptControl Flow — Decisions and Loops

Programs earn their keep by branching (if / else, switch) and repeating (for, for...of, while). The shapes below cover essentially every loop and branch you'll write this year — and the block ends with truthiness, the one rule here that genuinely surprises people, so run it rather than skimming it:

flow_tour.js — paste into the consoleruns offline
const scores = [72, 45, 91, 60];

// for...of -- "give me each item, in order". Your default loop.
for (const s of scores) {
  if (s >= 60) {
    console.log(`${s}: pass`);
  } else {
    console.log(`${s}: fail`);
  }
}

// The classic counted for -- when you genuinely need the index
for (let i = 0; i < scores.length; i++) {
  console.log(`question ${i + 1} scored ${scores[i]}`);
}

// while -- repeat until a condition flips
let retries = 3;
while (retries > 0) {
  console.log(`retrying… ${retries} left`);
  retries--;                     // shorthand for retries = retries - 1
}

// switch -- many branches on one value (each case needs its break)
const day = "sat";
switch (day) {
  case "sat":
  case "sun":
    console.log("weekend");
    break;
  default:
    console.log("weekday");
}

// TRUTHINESS: an if-condition doesn't need to BE true/false -- any value works,
// and exactly six values count as false:  false, 0, "" , null, undefined, NaN.
// Everything else -- everything -- is truthy.
if ("")  console.log("never prints");
if ("0") console.log("prints -- a non-empty string is truthy");
if ([])  console.log("prints -- an EMPTY ARRAY is truthy");   // the classic surprise
if ({})  console.log("prints -- an empty object is too");

The six falsy values are worth actually memorizing — false, 0, "", null, undefined, NaN — because "is this list empty?" written as if (list) is a bug: an empty array is truthy, so the check always passes. The honest spelling is if (list.length === 0). You'll use truthiness constantly for "did I get a value at all?" checks; just never for "is this container empty?".

Python readers passing through: Python's empty [] is falsy; JavaScript's is not. This single difference causes more cross-language bugs than any other line on this page.

🧠 Brain power

Predict the final number:

predict_2.js
let n = 0;
if ([])      n += 1;
if ("")      n += 10;
if (0.0)     n += 100;
if ("false") n += 1000;
console.log(n);
Reveal the answer

1001. The empty array is truthy (+1). The empty string is one of the six falsy values (skip). 0.0 is just 0 — falsy (skip). And "false" is a non-empty string — truthy (+1000) — the quotes make it text, and text with characters in it is always truthy, whatever it spells.

05 · Core JavaScriptFunctions — The Verbs, and Verbs as Values

A function is a named, reusable piece of behavior: values go in through parameters, one value comes back through return (no return means the caller gets undefined). JavaScript gives you two spellings — the classic declaration and the compact arrow function — and one idea that unlocks everything after this section: functions are values. You can store them in variables, put them in arrays, and hand them to other code to call later. Every button click you'll ever handle works exactly that way.

functions_tour.js — paste into the consoleruns offline
// A declaration: named, reusable, shows up by name in error traces
function greet(name, punctuation = "!") {     // = "!" is a default parameter
  return `Hello, ${name}${punctuation}`;
}
console.log(greet("Ada"));            // Hello, Ada!
console.log(greet("Ada", "?"));       // Hello, Ada?

// Arrow functions -- the compact spelling you'll use for short jobs
const double = (x) => x * 2;          // one expression: the result returns itself
const area = (w, h) => {              // with braces you must `return` explicitly
  const a = w * h;
  return a;
};
console.log(double(21), area(3, 4));  // 42 12

// Functions are VALUES. Hand one to another function like any other argument.
function applyTwice(fn, x) {
  return fn(fn(x));                   // calls whatever function it was handed
}
console.log(applyTwice(double, 5));   // 20
// Note what we passed: `double` (the function itself), not `double(5)` (a result).
// This exact move -- "here's a function, call it when the time comes" -- is how
// buttons work:  button.addEventListener("click", yourFunction). Coming in §07.

// Closures: an inner function REMEMBERS the variables it was born next to
function makeCounter() {
  let count = 0;                      // private -- no outside code can touch it
  return () => {
    count += 1;                       // the arrow still sees `count`…
    return count;                     // …even after makeCounter has returned
  };
}
const next = makeCounter();
console.log(next(), next(), next());  // 1 2 3
const fresh = makeCounter();          // a brand-new private count
console.log(fresh());                 // 1

The closure at the end deserves a slow second read. makeCounter finishes and returns — yet the arrow function it produced still holds a working reference to count, and each call updates it. The rule: variables live as long as some function can still see them. It sounds academic until you notice it's how every interactive page keeps state — your click counter in §07 is literally a closure with a button attached.

🧠 Brain power

Using makeCounter from the block above, predict the output:

predict_3.js
const counterA = makeCounter();
const counterB = makeCounter();
counterA();
counterA();
console.log(counterA(), counterB());
Reveal the answer

3 1. Each call to makeCounter() creates a fresh, private count — counterA and counterB close over two different variables. A has been called three times by the final line; B once. If both had printed 3, closures would just be globals in disguise. They're not: each closure carries its own pocket of memory.

06 · Core JavaScriptArrays & Objects — The Two Workhorses

Nearly all real data is one of two shapes. An array is an ordered list — quiz questions, chat messages, search results. An object is a labeled record — { name: "Ada", score: 91 } — one thing with named fields. Real apps nest them: an array of objects is the single most common data shape in software, and it's exactly what every API on the internet returns. Arrays come with a family of built-in methods that each take a function (§05 paying out already) and run the loop for you — the big five below are 90% of the array code you'll ever write:

data_tour.js — paste into the consoleruns offline
const tags = ["js", "dom", "async"];
console.log(tags[0], tags.length);        // js 3   (positions start at 0)
tags.push("fetch");                       // add to the end
console.log(tags.pop());                  // fetch -- remove from the end

const scores = [72, 45, 91, 60];

// THE BIG FIVE -- each takes a function and applies it for you
const doubled  = scores.map(s => s * 2);         // transform EVERY item
console.log(doubled);                            // [144, 90, 182, 120]

const passing  = scores.filter(s => s >= 60);    // keep items that pass the test
console.log(passing);                            // [72, 91, 60]

const firstFail = scores.find(s => s < 60);      // the FIRST match, or undefined
console.log(firstFail);                          // 45

const anyPerfect = scores.some(s => s === 100);  // does at least ONE match?
console.log(anyPerfect);                         // false

const total = scores.reduce((sum, s) => sum + s, 0);  // boil down to ONE value
console.log(total);                              // 268

// Objects: labeled records
const player = { name: "Ada", score: 91, level: 3 };
console.log(player.name);          // dot access -- when you know the field name
console.log(player["score"]);      // bracket access -- when the name is data…
const field = "level";
console.log(player[field]);        // 3 -- …like here, where it lives in a variable

// Destructuring pulls fields out by name; spread copies with changes
const { name, score } = player;
console.log(name, score);                  // Ada 91
const levelUp = { ...player, level: 4 };   // copy player, override one field
console.log(levelUp.level, player.level);  // 4 3 -- the original is untouched

// JSON: arrays + objects, frozen into text for storage and networks.
// It looks like JavaScript because it IS JavaScript's literal syntax, borrowed.
const wire = JSON.stringify(player);
console.log(wire);                         // {"name":"Ada","score":91,"level":3}
console.log(JSON.parse(wire).name);        // Ada -- text back into a live object

Learn the big five as questions, not syntax: map — "same list, transformed"; filter — "which items qualify?"; find — "the first one that qualifies?"; some — "does anything qualify?"; reduce — "collapse the list to one value". Your quiz lab uses map to turn question objects into buttons and filter to collect wrong answers for the review screen — the methods aren't decoration, they're how data becomes UI.

Python readers: map/filter are your list comprehensions wearing method syntax; reduce is functools.reduce.

🧠 Brain power

Two of these lines are commonly confused. Predict all three outputs:

predict_4.js
const xs = [1, 2, 3, 4];
console.log(xs.map(x => x % 2 === 0));
console.log(xs.filter(x => x % 2 === 0));
console.log(xs.reduce((acc, x) => acc + x, 10));
Reveal the answer

[false, true, false, true], then [2, 4], then 20. map never changes the length — it transforms each item, so a true/false test produces a list of booleans, one per input. filter uses the same test to decide what to keep. And reduce started its running total at 10 (the second argument), then added 1+2+3+4. If you said [2, 4] for the map line, you've found the exact confusion this question exists to vaccinate.

07 · The DOMMaking Pages Do Things

This is where JavaScript stops being a calculator in a console and becomes the reason web pages feel alive. The browser turns your HTML into a live tree of objects — the Document Object Model — and hands your script its root as document. Every tag is a node in that tree. Change a node — its text, its style, its children — and the browser repaints the pixels instantly. That's the entire trick behind every interactive page ever shipped: find a node, listen for the user, change the tree.

document <html> <body> <h1> "Quiz time" <p id="status"> "272 left" <button> "Submit" status.textContent = "272 left" edits the highlighted node — the browser repaints those pixels immediately
Fig. E11.2 — Your HTML becomes a live tree; scripts edit nodes, the browser repaints. Interactivity is just tree surgery on a schedule the user sets.

You need exactly three tools. document.querySelector("…") finds a node (the string is a CSS selector: "#id", ".class", or a tag name like "button"). Properties like .textContent, .style, and .value read and change it. And addEventListener("click", fn) hands the browser a function of yours to call when the user acts — the functions-as-values move from §05, now load-bearing. First, the reading-and-writing half:

dom_tour.html — save and double-clickruns offline
<!doctype html>
<meta charset="utf-8">
<title>DOM tour</title>

<h1 id="title">DOM tour</h1>
<p class="note">The page is a tree of objects. Scripts edit the tree.</p>

<script>
  // Find nodes with CSS selector syntax: "#id", ".class", "tag"
  const title = document.querySelector("#title");
  title.textContent = "The DOM, live";          // change its text
  title.style.color = "rebeccapurple";          // change its style

  // Create a node from nothing and attach it to the tree
  const badge = document.createElement("p");
  badge.textContent = "This paragraph is not in the HTML file. View source and check.";
  document.body.append(badge);
</script>

Now the half that makes it interactive. Build-along one: a live character counter, the kind under every tweet box and comment field ever shipped. Type in the box and watch the counter track you — every keystroke fires an "input" event, the browser calls your function, your function edits the tree:

counter.html — save and double-clickruns offline
<!doctype html>
<meta charset="utf-8">
<title>Character counter</title>

<textarea id="draft" rows="4" cols="42" placeholder="Draft your post…"></textarea>
<p id="status">280 characters left</p>

<script>
  const draft  = document.querySelector("#draft");
  const status = document.querySelector("#status");

  // "input" fires on every keystroke, paste, and delete
  draft.addEventListener("input", () => {
    const left = 280 - draft.value.length;
    status.textContent = `${left} characters left`;
    status.style.color = left < 20 ? "crimson" : "";   // urgent when nearly out
  });
</script>

Build-along two — the interview question from the hook, solved for good. Read it once, then close the file and rebuild it from a blank page; that rebuild is the real exercise, and it's the first item in this chapter's Flex your memory:

clicker.html — save and double-clickruns offline
<!doctype html>
<meta charset="utf-8">
<title>Click counter</title>

<button id="clicker">Clicked 0 times</button>

<script>
  const btn = document.querySelector("#clicker");
  let count = 0;                        // state: outlives every click

  btn.addEventListener("click", () => {
    count += 1;                         // the closure from §05, earning rent
    btn.textContent = `Clicked ${count} times`;
  });
</script>
🧠 Brain power

Take dom_tour.html and move the entire <script> block above the <h1>. Reload. What happens, and why?

Reveal the answer

A console error: TypeError: Cannot set properties of null (setting 'textContent'). Fig. E11.1 explains it: the browser builds the tree top to bottom and runs your script the moment it reaches it — at which point the <h1> doesn't exist yet, so querySelector returns null. That's why the script sits at the bottom of every example here (the grown-up alternative, <script defer src="…">, means "run after the tree is complete"). This error will greet you many times; now you know it on sight.

08 · AsyncAsync JavaScript, Gently — Why the Browser Never Freezes

Here's the constraint that shapes the whole language: your JavaScript runs on one thread — one worker, one thing at a time — and it's the same thread the browser uses to repaint the page and respond to clicks. If your code stopped to wait for anything slow, the entire tab would freeze: no scrolling, no typing, grey "page unresponsive" banner. So JavaScript refuses to wait. Slow jobs are handed to the browser's machinery, your code moves on immediately, and the result comes back later as a function call. Picture a food truck with one cook:

timer setTimeout network fetch the user clicks, typing appliances run in parallel — when one finishes, a ticket joins the queue the order queue (callbacks waiting) click handler timer done response ready next ticket — only when hands are free the cook: your JS one thread, one dish at a time this pickup loop — finish the current code, take the next queued callback — is the event loop. The appliances wait in parallel; the cook never waits at all — which is why the page never freezes.
Fig. E11.3 — The event loop: one cook (your single-threaded JS), an order queue of finished callbacks, and appliances (timers, network, input) that work in parallel and never block the cook.

You've already cooked this way once — addEventListener is exactly "leave a ticket when the user acts". setTimeout(fn, ms) is the same shape for time: "in ms milliseconds, put fn in the queue." Its sibling setInterval(fn, ms) repeats until you call clearInterval — that pair is your quiz lab's countdown clock:

timers_tour.js — paste into the consoleruns offline
console.log("A — order taken");
setTimeout(() => console.log("B — 2s timer done"), 2000);
setTimeout(() => console.log("C — zero-delay timer"), 0);
console.log("D — next line already");
// Prints A, D, C, then (2s later) B.
// Even a 0ms timer goes through the QUEUE -- it can only run after the
// current code finishes. setTimeout means "no sooner than", never "exactly at".

// setInterval repeats; clearInterval stops it. (Your quiz timer, right here.)
const tick = setInterval(() => console.log("tick"), 1000);
setTimeout(() => { clearInterval(tick); console.log("stopped"); }, 3500);

Timers hand you a moment; networks hand you a value — and the value isn't ready when the line runs. JavaScript's answer is the promise: calling fetch(…) returns immediately, but what it returns is not the data — it's a receipt for data that's still being prepared. A receipt can be in exactly one of three states, and it settles exactly once:

pending receipt in hand, no value yet work succeeds → resolve(value) work fails → reject(error) fulfilled — value ready .then(fn) runs / await resumes rejected — error instead .catch(fn) runs / await throws a promise settles exactly once, then never changes state again
Fig. E11.4 — The promise lifecycle: pending until the browser finishes the work, then fulfilled (your .then/await gets the value) or rejected (your .catch/try gets the error) — exactly once.
promise_tour.js — paste into the consoleruns offline
// A promise built by hand, so you can watch the receipt settle.
const receipt = new Promise((resolve) => {
  setTimeout(() => resolve("your value, freshly cooked"), 1500);
});

console.log(receipt);                       // Promise { <pending> } -- the receipt itself!
receipt.then((value) => console.log(value)); // "when it settles, call me with the value"
// ~1.5s later: your value, freshly cooked

Chains of .then() work but read like plumbing. async / await is the readable spelling of the same machinery: marking a function async lets you write await receipt, which pauses that function only — the cook serves other tickets while yours waits — and resumes it with the value once the promise settles. If the promise rejects, await throws — which is why real fetch code wears a try/catch and shows a loading state. The full pattern, with fetch(), the browser's built-in way to call any web API:

quotes.html — needs the 2-line local serverruns offline
<!doctype html>
<meta charset="utf-8">
<title>Fetch demo</title>

<p id="out">Loading quotes…</p>   <!-- the loading state: shown until data lands -->

<script>
  // fetch() needs a web address, so this ONE example won't run from a double-click:
  // browsers block file:// pages from reading local files. The fix is a tiny local
  // server -- from this folder, run:   python3 -m http.server
  // then open:                        http://localhost:8000/quotes.html
  const out = document.querySelector("#out");

  async function load() {
    try {
      const res = await fetch("quotes.json");      // await: pause HERE until settled
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const quotes = await res.json();             // body text -> live array
      out.textContent = quotes[Math.floor(Math.random() * quotes.length)];
    } catch (err) {
      out.textContent = `Could not load quotes: ${err.message}`;  // honest failure UI
    }
  }
  load();
</script>
quotes.json — save next to quotes.htmlruns offline
["Simplicity is the soul of efficiency.",
 "First, solve the problem. Then, write the code.",
 "Make it work, make it right, make it fast."]

The same four lines call any public API on the internet — same receipt, same await, same try/catch, just a bigger kitchen on the other end. GitHub's API needs no key and allows requests from anywhere:

api_tour.js — paste into the consoleneeds internet — no key
// The console allows await at the top level (inside a script, wrap in an async fn).
const res  = await fetch("https://api.github.com/users/octocat");
const user = await res.json();       // the API returns JSON -- §06 pays out
console.log(`${user.name} — ${user.followers} followers, ${user.public_repos} repos`);
🧠 Brain power

What would happen if: a page sets setTimeout(fn, 1000), and on the very next line starts a loop that grinds numbers for five full seconds. When does fn actually run — at the 1-second mark, or later? What is the user's scroll wheel doing during those five seconds?

Reveal the answer

fn runs at roughly the five-second mark, not at one. The timer "appliance" finishes at 1s and drops its ticket in the queue — but the cook is stuck grinding your loop, and queued tickets are only picked up when the current code finishes. Scrolling and clicks are queued tickets too, so the page is frozen the whole five seconds. Both facts are the same fact: setTimeout is "no sooner than", and long-running synchronous code blocks everything — which is why the browser makes every slow operation async by design.

09 · Modern JSModern Touches — Modules, Classes, and a Glimpse of TypeScript

Three things you'll meet in the wild the week you leave this page, each in passing. First, modules: real projects split code across files, and <script type="module"> plus import/export is how the files name what they share. (Like fetch, module imports need the two-line local server — the one setup where a bare double-click isn't enough.)

math.js + app.html — two files, served locallyruns offline
// ---- math.js ----------------------------------------------------
// `export` marks the public surface; everything else stays private.
export function double(x) {
  return x * 2;
}
export const TAU = 6.28318;
app.html — save next to math.jsruns offline
<!doctype html>
<meta charset="utf-8">
<title>Modules</title>
<script type="module">
  import { double, TAU } from "./math.js";
  console.log(double(TAU));      // 12.56636 -- run via: python3 -m http.server
</script>

Second, classes — one page's worth, because you'll read them everywhere even though plain objects and functions carried JavaScript's first two decades fine. A class is a factory for objects that share methods; constructor runs at new-time; this means "the object being worked on":

class_tour.js — paste into the consoleruns offline
class Quiz {
  constructor(questions) {        // runs once per `new Quiz(...)`
    this.questions = questions;   // `this` = the object under construction
    this.score = 0;
  }
  answer(i, choice) {             // a method -- shared by every Quiz instance
    if (this.questions[i].answer === choice) this.score += 1;
    return this.score;
  }
}

const q = new Quiz([{ text: "2 + 2?", answer: "4" }]);
console.log(q.answer(0, "4"));    // 1
// Honest note: JS objects don't NEED classes -- { } literals plus functions
// (like makeCounter in §05) model most things. Classes are organization, not magic.

Third, ten lines on TypeScript, because job listings will show you the word before any tutorial does. TypeScript is JavaScript plus type annotations, checked before the code runs — a whole category of bugs caught while you type instead of when a user clicks. Everything in this chapter is valid TypeScript already; TS is a weekend on top of JS, not a new language. It matters here because the tooling around a backend estate — admin UIs, BFF services, build tools, infrastructure CLIs, vendor SDKs — is heavily TypeScript, and most job listings that say "full-stack" mean it. Pointer, not a lesson:

teaser.ts — preview only, not needed for this chapter's JSruns offline
// TypeScript: the annotations after `:` declare what each value must be.
function score(answers: string[], correct: string[]): number {
  return answers.filter((a, i) => a === correct[i]).length;
}

score(["a", "d"], ["a", "c"]);   // fine -- returns 1
score("ad", ["a", "c"]);         // caught WHILE TYPING: string is not string[]
// Same bug in plain JS: runs, silently returns 0, ships to a user.

There are no dumb questions

Is JavaScript related to Java?
No — the name was 1995 marketing, riding Java's hype. They're unrelated languages with different designs, ecosystems, and jobs. (Java is a fine language too; it has its own chapter, E1.)
Do I need to learn HTML and CSS before this page?
No. This primer uses about ten HTML tags and introduces each where it appears — <button>, <p>, <textarea>, <script> cover most of it. Deep HTML/CSS is worth learning alongside, not before: JS is what makes the other two move.
Shouldn't I just learn React and skip this?
React is JavaScript — every framework assumes this page cold: arrow functions, map over arrays (literally how React renders lists), events, async, destructuring. Freshers who start with a framework can assemble apps but can't debug them. Vanilla first makes any framework learnable in days, and interviews test the vanilla layer anyway.
Is JavaScript only for browsers?
No — Node.js runs the same language on servers and command lines, and most build tooling is written in it. We learn in the browser because it's a zero-install runtime with instant visual feedback; everything you learn here transfers to Node unchanged.
Do I need to memorize every array method?
No. The big five — map, filter, find, some, reduce — cover the great majority of real code, and the rest (slice, includes, sort…) is a lookup away. Fluency in the five is the part a lookup can't give you.

10 · Watch it breakThe Fresher-Classic Gotchas, Demonstrated

Failure mode

Every snippet below runs without a single error message — and does the wrong thing. These six are the traps that eat a beginner's first month, and they double as the most common JavaScript screening questions. Paste the block into a fresh console, watch each one lie to you, and you're inoculated: seen-it-break beats read-about-it every time.

gotchas.js — paste into a fresh consoleruns offline
// GOTCHA 1 -- == coerces types before comparing
console.log(0 == "");             // true ?!  ("" converts to 0)
console.log("0" == 0);            // true ?!  (so "" and "0" both "equal" 0…)
console.log("" == "0");           // false ?! (…but not each other. Rules nobody keeps.)
console.log(0 === "");            // false -- ===: different types, honestly different

// GOTCHA 2 -- forgetting await: you logged the receipt, not the value
async function slowAnswer() {
  return 42;                      // an async function ALWAYS returns a promise
}
console.log(slowAnswer());        // Promise { … } -- the receipt! forgot await
slowAnswer().then(v => console.log(v));   // 42 -- or `await slowAnswer()` in async code
// If you ever see "Promise" or "[object Promise]" where data should be: missing await.

// GOTCHA 3 -- sort() sorts numbers… alphabetically
console.log([10, 9, 1].sort());               // [1, 10, 9] ?! -- compared as TEXT
console.log([10, 9, 1].sort((a, b) => a - b)); // [1, 9, 10] -- give it a comparator

// GOTCHA 4 -- `this` gets lost in an old-style callback
const timer = {
  seconds: 42,
  startBroken() {
    setTimeout(function () {           // a `function` callback gets its OWN `this`
      console.log("broken:", this.seconds);    // broken: undefined
    }, 100);
  },
  startFixed() {
    setTimeout(() => {                 // arrows have NO own `this` -- they keep yours
      console.log("fixed:", this.seconds);     // fixed: 42
    }, 200);
  },
};
timer.startBroken();
timer.startFixed();
// The rule that skips a chapter of pain: use arrow functions for callbacks.

// GOTCHA 5 -- const stops REASSIGNMENT, not mutation
const scores = [1, 2];
scores.push(3);                   // fine! same array, new contents
console.log(scores);              // [1, 2, 3]
// scores = [];                   // THIS is what const forbids -- TypeError

// GOTCHA 6 -- floats are binary fractions (true in every language)
console.log(0.1 + 0.2);           // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3);   // false
console.log(Math.abs(0.1 + 0.2 - 0.3) < 1e-9);   // true -- compare with tolerance

Notice how little you have to carry: gotchas 1 and 3 vanish if you always write === and always give sort a comparator; gotcha 4 vanishes if callbacks are always arrows; gotcha 2 announces itself once you know that Promise { … } in an output means a missing await. Four habits, four traps disarmed. Gotchas 5 and 6 are facts, not traps: const freezes the name-to-object binding, not the object's insides — and decimal fractions don't fit exactly into binary, in JavaScript or anywhere else.

11 · Under the hoodHow the Browser Runs Your Script

Optional depth — nothing below is needed to write the lab, but each piece makes something you've seen click. When the browser's HTML parser reaches a <script> tag, it pauses building the tree and hands the code to the JavaScript engine (V8 in Chrome and Edge, SpiderMonkey in Firefox, JavaScriptCore in Safari — as of Aug 2026, the big three). The engine parses the entire script first — syntax errors surface here, before any line runs — then executes it top to bottom, compiling hot code to machine code as it goes. Only when the script finishes does HTML parsing resume, which is both why a script can't find tags below itself (§07's Brain Power) and why a slow script visibly delays the page.

The event loop in five sentences — optional depth

JavaScript runs on one thread with a call stack (the code running right now) and a callback queue (finished work waiting its turn). Slow operations — timers, network, user input — are delegated to the browser's own machinery, which runs them in parallel and pushes a callback onto the queue when done. The event loop is a loop that does one thing: whenever the call stack is empty, take the oldest callback off the queue and run it to completion. Nothing ever interrupts running JavaScript — each callback finishes before the next begins, which is why you never worry about two pieces of your code racing each other mid-line. The fine print you'll meet in interviews: promise callbacks wait in a separate microtask queue that the loop drains completely before it touches the timer/event queue — which is why a .then() beats a setTimeout(…, 0) scheduled on the same line.

var and hoisting — historical context for the code you'll read

Before 2015, var was the only way to declare a variable, and it has two behaviors that let/const were designed to kill. Declarations are hoisted: the engine registers every var name at the top of its function before running anything, initialized to undefined — so reading one "too early" silently gives undefined instead of an honest error. And var scopes to the function, ignoring { } blocks entirely, so loop variables leak:

hoisting_peek.js — paste into the consoleruns offline
console.log(ghost);        // undefined -- no error! the var below was hoisted
var ghost = "boo";

if (true) {
  var leaky = "I escape blocks";
  let contained = "I don't";
}
console.log(leaky);        // "I escape blocks" -- var ignores the { } block
// console.log(contained); // ReferenceError -- let respects the block. Good.

That's the whole story: let/const are block-scoped and refuse to be read before their declaration line. You'll see var in older tutorials and legacy codebases constantly — read it fine, write it never.

12 · The road aheadWhere JavaScript Fits in a Backend Career

This chapter stands alone — but a backend engineer meets JavaScript in four places, and each one quietly assumes a reader who can do what you now can. Pointers, not lessons:

Where backend work touches JavaScript — and which section of this primer covers you
WhereWhat JavaScript is doing thereCovered by
Admin pages and internal dashboardsYour Spring Boot or Go service (E4, E12) returns JSON; a browser page fetches it and renders a table, a form, a status light — that page is fetch + DOM, i.e. this primer§07 + §08
BFF and Node servicesThe "backend for frontend" that sits between the browser and your core services is very often Node/TypeScript — same language, same event loop, no browser§08 + §09's teaser
Tooling and infrastructure CLIsBuild scripts, lint configs, deployment helpers and many vendor SDKs ship as npm packages — you will read TS-shaped code even while writing Java or Go§09
Code review across the stackFront-end pull requests land in the same repo as your service; reviewing them well means spotting §10's gotchas in someone else's diff§10
Boardroom translation

For a fresher, JavaScript is straightforward employability math: every product team ships a browser surface, so the person who can build one is useful on week one — and when the team builds a new backend feature, the engineer who can put a working demo UI in front of stakeholders is the one whose work gets seen. Services impress in dashboards; demos get funded. The elevator version: "Ten hours buys the language of every screen — the cheapest way for a new engineer to make their work, and everyone else's services, visible."

13 · The labBuild quiz.html — A Complete App in One File

Worked examples first, spec second — and you've already built every organ this app needs: state in a closure (§05, clicker), rendering data into DOM nodes (§06 + §07), a ticking clock (§08's setInterval), and fetch-with-fallback (§08's try/catch). The lab is assembling them into one organism: a self-contained interactive quiz, vanilla JS, no frameworks, no build step. Note the meta-trick, same as every lab in this track: the seed questions below are this chapter's own gotchas — building the quiz drills the page. Here's your questions file (and inline fallback array):

questions.json — the seed deck (also your inline fallback)runs offline
[
  { "question": "Which comparison should you always use?",
    "choices": ["==", "===", "=", "=>"],
    "answer": "===" },
  { "question": "What does [10, 9, 1].sort() return?",
    "choices": ["[1, 9, 10]", "[10, 9, 1]", "[1, 10, 9]", "a TypeError"],
    "answer": "[1, 10, 9]" },
  { "question": "console.log(getData()) prints 'Promise { … }'. The bug?",
    "choices": ["getData is broken", "a missing await", "the network is down", "console is broken"],
    "answer": "a missing await" },
  { "question": "Exactly which values are falsy?",
    "choices": ["everything empty, including [] and {}", "false, 0, \"\", null, undefined, NaN", "only false and null", "only false"],
    "answer": "false, 0, \"\", null, undefined, NaN" },
  { "question": "const scores = [1, 2]; scores.push(3); -- what happens?",
    "choices": ["TypeError: const", "works fine -- const stops reassignment, not mutation", "silently ignored", "scores becomes [3]"],
    "answer": "works fine -- const stops reassignment, not mutation" }
]
LAB E11 — quiz.html, a single-file interactive quiz app (vanilla JS)

Mission: build quiz.html — one file that shows one question at a time with its choices as buttons, gives instant right/wrong feedback, runs a visible countdown per question, and ends on a results screen with a review of misses and a restart button. Suggested skeleton: a state object ({ questions, current, score, answers }), one render() function that redraws the page from state, and listeners that change state and call render() — that state→render shape is, incidentally, the idea React industrializes.

  • Double-clicking quiz.html just works — one file, no frameworks, no build step, no server required for the core flow
  • Questions live in an array of objects; choice buttons are built with .map(…), and the results screen uses .filter(…) to list the questions you missed — both used meaningfully, not decoratively
  • Instant feedback styling: correct flashes the button green; wrong flashes red and highlights the correct choice, then auto-advances after ~1s (setTimeout)
  • A visible per-question countdown built on setInterval; reaching zero counts as wrong and advances; the interval is cleared on every answer — prove there are no ghost timers by logging ticks and answering early
  • Results screen shows score plus per-question review; Restart resets all state and re-renders without reloading the page
  • The async touch: on load, try { await fetch("questions.json") } (works when served via python3 -m http.server); on failure, fall back to the inline array and display "offline deck" in the UI — loading state included, no unhandled errors in the console either way
  • Self-measurement: a comment block at the top of the file listing three bugs you hit and the console evidence that led you to each — debugging is the skill this lab actually grades

Stretch: swap the deck for the Open Trivia DB API (https://opentdb.com/api.php?amount=5&type=multiple, no key) — you'll have to decode HTML entities and shuffle the choices, both real-API rites of passage. Second stretch: put your own backend behind it — serve questions.json from a Spring Boot endpoint (E4) or a Go handler (E12), and POST the final score back to it — this quiz becomes your first full-stack piece, with a service you wrote at both ends of the fetch.

14 · Interview radarHow This Shows Up in Interviews

Interview radar

Fresher-round JavaScript questions are remarkably standardized — screeners reach for the same five, because each separates "typed tutorials" from "understands the machine". You've met every one of them in running code:

"var vs let vs const?"

Strong answer Three declarations, one policy:

  • const by default — it signals that the binding is never reassigned
  • let only when reassignment is the point, as with a loop counter or a running score
  • var never in new code — it is function-scoped, ignores blocks, and hoists to undefined instead of erroring

Land it Naming why var is banned — scope plus hoisting (§11) — is what scores; "var is old" doesn't.

"== vs ===?"

Strong answer === compares type and value, while == coerces the types first, following rules too messy to trust. Give one example from memory — 0 == "" is true — and then state the policy: always ===, and the linter enforces it.

Land it Example plus policy is a complete answer.

"What does this log, in what order?"

The real test The setTimeout question — can you explain the event loop, not just guess the output?

Strong answer They'll show console.log("A"); setTimeout(() => console.log("B"), 0); console.log("C"). The output is A, C, B — and the why is what they're grading: JavaScript runs on one thread, and even a 0ms timer's callback goes through the queue, served only when the current code finishes. Sketch Fig. E11.3 in words — the cook, the queue, the appliances.

Land it Bonus signal: a promise's .then on the same line beats the timer, because microtasks drain first.

"map vs forEach?"

Strong answer map returns a new array — a transformation you keep — while forEach returns undefined and exists for side effects only. Then add the judgment layer: map with a discarded result is a smell, and hand-pushing into an output array inside forEach is the same smell mirrored.

Land it Choose by one question: is the result a value you keep?

"null vs undefined?"

Strong answer undefined is absence by default — an unset variable, a missing parameter, a function with no return. null is absence on purpose: a human assigned it to mean "deliberately empty".

Land it The detail that impresses: typeof null === "object" is a 1995 bug kept forever for compatibility — knowing it says you've actually run the language.

15 · RecapWhat You Can Do Now

  • You can open a blank file and produce a working interactive page — the exact test from the hook — with nothing installed
  • You can declare state with const/let deliberately, and explain in one line why var is banned
  • You can predict comparisons and conditions: === always, the six falsy values from memory, and why if ([]) passes
  • You can write and read arrow functions, pass functions as values, and explain what a closure remembers — with the counter as your proof
  • You can shape data with the big five array methods and say which question each one answers
  • You can find, edit, and create DOM nodes, and wire click and input events into live UI
  • You can explain the event loop with the cook-and-queue picture, read Promise { … } in an output as "missing await", and write async/await fetch code with a loading state and honest error handling
  • You can spot all six classic gotchas in code — yours, a teammate's, or a generated diff's
🧠 Flex your memory

From this chapter: close every tab, open a blank file, and rebuild clicker.html — button, state, listener — entirely from memory, then check it against §07. If any line stalls you, that line is the one to drill. And a forward pointer: when your Spring Boot service (E4) or Go service (E12) returns its first JSON, come back here — the admin page you'll want in front of it is exactly this primer's fetch + DOM tools, and building it will take you an evening, not a course.