javascript · level 1 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A loop keeps going while something is true.
Think of knocking on a door. You keep knocking while nobody answers, and you do not know how many knocks it will take. A while loop works the same way: it repeats as long as its condition is true.
Most while loops use a counting variable. Make it before the loop with let. Check it in the condition. Change it inside the block, so the condition turns false one day and the loop ends.
Forget to change it and the condition stays true forever. That is an : the program goes round and round and never moves on. The fix is always to change the variable inside the loop.
let count = 1;
while (count <= 3) {
console.log("Knock knock", count);
count++;
}
console.log("Who's there?"); Use for when you know how many turns you need, and while when you do not.
guess first
How many times will you say Nom?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
let cookies = 3;
while (cookies > 0) {
console.log("Nom");
cookies = cookies - 1;
}
console.log("All gone!");
your turn
Your turn. Count down to lift off.
Type a number to count down from in the first blank, and what to say at the end between the quotes. Then press run.
fix it
The trampoline will not start. Can you fix it?
- It is a ReferenceError. Which name has JavaScript never heard of?
- The loop checks
jumps, but no box called jumps was ever made. Make it before the loop. - Add let jumps = 0; as a new first line, then press run.
nailed it
you can loop until the job is done. :D
- A
whileloop repeats as long as its condition istrue. - Make the counter before the loop and change it inside.
- If the counter never changes, you get an infinite loop.
new words in your collection
- while
- infinite loop
This lesson isn’t saved. A free account remembers every lesson you finish.