JSJavaScript

JavaScript: Advanced – code examples

Contents

Destructuring in practice

Advanced#destructuring#rest#default
Use case: Unpack nested API responses cleanly and set default values.
const user = { id: 7, name: "Ada", adresse: { stadt: "London", plz: "N1" } };
const { name, adresse: { stadt }, rolle = "gast" } = user;
console.log(name, stadt, rolle);

const [erstes, , drittes = 0, ...rest] = [1, 2, undefined, 4, 5];
console.log(erstes, drittes, rest);

Nested patterns, default values and rest work together; a gap in the array pattern skips an element.

Merging objects and arrays

Advanced#spread#merge#immutable
Use case: Mix configurations with defaults without modifying the original.
const standard = { theme: "hell", laut: false, pos: { x: 0, y: 0 } };
const eigene = { laut: true };
const conf = { ...standard, ...eigene, pos: { ...standard.pos, x: 5 } };
console.log(conf);

const teil = [1, 2];
const alle = [0, ...teil, 3];
console.log(alle, Math.max(...alle));

Later values overwrite earlier ones. Nested objects have to be spread again yourself (spread copies shallowly).

Optional chaining & nullish

Advanced#optional chaining#nullish#safe
Use case: Safely access deeply nested API data without a TypeError.
const antwort = { daten: { nutzer: [{ name: "Ada" }] } };
console.log(antwort.daten?.nutzer?.[0]?.name);
console.log(antwort.fehler?.text ?? "no error");
console.log(antwort.holeName?.() ?? "no method");

?. stops at null/undefined and returns undefined (also for indexing ?.[i] and calls ?.()); ?? then supplies the default value.

Closure: private counter

Advanced#closure#scope#encapsulation
Use case: Encapsulate state without using classes or global variables.
function erzeugeZaehler(start = 0) {
  let n = start;
  return {
    increment: () => ++n,
    wert: () => n,
    reset: () => { n = start; }
  };
}
const z = erzeugeZaehler(10);
z.increment();
z.increment();
console.log(z.wert());
z.reset();
console.log(z.wert());

The inner functions keep access to n, which is unreachable from outside – a closure.

Debounce for input

Advanced#debounce#timer#closure
Use case: Send search requests only once the user has briefly stopped typing.
function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}

const suche = debounce((text) => console.log("Search for:", text), 100);
suche("j");
suche("ja");
suche("jav");   // only this last call is executed

Every new call resets the timer – a closure over timer. throttle works similarly (at most once every n ms).

Generator

Advanced#yield#generator#iterator
Use case: Process large or infinite sequences piece by piece without holding everything in memory.
function* zaehleBis(n) {
  for (let i = 1; i <= n; i++) yield i;
}
console.log([...zaehleBis(5)]);
let summe = 0;
for (const x of zaehleBis(100)) summe += x;
console.log(summe);

function* endlos() {
  let i = 0;
  while (true) yield i++;
}
const it = endlos();
console.log(it.next().value, it.next().value, it.next().value);

yield pauses the function and delivers the next value; the infinite sequence is computed only as far as you ask for it.