📋Spickzettel
Die wichtigsten Bausteine von modernem JavaScript auf einen Blick – mit Angabe, seit welcher ECMAScript-Version es sie gibt.
31 Einträge
📌Variablen & Typen
Deklarieren
ES20151const pi = 3.14; // Standard2let zaehler = 0; // wird neu zugewiesen3var alt = "nicht mehr verwenden";
Typ prüfen
1typeof 42 // "number"2typeof null // "object" (!)3Array.isArray([]) // true4Number.isNaN(NaN) // true
Umwandeln
1Number("42") // 422String(42) // "42"3Boolean("") // false4parseInt("08px", 10) // 8
Zahlen
BigInt ES202010.1 + 0.2 === 0.3 // false2Math.round(2.5) // 33(1234.5).toFixed(1) // "1234.5"42n ** 64n // BigInt
➗Operatoren
Gleichheit
1a === b // strikt, ohne Umwandlung2a !== b3Object.is(NaN, NaN) // true4wert == null // null ODER undefined
Logik & Standardwerte
?? ES2020, ??= ES20211a && b // b, wenn a truthy2a || "std" // "std", wenn a falsy3a ?? "std" // "std", nur bei null/undefined4x ??= 1; y ||= 2; z &&= 3;
Optional Chaining
ES20201nutzer?.adresse?.stadt2liste?.[0]3obj.methode?.()
Ternär & Spread
1const text = alter >= 18 ? "volljährig" : "minderjährig";2const alle = [...a, ...b];3const neu = { ...alt, x: 1 };
🔤Strings
Template-Literal
ES20151const s = `Hallo ${name}, du bist ${alter} Jahre alt`;
Methoden
1"JavaScript".includes("Script") // true2"a,b,c".split(",") // ["a","b","c"]3" x ".trim() // "x"4"abc".at(-1) // "c"5"5".padStart(3, "0") // "005"6"a-b-a".replaceAll("a", "x") // "x-b-x"
📚Arrays
Durchlaufen & umformen
1zahlen.map((x) => x * 2)2zahlen.filter((x) => x > 0)3zahlen.reduce((s, x) => s + x, 0)4zahlen.forEach((x, i) => console.log(i, x))
Suchen
1liste.find((x) => x.id === 3)2liste.findIndex((x) => x.id === 3)3liste.includes(wert)4liste.some((x) => x < 0)5liste.every((x) => x > 0)
Ohne Veränderung (ES2023)
ES20231liste.toSorted((a, b) => a - b)2liste.toReversed()3liste.with(0, "neu")4liste.toSpliced(1, 1)
Gruppieren
ES20241Object.groupBy(personen, (p) => p.stadt)2Map.groupBy(personen, (p) => p.stadt)
🗃️Objekte
Anlegen & Kurzschreibweisen
1const name = "Ada";2const p = { name, ["key" + 1]: true, gruss() { return "Hi"; } };
Durchlaufen
1Object.keys(obj) // ["a", "b"]2Object.values(obj)3Object.entries(obj) // [["a", 1], …]4Object.fromEntries([["a", 1]])
Destructuring
1const { name, alter = 0, ...rest } = person;2const [erstes, , drittes] = liste;3function f({ id, titel = "?" }) {}
Kopieren
1const flach = { ...obj };2const tief = structuredClone(obj);3Object.freeze(obj); // unveränderlich (flach)
ƒFunktionen & Klassen
Funktionen
1function add(a, b = 0) { return a + b; }2const mul = (a, b) => a * b;3const summe = (...zahlen) => zahlen.reduce((s, x) => s + x, 0);
Klasse
#privat ES20221class Konto {2 #stand = 0; // privat3 static waehrung = "EUR";4 constructor(inhaber) { this.inhaber = inhaber; }5 get stand() { return this.#stand; }6 einzahlen(b) { this.#stand += b; return this; }7}
Vererbung
1class Sparkonto extends Konto {2 constructor(inhaber, zins) {3 super(inhaber);4 this.zins = zins;5 }6}
this festlegen
1f.call(obj, a, b);2f.apply(obj, [a, b]);3const g = f.bind(obj);
⏳Asynchron
Promise erzeugen
withResolvers ES20241const warte = (ms) => new Promise((resolve) => setTimeout(resolve, ms));2const { promise, resolve, reject } = Promise.withResolvers();
async/await
ES20171async function lade() {2 try {3 const res = await fetch("/api/beispiele");4 if (!res.ok) throw new Error(`HTTP ${res.status}`);5 return await res.json();6 } catch (e) {7 console.error(e);8 }9}
Kombinatoren
1await Promise.all([a, b]) // alle, sonst Fehler2await Promise.allSettled([a, b]) // alle Ergebnisse3await Promise.race([a, b]) // erstes erledigtes4await Promise.any([a, b]) // erstes erfülltes
Timer & Microtasks
1const id = setTimeout(fn, 1000);2clearTimeout(id);3const iv = setInterval(fn, 500);4clearInterval(iv);5queueMicrotask(fn);
🧯Fehler
try/catch/finally
1try {2 riskant();3} catch (e) {4 console.error(e.name, e.message);5} finally {6 aufraeumen();7}
Werfen mit Ursache
cause ES20221throw new Error("Speichern fehlgeschlagen", { cause: e });
🌐Module & DOM
Module
1export const x = 1;2export default function main() {}3import main, { x } from "./modul.js";4const m = await import("./modul.js");
DOM
1const el = document.querySelector("#id");2el.textContent = "Text";3el.classList.toggle("aktiv");4el.addEventListener("click", (e) => {});5document.body.append(document.createElement("p"));
Speicher
1localStorage.setItem("k", JSON.stringify(obj));2const obj2 = JSON.parse(localStorage.getItem("k") ?? "null");