JSJavaScript

JavaScript: More snippets – code examples

Contents

if / else if / else

Control flow#if#conditionCompare in all languages
Use case: React differently, e.g. calculate grades or price tiers.
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

Control flow#for#loop#ofCompare in all languages
Use case: Process every element of a list or repeat n times.
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

Functions#function#return#parameterCompare in all languages
Use case: Bundle recurring logic, e.g. greeting texts or calculations.
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

OOP#class#oop#extends#inheritanceCompare in all languages
Use case: Bundle data and behavior, e.g. users, products, game characters.
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

OOP#class#private#getter#static
Use case: Protect internal data, e.g. the balance or token of a class.
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

Error handling#try#catch#exception#errorCompare in all languages
Use case: Guard user input or network responses without the program crashing.
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)

Files#fs#file#nodeCompare in all languages
Use case: Save and load logs, configurations or text data.
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

Files#json#serialization#stringify
Use case: Exchange data with web APIs, localStorage or other programs.
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

Strings#split#count#entries
Use case: Text analysis, e.g. most frequent words in a document.
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

Strings#regex#match#replace#pattern
Use case: Find and reshape email addresses, dates or patterns in text.
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)

Networking#fetch#api#async#http
Use case: Fetch data from a web API, e.g. weather, repositories or your own backends.
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)

Networking#node#http#server#api
Use case: Quickly provide a small API or a mock server for tests.
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

Asynchronous#promise#async#parallel#await
Use case: Start several API calls at the same time and evaluate them together.
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

Browser#dom#event#click#delegation
Use case: Serve dynamic lists (to-dos, tables) with a single click handler.
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

Browser#localStorage#json#browser#storage
Use case: Keep settings or to-do lists between page visits.
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.