JS Story

JS Story: JavaScript Summary

definition, syntax, usage patterns, references

1.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() {
    return `{ name: ${this.name}, job: ${this.job} }`;
  }
};
console.log(jim.show());
// { name: Fawcett, job: Instructor }
JavaScript uses a prototype model for inheritance. When a method call cannot be resolved on an object, the lookup walks up the object's prototype chain toward Object.prototype, the root of all plain objects. ES2015 class syntax wraps this same mechanism in a familiar form (see Chapter 3). JavaScript in the browser runs on a single thread built around an event loop. Long synchronous operations freeze the page because no other events can fire until the call stack is empty. Chapter 2 covers the execution engine in detail; Chapter 5 covers the async patterns - Promises and async/await - that avoid blocking.

1.1 Syntax Overview

The code block below is a quick-reference tour of JavaScript syntax, covering all the major constructs a web developer uses regularly.
JavaScript Syntax Quick Reference
// ── Values, variables, and scope ─────────────────────────────────────
// Primitive types: number, string, boolean, 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; block-scoped

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

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 parameter
const mul = (a, b) => a * b;               // arrow (lexical `this`)

// rest parameters and spread
function sum(...nums) { return nums.reduce((a, b) => a + b, 0); }
sum(...[1, 2, 3]);   // 6

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

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

const x = 1, y = 2;
const point = { x, y, ["p" + "3"]: 3 };   // shorthand + computed keys
const copy  = { ...person, age: 36 };      // spread / merge

// ── Template literals ──────────────────────────────────────────────────
const msg = `Hello, ${name}! You are ${person.id === 1 ? "first" : "not first"}.`;

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

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

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

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

async function loadUser(id) {
  try {
    const r    = await fetch(`/api/user/${id}`);
    const data = await r.json();
    render(data);
  } catch (e) {
    showError(e.message);
  }
}

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

// ── Truthy / falsy ─────────────────────────────────────────────────────
// falsy: false, 0, -0, 0n, "", null, undefined, NaN
// everything else is truthy, including "0", [], {}
"5" == 5    // true  (coerces type)
"5" === 5   // false (strict, no coercion)

1.2 Three Ways JavaScript is Used

In practice, JavaScript serves one of three main roles on a web page:
  1. Event-driven DOM mutation - functions that run in response to user actions. The handler reads or mutates elements in the document:
    document.querySelector('#go').addEventListener('click', () => {
      document.querySelector('#msg').textContent = 'Clicked!';
    });
  2. Shared navigation and menu objects - objects that build and manage navigation menus used across many pages. A single change in the shared script updates every page automatically:
    // js/nav.js - loaded by every page
    function buildPages() {
      document.getElementById('pages').innerHTML = pagesMenuHtml;
    }
  3. Stateful widget objects - objects that encapsulate complex visual components by holding and mutating private state. Examples: a sortable table, a collapsible tree, an auto-complete input, or a custom web component:
    class Accordion {
      #open = null;
      toggle(panel) {
        if (this.#open) this.#open.classList.remove('expanded');
        this.#open = (this.#open === panel) ? null : panel;
        this.#open?.classList.add('expanded');
      }
    }

1.3 References

Reference Description
ECMAScript 2025 Spec (ECMA-262) Normative specification for the current ECMAScript edition.
ECMA-262 Living Draft Continuously updated draft reflecting approved and in-flight changes.
MDN JavaScript Reference Authoritative task-oriented reference with examples and caveats.
javascript.info Modern, structured JavaScript tutorial with runnable examples throughout.
Understanding data types in JS Clear and complete overview of JavaScript's type system.
Prototypes and Inheritance Describes the JavaScript prototype inheritance model clearly.
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.