JSJavaScript

JavaScript cheatsheet – syntax overview

85 key commands and patterns for quick reference.

Basics Operators Control flow Arrays Objects, Map & Set Strings Functions & Classes Async & Errors DOM & Browser Modules & Node.js

Basics

console.log("Text", wert);Output to the console
// Comment /* Block */Single-line and multi-line comment
const x = 1; let y = 2;Constant and mutable variable
typeof xType of a value as a string
Number("5") String(5) Boolean(0)Type conversion
parseInt("42px", 10) parseFloat("3.5")Read a number from text (ignores the rest)
Number.isNaN(x) Number.isInteger(x)Check a number (NaN === NaN is false!)
x = prompt("Name?") alert("Hi")Input/message (browser only)

Operators

+ - * / % **Arithmetic: including remainder and power
=== !== < > <= >=Strict comparisons (always use ===)
&& || !Logical: and, or, not
a ?? bb only if a is null or undefined
obj?.prop obj?.[k] fn?.()Optional chaining
x ||= 1 x &&= 2 x ??= 3Logical assignments
bedingung ? a : bTernary operator
x++ x-- x += 2Increment and assignment with operation

Control flow

if (x) {} else if (y) {} else {}Branching
for (let i = 0; i < n; i++) {}Counting loop
for (const x of liste) {}Iterate over values
for (const k in obj) {}Iterate over the keys of an object
while (bedingung) {} do {} while (b)Loops with a condition
break; continue;Exit the loop / next iteration
switch (x) { case 1: ...; break; default: ... }Multi-way selection (do not forget break)

Arrays

const a = [1, 2, 3]; a.lengthCreate an array, length
a.push(4) a.pop() a.shift() a.unshift(0)Add and remove at the end/beginning
a.slice(1, 3) a.splice(1, 1)Copy a section / remove in place
a.map(f) a.filter(f) a.reduce(f, start)Transform, filter, summarize
a.find(f) a.findIndex(f) a.includes(x)Search
a.some(f) a.every(f)At least one / all elements satisfy f
a.sort((x, y) => x - y)Sort numbers (modifies a!)
a.join(", ") a.reverse() a.at(-1)Join, reverse, last element
Array.from({ length: 3 }, (_, i) => i)Create an array from a rule
a.flat() a.flatMap(f)Flatten nesting

Objects, Map & Set

const o = { a: 1, b: 2 }; o.c = 3;Create and extend an object
Object.keys(o) Object.values(o) Object.entries(o)Keys, values, pairs
delete o.a "b" in oDelete / check a property
{ ...o1, ...o2 }Merge objects (shallow)
const { a, b = 0 } = o; const [x, y] = arr;Destructuring
structuredClone(o)Deep copy
const m = new Map(); m.set(k, v); m.get(k)Map: arbitrary keys
const s = new Set(arr); s.add(x); s.has(x)Set: unique values
Object.fromEntries(paare)Build an object from pairs

Strings

s.length s[0] s.at(-1)Length and character access
s.toUpperCase() s.toLowerCase() s.trim()Upper/lower case, remove whitespace
s.split(",") arr.join(",")Split / join
s.includes("x") s.startsWith("x") s.endsWith("x")Check contains / start / end
s.indexOf("x") s.slice(1, 4)Search / substring
s.replace("a", "b") s.replaceAll("a", "b")Replace (first / all)
s.padStart(5, "0") s.repeat(3)Pad / repeat
`Hallo ${name}!`Template literal with placeholders
s.match(/\d+/g) /^\d+$/.test(s)Regex: find matches / test

Functions & Classes

function f(a, b = 2) { return a + b; }Function with a default value
const f = (a, b) => a + b;Arrow function
function f(...args) {}Rest parameters
f.call(obj, a) f.apply(obj, [a]) f.bind(obj)Set this
(() => { /* ... */ })();Immediately invoked function expression (IIFE)
class A extends B { constructor() { super(); } }Class with inheritance
#privat static x get wert() {}Private fields, static members, getters
x instanceof ACheck membership in a class
function* gen() { yield 1; }Generator function

Async & Errors

setTimeout(fn, 1000) clearTimeout(id)Run once after a delay
setInterval(fn, 1000) clearInterval(id)Run repeatedly
new Promise((resolve, reject) => {})Create a promise
async function f() { await g(); }async/await
Promise.all([p1, p2]) Promise.allSettled([...])Wait for multiple promises
fetch(url).then(r => r.json())Send an HTTP request
try {} catch (e) {} finally {}Error handling
throw new Error("Text")Raise an error
JSON.stringify(o) JSON.parse(s)Object ↔ JSON text

DOM & Browser

document.querySelector("#id .klasse")First matching element
document.querySelectorAll("li")All matching elements
el.textContent = "Text"Set text (safe)
el.classList.add("a") el.classList.toggle("b")Change CSS classes
el.setAttribute("href", "#") el.dataset.idAttributes and data-* values
document.createElement("div") el.append(kind)Create and insert an element
el.addEventListener("click", (e) => {})React to events
localStorage.setItem(k, v) localStorage.getItem(k)Store data permanently in the browser
location.href history.back()Read the address / page history

Modules & Node.js

export const x = 1; export default f;Export
import f, { x } from "./datei.js";Import
const m = await import("./m.js");Dynamic import
npm install paket npm install -D paketInstall a package (runtime / development)
node datei.js node --watch datei.jsRun a file (with automatic restart)
import { readFile } from "node:fs/promises";Read files asynchronously
process.argv process.env.NAMEArguments and environment variables