Loops
Schleifen benötigen wir, um einen Code mehrmals auszuführen. Es gibt mehrere Möglichkeiten, die Anzahl der Schleifen zu bestimmen.
- Wir setzen selbst eine bestimmte Zahl fest (
forLoop) - Wir führen Code aus, solange eine Bedingung wahr ist (
whileLoop) - Wir iterieren über die Elemente eines Arrays (
for,for-of,forEach)
For loop
Section titled “For loop”Eine for Schleife führt einen Code mehrmals aus – so oft wir wollen. Die Syntax für eine for Schleife sieht so aus:
for (initialExpression; condition; incremetExpression) { statement;}Ein Beispiel, Schritt für Schritt erklärt:
for (let i = 0; i < 2; i++) { const timesBounced = i + 1; console.log(`The ball has bounced ${timesBounced} times.`);}console.log("This is the next line of code.");1. Iteration
- JavaScript sieht die Schleife, deklariert die Variable
iund setzt sie gleich0. - JavaScript prüft, ob die Bedingung wahr ist.
1 < 10ist wahr. Nun führt JavaScript den Codeblock aus. Jedesiwird durch0ersetzt. timesBounced = 0 + 1evaluiert zutimesBounced = 1- Die Konsolenausgabe lautet also:
The ball has bounced 1 times. - Nun springt JavaScript wieder nach oben und führt die
increment expressionaus:i++bedeuteti = i + 1, d.h.i = 0 + 1, das evaluiert zu1.
2. Iteration
- JavaScript prüft wieder die Bedingung:
1 < 2ist immer noch wahr, der Codeblock wird ein weiteres Mal ausgeführt. - Nun wird
iüberall durch1ersetzt:timesBounced = 1 + 1ergibt2. - Die Konsolenausgabe lautet:
The ball has bounced 2 times. - JavaScript springt wieder zur
increment expression:1++heißti = 1 + 1, das ergibt2.
3. Iteration
- JavaScript prüft ein weiteres Mal die Bedinung:
2 < 2istfalse. - JavaScript bricht die Schleife ab und geht zur nächsten Codezeile weiter.
- Die Konsolenausgabe lautet nun:
This is the next line of code.
Looping through arrays
Section titled “Looping through arrays”In der Praxis iteriert man fast immer über einen Array oder ein Objekt. Wenn man über einen Array iteriert, geht man einmal durch alle Items im Array. Als Bedingung nutzt man die Länge des Arrays. Die Variable i entspricht dem Index [i] der Array Items, somit kann über die Array Items iteriert werden.
const fruitBasket = ['banana', 'pear', 'guava'];for (let i = 0; i < fruitBasket.length; i++) { console.log(`There's a ${fruitBasket[i]} in the basket.`);}Negative increment expression
Section titled “Negative increment expression”Man kann eine for Schleife auch mit einer negativen increment expression schreiben. Die Schleife durchläuft das Array von hinten nach vorne. Man verwendet das, wenn man eine super performante Anwendung baut, in der (normalen) Website-Praxis braucht man sich um Performance bei for Schleifen keine Gedanken zu machen.
for (let i = fruitBasket.length - 1; i >= 0; i--) { console.log(`There's a ${fruitBasket[i]} in the basket.`);}Logic within for loops
Section titled “Logic within for loops”Innerhalb einer for Loop können logische Ausdrücke wie if/else verwendet werden.
const numbers = [25, 22, 12, 56, 8, 18, 34];
for (let i = 0; i < numbers.length -1; i++) { const num = numbers[i]; if (num < 20) { console.log(`${num} is less than 20!`); };};Infinite loops
Section titled “Infinite loops”Wenn eine Bedingung immer zu true evaluiert, hängt sich der Browser in einer unendlichen Schleife auf. Dann hilft nur Code löschen und den Browser neu laden (und eventuell über den Taskmanager beenden).
for (let i = 1; i < 1, i--) { console.log('Haha! You are stuck!');}For-of loop
Section titled “For-of loop”Die for-of Schleife ist eine sehr viel bessere Methode, um über einen Array zu iterieren. Sie durchläuft einen Array immer genau ein Mal und benötigt weder die Länge des Arrays noch eine increment expression. Der Code kann viel einfacher gelesen und gepflegt werden.
for (let fruit of fruitBasket) { console.log(`There's a ${fruit} in the basket.`);}ForEach loop
Section titled “ForEach loop”Alle Arrays besitzen die forEach Methode. Damit kann – mit einfacher Schreibweise – über alle Elemente des Arrays iteriert werden.
Die forEach Methode akzeptiert eine Callback-Funktion, die wiederum drei Argumente annimmt:
currentValuebezieht sich auf das aktuelle Element im Arrayindexist die Position des Elements im Array (zero-based)arraybezieht sich auf den Array, über den gerade iteriert wird (dieses Argument wird meistens nicht benötigt) In der Praxis wird meistens nur das erste Argument (currentValue) eingesetzt.
array.forEach((currentValue, index, array) => { // your statement here});
// you can omit index and array most of the time:array.forEach(currentValue => { // your statement here});Fruitbasket Beispiel von oben:
const fruitBasket = ['banana', 'pear', 'guava'];fruitBasket.forEach(function (fruit) { console.log(`There's a ${fruit} in the basket.`);});Mit Arrow-Function und implicit return
fruitBasket.forEach(fruit => { console.log(`There's a ${fruit} in the basket.`);});// noch kürzer mit implicit returnfruitBasket.forEach(fruit => console.log(`There's a ${fruit} in the basket.`));Falls doch einmal der index benötigt wird, ist die Schreibweise so:
fruitBasket.forEach((fruit, index) => console.log(fruit, index));Excercises
Section titled “Excercises”for/for-of
Section titled “for/for-of”const numbers = [1, 12, 4, 18, 9, 7, 11, 3, 50, 5, 6];- Loop through the numbers and
console.logeach number within. - Loop through the numbers. If the numbers are greater than 5,
console.logthem. - Create a new array. Add all numbers that are greater than 10 into this new array (and mind the order).
- Create a new array. Multiply all numbers by 5 and put them into the new array.
forEach
Section titled “forEach”const people = [ { firstName: 'Benjamin', lastName: 'Franklin', yearOfDeath: '1790'}, { firstName: 'Thomas', lastName: 'Edison', yearOfDeath: '1931'}, { firstName: 'Franklin', lastName: 'Roosevelt', yearOfDeath: '1945'}, { firstName: 'Napoleon', lastName: 'Bonaparte', yearOfDeath: '1821'}, { firstName: 'Abraham', lastName: 'Lincoln', yearOfDeath: '1865'}, { firstName: 'Mother', lastName: 'Theresa', yearOfDeath: '1997'}, { firstName: 'Mahatma', lastName: 'Gandhi', yearOfDeath: '1948'}, { firstName: 'Winston', lastName: 'Churchill', yearOfDeath: '1965'}, { firstName: 'Charles', lastName: 'Darwin', yearOfDeath: '1882'}, { firstName: 'Albert', lastName: 'Einstein', yearOfDeath: '1995'}, { firstName: 'Pablo', lastName: 'Picasso', yearOfDeath: '1973'}, { firstName: 'Ludwig', lastName: 'van Beethoven', yearOfDeath: '1827'}, { firstName: 'Walt', lastName: 'Disney', yearOfDeath: '1966'}, { firstName: 'Henry', lastName: 'Ford', yearOfDeath: '1947'}, { firstName: 'Steve', lastName: 'JObs', yearOfDeath: '2012'},]console.logthe first name of each person in the array.- Make a second array that contains only the first name of each person.
- Make a third array that contains people that have died after 1950.
- Find index of Charles Darwin in the array.
// 1. console.log the first name of each person in the array.people.forEach(person => console.log(person.firstName));
// 2. Make a second array that contains only the first name of each person.const firstNames = [];people.forEach(person => firstNames.push(person.firstName));console.log(firstNames);
// 3. Make a third array that contains people that have died after 1950.const diedAfter1950 = [];people.forEach(person => { if (person.yearOfDeath > 1950) { diedAfter1950.push(person); };});console.log(diedAfter1950);
// 4. Find index of Charles Darwin in the array.// if sth. cannot be found, index should be -1let darwinIndex = -1;people.forEach((person, index) => { console.log(person, index); if (person.firstName === 'Charles' && person.lastName === 'Darwin') { darwinIndex = index; };});console.log(darwinIndex);
// eleganter geht das aber mit findIndex()const darwinIndex = people.findIndex(person => (person.firstName === 'Charles' && person.lastName === 'Darwin'));console.log(darwinIndex);