typescript · 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.
A while loop has a condition, like an if. While the condition is true, its block runs, then it checks again. As soon as it is false, the loop stops.
You make the counter yourself: a box before the loop, a test in the brackets, and a step inside the block. It is a for loop with its parts spread out.
Forget the step and the condition stays true forever. That is an : it never ends, like a song stuck on repeat. Make sure something inside changes.
let knocks: number = 1;
while (knocks <= 3) {
console.log("Knock knock", knocks);
knocks++;
}
console.log("Who's there?"); If a program seems stuck, look for a loop whose condition can never turn false.
guess first
Munch, munch. How many biscuits are left?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
let biscuits: number = 3;
while (biscuits > 0) {
biscuits = biscuits - 1;
}
console.log("Biscuits left:", biscuits);
your turn
Your turn. Blow up a balloon.
Choose how big the balloon can get before it pops, a number from 2 to 100. Then press run and watch it double.
fix it
The trampoline will not bounce. Fix it!
- Read the error:
TS2454: Variable 'jumps' is used before being assigned. - The box exists, but nothing was ever put in it. The loop cannot compare an empty box with 3.
- Give the box a starting value: let jumps: number = 0; then press run.
nailed it
your loops know when to stop. :D
- A
whileloop repeats while its condition istrue. - Make the counter before the loop, and step it inside.
- No step means an infinite loop that never ends.
new words in your collection
- while
- infinite loop
This lesson isn’t saved. A free account remembers every lesson you finish.