JavaScriptLesson 8 of 16
Loops: for, while and for...of
A loop repeats code for as long as needed: for every song, every day or until a sum is saved. Computers never get bored, so we hand them the routine.
Key points
- for (let i = 1; i <= 3; i++) counts: a start, a condition and a step
- for (const item of list) visits every item of an array
- while (…) keeps going while the condition holds; make sure it turns false at some point
- break leaves the loop at once, continue skips the rest of the current round
- A common pattern: let total = 0 before the loop, total += … inside it
Example
for (let i = 1; i <= 3; i++) { console.log(`Round ${i}`);} for (const fruit of ["apple", "kiwi", "mango"]) { if (fruit === "kiwi") continue; console.log(fruit);} // Is the word a palindrome? Walk in from both ends.const word = "level";let left = 0;let right = word.length - 1;let same = true;while (left < right) { if (word[left] !== word[right]) { same = false; break; } left++; right--;}console.log(`${word} is a palindrome: ${same}`);continue skipped kiwi. The palindrome check walks in from both ends with two pointers and stops with break at the first mismatch.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.A fitness tracker logged a week of steps. With for...of, add every day to total and count the days with 8000 steps or more. Then use a while loop to find how many weeks it takes to save 100 if you put aside 15 a week. Print Total: 54000, Active days: 4 and Weeks to save 100: 7.
Output
What your program prints appears here.