Heute wirst du lernen:
let und constAm Ende verstehst du, wie Variablen in JavaScript funktionieren und wie lange sie “leben”.
Scope bestimmt, wo eine Variable verfügbar ist.
let und const sind Variablen nur im Block gültigEine Closure ist eine Funktion, die sich an Variablen aus ihrem äußeren Scope erinnert, auch wenn dieser bereits ausgeführt wurde.
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
Erklärung:
inner hat weiterhin Zugriff auf count, obwohl outer bereits beendet ist
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
Erstelle eine Counter-Funktion mit Closure, die:
Beispiel:
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const myCounter = createCounter();
console.log(myCounter()); // 1
console.log(myCounter()); // 2
console.log(myCounter()); // 3