JavaScript Fortgeschritten Tag 1: Fortgeschrittene Funktionen & Muster

Ziel des Tages

Heute lernst du:

Am Ende wirst du sauberere, wiederverwendbare und leistungsfähigere Funktionen schreiben können.

Schritt 1: Higher-Order Functions

Eine Funktion, die eine andere Funktion als Argument nimmt oder eine Funktion zurückgibt.


const add = x => y => x + y;
console.log(add(2)(3)); // 5

Schritt 2: IIFE

Eine Immediately Invoked Function Expression wird sofort ausgeführt:


(function(){
  console.log("IIFE wird sofort ausgeführt!");
})();

Schritt 3: Currying & Partial Application

Eine Funktion mit mehreren Parametern wird in mehrere Funktionen aufgeteilt:


const multiply = x => y => x * y;
console.log(multiply(2)(3)); // 6

Schritt 4: Funktionskomposition

Mehrere Funktionen werden kombiniert, um eine neue Funktion zu erzeugen:


const compose = (f, g) => x => f(g(x));

const double = x => x * 2;
const square = x => x * x;

console.log(compose(square, double)(3)); // 36

Übung


const add = x => y => x + y;
console.log(add(2)(3));

(function(){
  console.log("IIFE wird sofort ausgeführt!");
})();

Aufgabe

Erledige Folgendes:

Beispiel:


// Curried Multiplikation
const multiply = x => y => x * y;
console.log(multiply(4)(5)); // 20

// IIFE mit Name
(function(){
  console.log("Alex");
})();