for loops · boucles for
Repeating with a for loop
- A loop runs the same block many times, so you don't repeat yourself.
for (let i = 1; i <= 5; i++) { ... }has three parts: starti = 1, testi <= 5, stepi++.
Répéter avec une boucle for
- Une boucle exécute le même bloc plusieurs fois, pour ne pas vous répéter.
for (let i = 1; i <= 5; i++) { ... }a trois parties : départi = 1, testi <= 5, pasi++.
for (let i = 1; i <= 3; i++) {
console.log(i); // → 1, then 2, then 3
}
Build a running total
- Keep a variable outside the loop and add to it on every pass.
Construire un total cumulé
- Gardez une variable en dehors de la boucle et ajoutez-y à chaque passage.
let total = 0;
for (let i = 1; i <= 10; i++) {
total = total + i;
}
console.log(total); // → 55
Trace the running total · Tracez le total accumulé
A loop repeats its body. Step through the passes and watch total grow. · Une boucle répète son corps. Passer à travers les passages et observer total grandir.
Watch out
i <= 5stops after 5;i < 5stops before 5. Picking the wrong one is the classic "off-by-one" bug.- Start the total at
0before the loop, not inside it.
Attention
i <= 5s'arrête après 5 ;i < 5s'arrête avant 5. Choisir le mauvais est l'erreur classique « hors par un ».- Commencez le total à
0avant la boucle, pas à l'intérieur.
Common mistakes
for (let i = 0; i < n; i++)runsntimes.- Declare the counter with
let, not without.
Erreurs courantes
for (let i = 0; i < n; i++)s'exécutenfois.- Déclarez le compteur avec
let, pas sans.
Now you try
- Use a
forloop. - Press Check answer to test it.
À vous maintenant
- Utilisez une boucle
for. - Appuyez sur Vérifier la réponse pour tester.
Use a for loop to log the numbers 1 to · à 5, one per line. · Utiliser une boucle for pour log les nombres de 1 à 5, une par ligne.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
Use a for loop to add up 1 to · à 10, then log the total (it is 55). · Utilisez une boucle for pour additionner 1 à 10, puis journalisez le total (c'est 55).
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
Use a for loop to log the even numbers 2, 4, 6, one per line (step by 2 with i += 2). · Utiliser une boucle for pour log les nombres pairs 2, 4, 6, une par ligne (parcourir par 2 avec i += 2).
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.