📋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

ES2015
1const pi = 3.14; // Standard
2let zaehler = 0; // wird neu zugewiesen
3var alt = "nicht mehr verwenden";

Typ prüfen

1typeof 42 // "number"
2typeof null // "object" (!)
3Array.isArray([]) // true
4Number.isNaN(NaN) // true

Umwandeln

1Number("42") // 42
2String(42) // "42"
3Boolean("") // false
4parseInt("08px", 10) // 8

Zahlen

BigInt ES2020
10.1 + 0.2 === 0.3 // false
2Math.round(2.5) // 3
3(1234.5).toFixed(1) // "1234.5"
42n ** 64n // BigInt

➗Operatoren

Gleichheit

1a === b // strikt, ohne Umwandlung
2a !== b
3Object.is(NaN, NaN) // true
4wert == null // null ODER undefined

Logik & Standardwerte

?? ES2020, ??= ES2021
1a && b // b, wenn a truthy
2a || "std" // "std", wenn a falsy
3a ?? "std" // "std", nur bei null/undefined
4x ??= 1; y ||= 2; z &&= 3;

Optional Chaining

ES2020
1nutzer?.adresse?.stadt
2liste?.[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

ES2015
1const s = `Hallo ${name}, du bist ${alter} Jahre alt`;

Methoden

1"JavaScript".includes("Script") // true
2"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)

ES2023
1liste.toSorted((a, b) => a - b)
2liste.toReversed()
3liste.with(0, "neu")
4liste.toSpliced(1, 1)

Gruppieren

ES2024
1Object.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 ES2022
1class Konto {
2 #stand = 0; // privat
3 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 ES2024
1const warte = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2const { promise, resolve, reject } = Promise.withResolvers();

async/await

ES2017
1async 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 Fehler
2await Promise.allSettled([a, b]) // alle Ergebnisse
3await Promise.race([a, b]) // erstes erledigtes
4await 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 ES2022
1throw 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");