JavaScript documentation
MDN JavaScript guide + reference (syntax, built-ins, browser APIs).
MDN JavaScript guide + reference (syntax, built-ins, browser APIs).
mkdir my-js && cd my-js
npm init -y
node -e 'console.log("hello")'
{
"type": "module",
"scripts": {
"dev": "node index.js"
}
}
const res = await fetch("/api/data");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
const btn = document.querySelector("button#save");
btn?.addEventListener("click", () => {
console.log("save");
});
var legacy = 1; // function-scoped
let n = 0; // block-scoped (mutable)
const name = "Sam"; // block-scoped (binding is immutable)
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];
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);
function add(a, b = 0) {
return a + b;
}
const mul = (a, b) => a * b;
class User {
constructor(id, email) {
this.id = id;
this.email = email;
}
toString() {
return `${this.id}:${this.email}`;
}
}
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;
}
}