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)