JavaScript: More snippets – code examples
- if / else if / else
- for and for...of loop
- Function with default value
- Class with inheritance
- Class with a private field
- try / catch / finally
- Reading and writing a file (Node.js)
- Reading and writing JSON
- Counting words
- Regular expression
- Loading data from an API (fetch)
- Minimal HTTP server (Node.js)
- Parallel tasks with Promise.all
- DOM list with event delegation
- Storing data in the browser
if / else if / else
const punkte = 73;
if (punkte >= 90) {
console.log("very good");
} else if (punkte >= 70) {
console.log("good");
} else {
console.log("needs improvement");
}Curly braces form the block; always compare with === instead of ==.
for and for...of loop
for (let i = 0; i < 3; i++) {
console.log("Round", i);
}
for (const frucht of ["Apple", "Pear"]) {
console.log(frucht);
}The classic for loop counts, for...of iterates directly over the values of a collection.
Function with default value
function begruesse(name, gruss = "Hello") {
return gruss + ", " + name + "!";
}
console.log(begruesse("Ada"));
console.log(begruesse("Linus", "Hi"));Parameters with a default value are optional. JavaScript has no named arguments – instead you pass an object and destructure it.
Class with inheritance
class Tier {
constructor(name) {
this.name = name;
}
sprich() {
return this.name + " makes a sound";
}
}
class Hund extends Tier {
sprich() {
return this.name + " says Woof!";
}
}
console.log(new Hund("Rex").sprich());Hund inherits from Tier and overrides sprich; behind the scenes the prototype chain is still at work.
Class with a private field
class Konto {
#saldo = 0;
einzahlen(betrag) {
if (betrag <= 0) throw new RangeError("Amount must be positive");
this.#saldo += betrag;
return this;
}
get saldo() {
return this.#saldo;
}
static vonBetrag(b) {
return new Konto().einzahlen(b);
}
}
console.log(Konto.vonBetrag(50).einzahlen(25).saldo);
try {
new Konto().einzahlen(-5);
} catch (e) {
console.log(e.name, e.message);
}#saldo is not reachable outside the class; the getter makes the value read-only. return this allows method chaining.
try / catch / finally
try {
JSON.parse("{broken");
} catch (e) {
console.log("Invalid:", e.name);
} finally {
console.log("Cleaning up");
}JavaScript has no int("abc") that raises an error (Number("abc") returns NaN); the closest analogue is JSON.parse with invalid text, which throws a SyntaxError. finally always runs.
Reading and writing a file (Node.js)
import { writeFileSync, readFileSync } from "node:fs";
writeFileSync("notizen.txt", "Line 1\nLine 2\n", "utf-8");
const text = readFileSync("notizen.txt", "utf-8");
for (const zeile of text.split("\n")) {
if (zeile) console.log(zeile);
}File access exists only in Node.js (with "type": "module" or as .mjs), not in the browser. For large files, use the asynchronous variants from node:fs/promises.
Reading and writing JSON
const daten = { name: "Ada", sprachen: ["JavaScript", "C"], aktiv: true };
const text = JSON.stringify(daten, null, 2);
console.log(text);
const zurueck = JSON.parse(text);
console.log(zurueck.sprachen[0]);stringify converts an object to text (the third argument indents), parse converts it back. Functions and undefined are lost in the process.
Counting words
const text = "this is a test this is good";
const zaehler = {};
for (const wort of text.split(" ")) {
zaehler[wort] = (zaehler[wort] ?? 0) + 1;
}
console.log(zaehler);
const top = Object.entries(zaehler).sort((a, b) => b[1] - a[1]).slice(0, 2);
console.log(top);?? 0 starts the counter at 0. With third-party text, a Map is safer, because words like constructor would otherwise collide with object properties.
Regular expression
const text = "Contact: ada@example.com, bob@test.org";
console.log(text.match(/[\w.]+@[\w.]+\.\w+/g));
console.log("Phone 12345".replace(/\d+/g, "#"));
const m = "2026-03-15".match(/(?<jahr>\d{4})-(?<monat>\d{2})-(?<tag>\d{2})/);
console.log(m.groups.tag + "." + m.groups.monat + "." + m.groups.jahr);With the g flag, match returns all matches; named groups (?<name>) make results readable.
Loading data from an API (fetch)
async function ladeRepo(name) {
const antwort = await fetch("https://api.github.com/repos/" + name);
if (!antwort.ok) throw new Error("HTTP " + antwort.status);
return antwort.json();
}
try {
const repo = await ladeRepo("nodejs/node");
console.log(repo.full_name, repo.stargazers_count);
} catch (e) {
console.error("Error:", e.message);
}fetch does not throw on 404/500 – so check antwort.ok. Top-level await works in ES modules (and in the browser with type="module").
Minimal HTTP server (Node.js)
import { createServer } from "node:http";
const server = createServer((req, res) => {
const url = new URL(req.url, "http://localhost");
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
res.end(JSON.stringify({ pfad: url.pathname, zeit: new Date().toISOString() }));
});
server.listen(3000, () => console.log("Running at http://localhost:3000"));Without frameworks, the built-in node:http is enough. In a real project you usually use Express, Fastify or Hono.
Parallel tasks with Promise.all
const warte = (ms) => new Promise((res) => setTimeout(res, ms));
async function lade(name, ms) {
await warte(ms);
return name + " loaded";
}
async function main() {
const ergebnisse = await Promise.all([lade("A", 100), lade("B", 200), lade("C", 100)]);
console.log(ergebnisse);
const status = await Promise.allSettled([lade("X", 10), Promise.reject(new Error("broken"))]);
console.log(status.map(s => s.status));
}
main();Promise.all aborts at the first error, allSettled waits for all and returns status and value for each task.
DOM list with event delegation
const liste = document.createElement("ul");
["Milk", "Bread", "Eggs"].forEach((t) => {
const li = document.createElement("li");
li.textContent = t;
liste.append(li);
});
document.body.append(liste);
liste.addEventListener("click", (e) => {
const li = e.target.closest("li");
if (li) {
li.classList.toggle("erledigt");
console.log(li.textContent, li.classList.contains("erledigt"));
}
});
liste.children[1].click();
console.log(document.querySelectorAll("li.erledigt").length);One handler on the ul is enough, because clicks "bubble" upward. On a real page you access existing HTML with querySelector.
Storing data in the browser
const KEY = "todos";
function lade() {
try {
return JSON.parse(localStorage.getItem(KEY)) ?? [];
} catch {
return [];
}
}
function speichere(todos) {
localStorage.setItem(KEY, JSON.stringify(todos));
}
const todos = lade();
todos.push({ text: "Learn JavaScript", fertig: false });
speichere(todos);
console.log(lade().length);localStorage stores only strings – hence JSON.stringify/parse. The try/catch protects against corrupted or blocked storage.