WebDev Story

WebDev Story: JavaScript Summary

definition, execution model, syntax, usage patterns

4.0 What is JavaScript?

JavaScript is a high-level, dynamically typed, interpreted programming language based on objects composed of key-value pairs. Keys are names; values may be a function, a literal, or another object.
let jim = {
  "name": "Fawcett",
  "job":  "Instructor",
  show: function() {
    return `{ name: ${this.name}, job: ${this.job} }`;
  }
};
console.log(jim.show());
// output: { name: Fawcett, job: Instructor }
JavaScript uses a prototype model to support specialization. When a method call cannot be resolved on an object, function lookup walks up the object's prototype chain toward Object.prototype, the root of all plain objects.

4.1 Execution Engine

JavaScript in the browser runs on a single-threaded execution engine built around an Event Loop:
  1. When a JavaScript function is called, its execution context is pushed onto the Call Stack.
  2. When an event fires (click, load, timer, fetch response, …), its handler is placed on the Event Queue (also called the Message Queue).
  3. The event loop picks the next queued handler only when the call stack is empty — meaning all synchronous code has finished.
  4. Microtasks (Promise callbacks, queueMicrotask) drain completely after each task, before the next task is dequeued.
This model means: keep event handlers short and non-blocking. Long synchronous operations freeze the UI because no other events can be processed until the call stack empties. Use async/await or Promises for operations that take time. Web Workers run JavaScript on background threads but cannot access the DOM. They communicate with the main thread through postMessage.
JavaScript (ECMAScript) specification The JavaScript language is standardized by ECMA International as ECMAScript (ECMA-262). The living draft at tc39.es/ecma262 reflects the latest approved and in-flight changes.

4.2 Syntax Overview

The code block below is a quick-reference tour of JavaScript syntax, covering all the major features a web developer uses regularly.
JavaScript Syntax Quick Reference
// ── Values, variables, and scope ─────────────────────────────────────
// Numbers, strings, booleans, null, undefined, BigInt, Symbol
let n = 42, s = "hi", ok = true, z = null;

const PI = 3.1416;    // cannot be reassigned
let count = 0;        // can be reassigned

// ── Expressions and operators ─────────────────────────────────────────
1 + 2 * 3;            // 7
10 ** 2;              // 100 (exponent)
a === b;              // strict equality (no coercion)
a && b || c;          // short-circuiting

const name = user.name ?? "Anonymous";      // nullish coalescing
const city = user.address?.city;            // optional chaining

// ── Control flow ──────────────────────────────────────────────────────
if (x > 0) { ... } else { ... }

for (let i = 0; i < 3; i++) { ... }
for (const v of [1, 2, 3]) { ... }         // iterable loop
while (cond) { ... }

switch (kind) {
  case "cat": doCat(); break;
  default: fallback();
}

// ── Functions ─────────────────────────────────────────────────────────
function add(a, b = 0) { return a + b; }   // default param

const mul = function(a, b) { return a * b; };  // expression

const dbl = x => x * 2;                    // arrow (lexical `this`)

// ── Objects and arrays ────────────────────────────────────────────────
const person = { id: 1, name: "Ada" };
const team   = ["A", "B", "C"];

const { name } = person;                   // destructuring
const [first, ...rest] = team;

const x = 1, y = 2;
const point = { x, y, ["p" + "3"]: 3 };   // shorthand + computed keys

const withAge = { ...person, age: 36 };    // spread/merge
const bigger  = [...team, "D"];

// ── Template literals ─────────────────────────────────────────────────
const who = "world";
const msg = `Hello, ${who}!
This spans multiple lines.`;

// ── Classes (ES2015+) ─────────────────────────────────────────────────
class Counter {
  #n = 0;                            // private field
  inc() { this.#n++; }
  get value() { return this.#n; }
  static from(n) { const c = new Counter(); c.#n = n; return c; }
}

// ── Modules ───────────────────────────────────────────────────────────
// export.js
export const PI = 3.14;
export default function area(r) { return PI * r * r; }

// import.js
import area, { PI } from "./export.js";

// ── Promises and async/await ──────────────────────────────────────────
fetch("/api/user")
  .then(r => r.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));

async function load() {
  try {
    const r    = await fetch("/api/user");
    const data = await r.json();
    console.log(data);
  } catch (e) {
    console.error(e);
  }
}

// ── Errors ────────────────────────────────────────────────────────────
try {
  risky();
} catch (err) {
  console.error(err.message);
} finally {
  cleanup();
}

// ── DOM basics ────────────────────────────────────────────────────────
const btn = document.querySelector("#go");
btn.addEventListener("click", () => {
  document.body.style.backgroundColor = "papayawhip";
});

// ── Truthy / falsy and equality ───────────────────────────────────────
// falsy: false, 0, -0, 0n, "", null, undefined, NaN
if ("0") { /* runs — non-empty string is truthy */ }

"5" == 5    // true  (coerces)
"5" === 5   // false (strict)

4.3 Three Ways JavaScript is Used

In practice, JavaScript is used in one of three main patterns on a web page:
  1. Event-driven DOM mutation — functions that run in response to user actions:
    <div id="demo" onclick="toggle('demo')">Hello World</div>
  2. Shared menu and navigation objects — objects that build and manage menus used by many pages. A single change in the shared script updates every page automatically.
  3. Stateful widget objects — objects that encapsulate complex visual components by holding and mutating private state (e.g., a sortable table, collapsible tree, or auto-complete input).
Methods and properties are appended to plain objects with simple property assignment. ES2015 class syntax provides a more structured alternative, wrapping the same prototype model (see Chapter 5).

4.4 References

Reference Description
ECMAScript 2025 Spec (ECMA-262) Normative spec for the current ECMAScript edition (June 2025).
ECMA-262 Living Draft Continuously updated draft reflecting approved and in-flight changes.
MDN JavaScript Reference Authoritative task-oriented reference with examples and caveats.
MDN JavaScript Guide Big-picture language guide with how-tos and best practices.
Understanding data types in JS Clear and complete overview of JavaScript's type system.
Understanding Objects in JS Thorough explanation of how JavaScript objects work.
Prototypes and Inheritance Describes the JavaScript inheritance model clearly.
Modules, Import, and Export How modules factor complex code into simpler parts.
Event Loop, Callbacks, Promises, Async/Await How JavaScript reacts to user events over time.
DigitalOcean JS tutorial series Large collection of beginner-to-intermediate tutorials.
TC39 ECMAScript Proposals (Stage 2+) Tracks features likely to land in future ECMAScript editions.
onlinejsplayground.com Browser-based JS sandbox — run snippets without installing anything.