Loops
-
map() and filter()
- You can use
map()
to do something to each item in a collection and create a new collection containing the changed items:function toUpper(string) { return string.toUpperCase(); } const cats = ['Leopard', 'Serval', 'Jaguar', 'Tiger', 'Caracal', 'Lion']; const upperCats = cats.map(toUpper); console.log(upperCats); // [ "LEOPARD", "SERVAL", "JAGUAR", "TIGER", "CARACAL", "LION" ]
- You can use
filter()
to test each item in a collection, and create a new collection containing only items that match:function lCat(cat) { return cat.startsWith('L'); } const cats = ['Leopard', 'Serval', 'Jaguar', 'Tiger', 'Caracal', 'Lion']; const filtered = cats.filter(lCat); console.log(filtered); // [ "Leopard", "Lion" ]
- You can use
-
for loop
for
loopconst cats = ['Leopard', 'Serval', 'Jaguar', 'Tiger', 'Caracal', 'Lion']; for (let i = 0; i < cats.length; i++) { console.log(cats[i]); }
for...of
loopconst cats = ['Leopard', 'Serval', 'Jaguar', 'Tiger', 'Caracal', 'Lion']; for (const cat of cats) { console.log(cat); }
- If you want to exit a loop before all the iterations have been completed, you can use the break statement. A
break
statement will immediately exit the loop and make the browser move on to any code that follows it. - The continue statement works similarly to
break
, but instead of breaking out of the loop entirely, it skips to the next iteration of the loop. -
while and do...while
- Syntax for while:
initializer while (condition) { // code to run final-expression }
- Syntax for do...while:
initializer do { // code to run final-expression } while (condition)
- Syntax for while: