JavaScript — Grundlagen
Kapitel 9 · Praxis

Praxis — Mini-Skripte

  1. 1) Click-Counter. Bei jedem Klick auf einen Button hochzählen.
    let count = 0;
    btn.addEventListener("click", () => {
      count++;
      output.textContent = `Klicks: ${count}`;
    });
  2. 2) Live-Suche. Liste filtern beim Tippen.
    input.addEventListener("input", () => {
      const q = input.value.toLowerCase();
      items.forEach(i => {
        i.style.display = i.textContent.toLowerCase().includes(q) ? "" : "none";
      });
    });
  3. 3) Fetch mit async/await.
    async function getUser(id) {
      const r = await fetch(`/api/users/${id}`);
      if (!r.ok) throw new Error("404");
      return r.json();
    }
  4. 4) Debounce. Funktion erst N ms nach letztem Trigger ausführen.
    function debounce(fn, ms) {
      let timer;
      return (...args) => {
        clearTimeout(timer);
        timer = setTimeout(() => fn(...args), ms);
      };
    }
    const search = debounce(q => fetch("/search?q=" + q), 300);
  5. 5) localStorage — Daten persistieren.
    localStorage.setItem("name", "Anna");
    const name = localStorage.getItem("name");
    // JSON für Objekte:
    localStorage.setItem("user", JSON.stringify({id: 1}));
    const user = JSON.parse(localStorage.getItem("user"));
  6. 6) Destructuring.
    const {name, alter} = person;
    const [a, b, ...rest] = [1, 2, 3, 4, 5];
    function f({x, y = 0}) { return x + y; }   // Default-Werte
  7. 7) Modul-Import.
    // utils.js
    export function add(a, b) { return a + b; }
    export default function main() { /* ... */ }
    
    // app.js
    import main, { add } from './utils.js';
Zurück zu Informatik