JavaScript

Quickstart (Node project)

bash
mkdir my-js && cd my-js
npm init -y
node -e 'console.log("hello")'

Project setup (ESM + scripts)

json
{
  "type": "module",
  "scripts": {
    "dev": "node index.js"
  }
}

Fetch + JSON

javascript
const res = await fetch("/api/data");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();

DOM query + event

javascript
const btn = document.querySelector("button#save");
btn?.addEventListener("click", () => {
  console.log("save");
});

Variables (var/let/const)

javascript
var legacy = 1; // function-scoped
let n = 0;       // block-scoped (mutable)
const name = "Sam"; // block-scoped (binding is immutable)

Datatypes (primitive + object)

javascript
const s = "str";
const i = 123;
const b = true;
const n = null;
const u = undefined;
const sym = Symbol("id");
const big = 123n;

const obj = { a: 1 };
const arr = [1, 2, 3];

Iteration (for/of, for/in, map/filter)

javascript
const xs = [1, 2, 3];

for (const x of xs) console.log(x); // values
for (const k in { a: 1, b: 2 }) console.log(k); // keys

const doubled = xs.map((x) => x * 2);
const evens = xs.filter((x) => x % 2 === 0);

Functions (declaration, arrow, default args)

javascript
function add(a, b = 0) {
  return a + b;
}

const mul = (a, b) => a * b;

Classes (constructor + method)

javascript
class User {
  constructor(id, email) {
    this.id = id;
    this.email = email;
  }
  toString() {
    return `${this.id}:${this.email}`;
  }
}

Async/Await (try/catch)

javascript
async function getJSON(url) {
  try {
    const r = await fetch(url);
    if (!r.ok) throw new Error(`HTTP ${r.status}`);
    return await r.json();
  } catch (err) {
    console.error(err);
    throw err;
  }
}