JavaScript Loops
Loops (Schleifen) wiederholen Code automatisch mehrmals. Perfekt um durch Listen zu gehen oder Aktionen zu wiederholen.
Was sind Loops?
Loops führen Code wiederholt aus:
// Ohne Loop (mühsam!)
console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);
// Mit Loop (elegant!)
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Ausgabe: 1, 2, 3, 4, 5Wann braucht man Loops?
- Arrays durchgehen
- Wiederholte Aktionen
- Zählen
- Daten verarbeiten
for Loop - Der Klassiker
Der häufigste Loop:
for (start; bedingung; schritt) {
// Code wird wiederholt
}
// Beispiel
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Ausgabe: 0, 1, 2, 3, 4Die 3 Teile:
- Start:
let i = 0(Startwert) - Bedingung:
i < 5(Wann stoppen?) - Schritt:
i++(Nach jeder Runde)
for Loop Beispiele
// Von 0 bis 4
for (let i = 0; i < 5; i++) {
console.log(i);
}
// 0, 1, 2, 3, 4
// Von 1 bis 10
for (let i = 1; i <= 10; i++) {
console.log(i);
}
// 1, 2, 3, ..., 10
// Rückwärts zählen
for (let i = 5; i > 0; i--) {
console.log(i);
}
// 5, 4, 3, 2, 1
// In 2er Schritten
for (let i = 0; i <= 10; i += 2) {
console.log(i);
}
// 0, 2, 4, 6, 8, 10
// Nur gerade Zahlen
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
console.log(i + ' ist gerade');
}
}Arrays mit for durchgehen
const namen = ['Max', 'Anna', 'Tom', 'Lisa'];
// Mit Index
for (let i = 0; i < namen.length; i++) {
console.log(namen[i]);
}
// Max, Anna, Tom, Lisa
// Mit Nummerierung
for (let i = 0; i < namen.length; i++) {
console.log(`${i + 1}. ${namen[i]}`);
}
// 1. Max
// 2. Anna
// 3. Tom
// 4. Lisa
// Rückwärts durch Array
const zahlen = [1, 2, 3, 4, 5];
for (let i = zahlen.length - 1; i >= 0; i--) {
console.log(zahlen[i]);
}
// 5, 4, 3, 2, 1while Loop - Solange wie...
Loop läuft solange Bedingung wahr ist:
while (bedingung) {
// Code wiederholen
}
// Beispiel
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// 0, 1, 2, 3, 4Wichtig: Variable muss außerhalb definiert sein!
while Loop Beispiele
// Zähler
let count = 1;
while (count <= 5) {
console.log('Count: ' + count);
count++;
}
// Mit Bedingung
let passwort = '';
while (passwort !== 'geheim') {
passwort = prompt('Passwort eingeben:');
}
console.log('Richtig!');
// Summe berechnen
let summe = 0;
let zahl = 1;
while (zahl <= 10) {
summe += zahl;
zahl++;
}
console.log('Summe: ' + summe); // 55
// Rückwärts
let countdown = 5;
while (countdown > 0) {
console.log(countdown);
countdown--;
}
console.log('Start!');
// 5, 4, 3, 2, 1, Start!do...while Loop - Mindestens einmal
Loop wird mindestens einmal ausgeführt:
do {
// Code (mindestens 1x)
} while (bedingung);
// Beispiel
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
// 0, 1, 2, 3, 4Unterschied zu while:
// while: Kann 0x ausgeführt werden
let x = 10;
while (x < 5) {
console.log(x); // Wird NICHT ausgeführt
}
// do...while: Mindestens 1x
let y = 10;
do {
console.log(y); // Wird 1x ausgeführt
} while (y < 5);
// Ausgabe: 10do...while Beispiele
// User Input
let antwort;
do {
antwort = prompt('Sag "ja" oder "nein"');
} while (antwort !== 'ja' && antwort !== 'nein');
console.log('Danke!');
// Würfelspiel
let würfel;
do {
würfel = Math.floor(Math.random() * 6) + 1;
console.log('Gewürfelt: ' + würfel);
} while (würfel !== 6);
console.log('6 gewürfelt! Gewonnen!');for...of - Durch Werte iterieren
Modern & einfach für Arrays:
const array = [wert1, wert2, wert3];
for (const wert of array) {
console.log(wert);
}
// Beispiel
const namen = ['Max', 'Anna', 'Tom'];
for (const name of namen) {
console.log('Hallo ' + name);
}
// Hallo Max
// Hallo Anna
// Hallo TomVorteile:
- ✅ Kein Index nötig
- ✅ Lesbarer Code
- ✅ Weniger Fehler
// Zahlen
const zahlen = [10, 20, 30, 40, 50];
for (const zahl of zahlen) {
console.log(zahl * 2);
}
// 20, 40, 60, 80, 100
// Strings durchgehen
const text = 'Hallo';
for (const buchstabe of text) {
console.log(buchstabe);
}
// H, a, l, l, o
// Objekte in Array
const users = [
{ name: 'Max', age: 25 },
{ name: 'Anna', age: 30 }
];
for (const user of users) {
console.log(`${user.name} ist ${user.age} Jahre alt`);
}for...in - Durch Keys iterieren
Für Object Properties:
const object = { key1: wert1, key2: wert2 };
for (const key in object) {
console.log(key); // Key
console.log(object[key]); // Wert
}
// Beispiel
const person = {
name: 'Max',
age: 25,
city: 'Berlin'
};
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
// name: Max
// age: 25
// city: BerlinAuch für Arrays (aber nicht empfohlen):
const zahlen = [10, 20, 30];
// ❌ Funktioniert, ist aber verwirrend
for (const index in zahlen) {
console.log(index); // '0', '1', '2' (Strings!)
console.log(zahlen[index]);
}
// ✅ BESSER: for...of für Arrays
for (const zahl of zahlen) {
console.log(zahl); // 10, 20, 30
}forEach - Array Method
Moderne Array-Methode:
array.forEach(function(element) {
// Code für jedes Element
});
// Beispiel
const namen = ['Max', 'Anna', 'Tom'];
namen.forEach(function(name) {
console.log('Hallo ' + name);
});
// Mit Arrow Function (modern!)
namen.forEach(name => {
console.log('Hallo ' + name);
});Mit Index und Array:
const namen = ['Max', 'Anna', 'Tom'];
// Alle Parameter
namen.forEach((name, index, array) => {
console.log(`${index + 1}. ${name}`);
console.log('Array Länge:', array.length);
});
// 1. Max
// Array Länge: 3
// 2. Anna
// Array Länge: 3
// ...
// Nur Index
namen.forEach((name, index) => {
console.log(`[${index}]: ${name}`);
});
// [0]: Max
// [1]: Anna
// [2]: Tombreak - Loop vorzeitig beenden
Stoppt den Loop sofort:
// Stoppt bei bestimmtem Wert
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Loop endet hier
}
console.log(i);
}
// 0, 1, 2, 3, 4
// Suche in Array
const zahlen = [1, 5, 8, 10, 15, 20];
let gefunden = false;
for (const zahl of zahlen) {
if (zahl === 10) {
console.log('10 gefunden!');
gefunden = true;
break; // Nicht weiter suchen
}
}
// Mit while
let count = 0;
while (true) { // Endlos-Loop
count++;
console.log(count);
if (count === 5) {
break; // Beendet Loop
}
}continue - Iteration überspringen
Springt zur nächsten Iteration:
// Überspringt bestimmte Werte
for (let i = 0; i < 10; i++) {
if (i === 5) {
continue; // Überspringt 5
}
console.log(i);
}
// 0, 1, 2, 3, 4, 6, 7, 8, 9
// Nur gerade Zahlen
for (let i = 0; i < 10; i++) {
if (i % 2 !== 0) {
continue; // Überspringt ungerade
}
console.log(i);
}
// 0, 2, 4, 6, 8
// Filtern
const namen = ['Max', '', 'Anna', '', 'Tom'];
for (const name of namen) {
if (name === '') {
continue; // Leere Namen überspringen
}
console.log(name);
}
// Max, Anna, TomVerschachtelte Loops
Loops in Loops:
// Multiplikationstabelle
for (let i = 1; i <= 5; i++) {
for (let j = 1; j <= 5; j++) {
console.log(`${i} x ${j} = ${i * j}`);
}
console.log('---');
}
// 2D Array
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
for (let zeile = 0; zeile < matrix.length; zeile++) {
for (let spalte = 0; spalte < matrix[zeile].length; spalte++) {
console.log(`[${zeile}][${spalte}] = ${matrix[zeile][spalte]}`);
}
}
// Muster erstellen
for (let i = 1; i <= 5; i++) {
let zeile = '';
for (let j = 1; j <= i; j++) {
zeile += '* ';
}
console.log(zeile);
}
// *
// * *
// * * *
// * * * *
// * * * * *Praktische Beispiele
Beispiel 1: Summe berechnen
const zahlen = [10, 20, 30, 40, 50];
let summe = 0;
for (const zahl of zahlen) {
summe += zahl;
}
console.log('Summe:', summe); // 150
// Mit for Loop
let summe2 = 0;
for (let i = 0; i < zahlen.length; i++) {
summe2 += zahlen[i];
}
console.log('Summe:', summe2); // 150Beispiel 2: Maximum finden
const zahlen = [15, 8, 42, 23, 16];
let max = zahlen[0]; // Startwert
for (const zahl of zahlen) {
if (zahl > max) {
max = zahl;
}
}
console.log('Maximum:', max); // 42Beispiel 3: Array filtern
const zahlen = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const gerade = [];
for (const zahl of zahlen) {
if (zahl % 2 === 0) {
gerade.push(zahl);
}
}
console.log(gerade); // [2, 4, 6, 8, 10]Beispiel 4: String umkehren
const text = 'Hallo';
let reversed = '';
for (let i = text.length - 1; i >= 0; i--) {
reversed += text[i];
}
console.log(reversed); // ollaH
// Mit for...of
let reversed2 = '';
for (const buchstabe of text) {
reversed2 = buchstabe + reversed2;
}
console.log(reversed2); // ollaHBeispiel 5: Fakultät berechnen
// 5! = 5 * 4 * 3 * 2 * 1 = 120
const n = 5;
let fakultät = 1;
for (let i = 1; i <= n; i++) {
fakultät *= i;
}
console.log(`${n}! = ${fakultät}`); // 5! = 120Beispiel 6: Countdown
let countdown = 10;
const timer = setInterval(() => {
console.log(countdown);
if (countdown === 0) {
console.log('Start!');
clearInterval(timer);
}
countdown--;
}, 1000); // Jede SekundeBeispiel 7: Fibonacci-Folge
// Erste 10 Fibonacci-Zahlen
const n = 10;
const fibonacci = [0, 1];
for (let i = 2; i < n; i++) {
fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
}
console.log(fibonacci);
// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]Beispiel 8: Array transformieren
const zahlen = [1, 2, 3, 4, 5];
const verdoppelt = [];
for (const zahl of zahlen) {
verdoppelt.push(zahl * 2);
}
console.log(verdoppelt); // [2, 4, 6, 8, 10]
// Namen großschreiben
const namen = ['max', 'anna', 'tom'];
const kapitalisiert = [];
for (const name of namen) {
kapitalisiert.push(name[0].toUpperCase() + name.slice(1));
}
console.log(kapitalisiert); // ['Max', 'Anna', 'Tom']Loop-Vergleich
Wann was nutzen?
const array = [1, 2, 3, 4, 5];
// ✅ for - Volle Kontrolle, Index wichtig
for (let i = 0; i < array.length; i++) {
console.log(i, array[i]);
}
// ✅ for...of - Einfach, moderne Arrays
for (const item of array) {
console.log(item);
}
// ✅ forEach - Functional Style
array.forEach((item, index) => {
console.log(index, item);
});
// ✅ while - Bedingungsbasiert
let i = 0;
while (i < array.length) {
console.log(array[i]);
i++;
}
// ✅ for...in - Für Objects
const obj = { a: 1, b: 2 };
for (const key in obj) {
console.log(key, obj[key]);
}Faustregel:
- for...of: Moderne Arrays (einfach & lesbar)
- forEach: Functional Programming
- for: Brauche Index/Kontrolle
- while: Bedingungsbasiert
- for...in: Objects
Best Practices
✅ DO:
- for...of für Arrays (modern & lesbar)
- const in Loops wenn möglich
- Früh break bei Suche
- Aussagekräftige Namen (nicht nur
i) - Array.length cachen bei großen Arrays
// ✅ for...of
const namen = ['Max', 'Anna', 'Tom'];
for (const name of namen) {
console.log(name);
}
// ✅ Früh break
for (const name of namen) {
if (name === 'Anna') {
console.log('Gefunden!');
break;
}
}
// ✅ Length cachen (Performance)
const length = bigArray.length;
for (let i = 0; i < length; i++) {
// ...
}
// ✅ Aussagekräftige Namen
for (const user of users) {
console.log(user.name);
}
for (const product of products) {
console.log(product.price);
}❌ DON'T:
- Nicht Array in Loop modifizieren
- Nicht zu tief verschachteln
- Nicht forEach mit break/continue
- Nicht Endlos-Loops ohne Ausstieg
// ❌ SCHLECHT: Array in Loop ändern
const zahlen = [1, 2, 3, 4, 5];
for (let i = 0; i < zahlen.length; i++) {
zahlen.push(i); // Loop endet nie!
}
// ❌ SCHLECHT: Zu tief verschachtelt
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
for (let k = 0; k < 10; k++) {
// Zu komplex!
}
}
}
// ❌ SCHLECHT: break in forEach
array.forEach(item => {
if (item === 5) {
break; // ❌ Funktioniert nicht!
}
});
// ✅ BESSER: for...of mit break
for (const item of array) {
if (item === 5) {
break; // ✅ Funktioniert
}
}
// ❌ SCHLECHT: Endlos-Loop
while (true) {
// Kein break = läuft ewig!
}Performance-Tipps
const bigArray = new Array(1000000).fill(0);
// ❌ Langsam: length jedes Mal berechnen
for (let i = 0; i < bigArray.length; i++) {
// ...
}
// ✅ Schneller: length cachen
const length = bigArray.length;
for (let i = 0; i < length; i++) {
// ...
}
// ✅ Am schnellsten: for...of
for (const item of bigArray) {
// ...
}TipsAndTricks
Tipps & Tricks
for...of statt klassischem for Loop
Moderne Syntax für cleanen Code:
const namen = ['Max', 'Anna', 'Tom'];
// ❌ Alt: Index-basiert
for (let i = 0; i < namen.length; i++) {
console.log(namen[i]);
}
// ✅ Neu: for...of
for (const name of namen) {
console.log(name);
}
// Mit Index wenn nötig
for (const [index, name] of namen.entries()) {
console.log(`${index}: ${name}`);
}
Array Methods statt Loops
Nutze moderne Array-Methoden für typische Aufgaben:
const zahlen = [1, 2, 3, 4, 5];
// Statt Loop zum Verdoppeln
const doubled = zahlen.map(n => n * 2); // [2, 4, 6, 8, 10]
// Statt Loop zum Filtern
const gerade = zahlen.filter(n => n % 2 === 0); // [2, 4]
// Statt Loop zum Summieren
const summe = zahlen.reduce((acc, n) => acc + n, 0); // 15
Break und Continue clever einsetzen
Optimiere Loop-Performance:
// Break: Früher Ausstieg
for (const user of users) {
if (user.id === targetId) {
console.log('Gefunden!');
break; // Stoppt Loop
}
}
// Continue: Überspringen
for (const number of numbers) {
if (number % 2 !== 0) continue; // Ungerade überspringen
console.log(number); // Nur gerade Zahlen
}
Array.length cachen für Performance
Bei großen Arrays macht das einen Unterschied:
const bigArray = new Array(1000000).fill(0);
// ❌ Langsam: length wird jedes Mal berechnet
for (let i = 0; i < bigArray.length; i++) { }
// ✅ Schneller: length cachen
const length = bigArray.length;
for (let i = 0; i < length; i++) { }
// ✅ Am besten: for...of (optimiert)
for (const item of bigArray) { }
📝 Quiz
Was ist der Unterschied zwischen for...of und for...in?
📝 Quiz
Kann man break in forEach nutzen?
Übungsaufgaben
Aufgabe 1: Zahlen ausgeben
Erstelle Loops die:
- 1 bis 100 ausgeben
- Nur gerade Zahlen
- Rückwärts von 50 bis 1
Aufgabe 2: Array verarbeiten
Erstelle Array mit Zahlen:
- Berechne die Summe
- Finde Maximum
- Zähle gerade Zahlen
Aufgabe 3: Multiplikationstabelle
Erstelle mit verschachtelten Loops:
- 1x1 bis 10x10
- Formatiert ausgeben
Aufgabe 4: Primzahlen
Schreibe Loop der:
- Alle Primzahlen bis 100 findet
- In Array speichert
- Ausgibt
Nächste Schritte
Du kennst jetzt:
- ✅ for, while, do-while Loops
- ✅ for...of und for...in
- ✅ forEach Array Method
- ✅ break und continue
- ✅ Verschachtelte Loops
- ✅ Praktische Anwendungen
- ✅ Best Practices & Performance
Als Nächstes lernst du:
- Functions (function, arrow functions)
- Parameters & Return Values
- Scope & Closure
- Higher-Order Functions
Weiter so! 🚀
Gut gemacht! 🎉
Du hast "JavaScript Loops - for, while, forEach" abgeschlossen
Artikel bewerten
Bitte einloggen um zu bewerten
Das könnte dich auch interessieren
JavaScript Grundlagen: Deine erste Programmierung
Lerne JavaScript von Null! Variablen, Funktionen, Events - alles was du brauchst um interaktive Webseiten zu erstellen.
JavaScript Arrays - Listen & Array Methods
Lerne JavaScript Arrays: Erstellung, Zugriff, push, pop, map, filter, reduce, forEach, find, spread, destructuring und Best Practices.
JavaScript Conditionals - if, else, switch
Lerne JavaScript Conditionals: if, else, else if, switch - Vergleiche, Logische Operatoren, Truthy/Falsy und Best Practices für Bedingungen.