EMZETT.
Login

Kurz: Arrow-Funktionen (Pfeilfunktionen) sind eine kurze Schreibweise für Funktionen, eingeführt in ES2015. Sie werden heute ständig benutzt, vor allem als Argument für map, filter und Co.

Teil des Kurses JavaScript

Kapitel 11 von 40 im Kurs JavaScript. Mit Fortschritt, Quiz und Zertifikat auf der Lernseite.

Arrow-Funktionen (Pfeilfunktionen) sind eine kurze Schreibweise für Funktionen, eingeführt in ES2015. Sie werden heute ständig benutzt, vor allem als Argument für map, filter und Co.

Syntax

const addiere = (a, b) => a + b;
const quadrat = x => x * x;               // ein Parameter: Klammern optional
const hallo = () => "Hallo";              // keine Parameter
const rechne = (a, b) => {                // Block: return nötig
  const summe = a + b;
  return summe * 2;
};
console.log(addiere(2, 3), quadrat(6), hallo(), rechne(1, 2));

Ausgabe:

5 36 Hallo 6

Passt der Rumpf in einen Ausdruck, kannst du { } und return weglassen. Soll ein Objekt direkt zurückgegeben werden, setze es in runde Klammern:

const punkt = (x, y) => ({ x, y });
console.log(punkt(3, 4));

Ausgabe:

{ x: 3, y: 4 }

Vergleich: normal und Arrow

const zahlen = [1, 2, 3, 4];
 
const a = zahlen.map(function (x) { return x * 2; });
const b = zahlen.map(x => x * 2);
console.log(a, b);
console.log(zahlen.filter(x => x % 2 === 0));
console.log(zahlen.reduce((summe, x) => summe + x, 0));

Ausgabe:

[ 2, 4, 6, 8 ] [ 2, 4, 6, 8 ]
[ 2, 4 ]
10

Der Unterschied bei this

Der wichtigste inhaltliche Unterschied: Eine Arrow-Funktion hat kein eigenes this, sondern übernimmt es von außen. Das ist in Klassen und Callbacks hilfreich:

class Zaehler {
  constructor() { this.stand = 0; }
  startMitNormal() {
    [1, 2, 3].forEach(function () {
      try { this.stand++; } catch (e) { console.log("normal:", e.constructor.name); }
    });
  }
  startMitArrow() {
    [1, 2, 3].forEach(() => { this.stand++; });
    return this.stand;
  }
}
const z = new Zaehler();
z.startMitNormal();
console.log("arrow:", z.startMitArrow());

Ausgabe:

normal: TypeError
normal: TypeError
normal: TypeError
arrow: 3

Weitere Unterschiede: Arrow-Funktionen haben kein arguments, können nicht mit new aufgerufen werden und eignen sich nicht als Objektmethoden, wenn du this brauchst.

Wann was?

  • Arrow: Callbacks, kurze Hilfsfunktionen, Funktionen in Methoden
  • function-Deklaration: benannte Funktionen auf oberster Ebene, wenn du Hoisting willst
  • Methodenschreibweise: { methode() { ... } } für Objektmethoden

Funktionen höherer Ordnung

Funktionen, die andere Funktionen aufnehmen oder zurückgeben, heißen Higher-Order-Functions:

const mal = faktor => zahl => zahl * faktor;   // gibt eine Funktion zurück
const verdopple = mal(2);
const verdreifache = mal(3);
console.log(verdopple(10), verdreifache(10));
 
const log = (fn) => (...args) => {
  const ergebnis = fn(...args);
  console.log(`${fn.name || "fn"}(${args}) = ${ergebnis}`);
  return ergebnis;
};
const plus = (a, b) => a + b;
log(plus)(2, 3);

Ausgabe:

20 30
plus(2,3) = 5

Sofort ausgeführte Funktionen (IIFE)

const ergebnis = (() => {
  const geheim = 42;
  return geheim + 1;
})();
console.log(ergebnis);

Ausgabe:

43

Merke

  • (a, b) => a + b ist die Kurzform; bei einem Ausdruck entfallen {} und return
  • Objekt zurückgeben: () => ({ ... })
  • Arrow-Funktionen übernehmen this von außen
  • Sie sind ideal für Callbacks; nicht für Konstruktoren
  • Funktionen höherer Ordnung nehmen Funktionen auf oder geben welche zurück

Übungsaufgabe

Schreibe const verdopple = x => ..., wende sie mit map auf [1, 2, 3] an, und baue eine Funktion mal(faktor), die eine Multiplikationsfunktion zurückgibt.

Quiz zur Selbstkontrolle

Weiter im Kurs

Zurück: Funktionen

Weiter: Gültigkeitsbereich und Closures

Alle Kapitel: JavaScript im Überblick