for loops · bucles 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++.
Repetir con un bucle for
- Un bucle ejecuta el mismo bloque muchas veces, así que no tienes que repetirte.
for (let i = 1; i <= 5; i++) { ... }tiene tres partes: inicioi = 1, condicióni <= 5, pasoi++.
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.
Construir una suma acumulativa
- Mantén una variable fuera del bucle y súmale en cada pasada.
let total = 0;
for (let i = 1; i <= 10; i++) {
total = total + i;
}
console.log(total); // → 55
Trace the running total · Rastrear la suma acumulada
A loop repeats its body. Step through the passes and watch total grow. · Un bucle repite su cuerpo. Recorre las iteraciones y observa cómo crece total.
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.
Ten cuidado
i <= 5se detiene después de 5;i < 5se detiene antes de 5. Elegir el incorrecto es el clásico error "off-by-one".- Inicia el total en
0antes del bucle, no dentro de él.
Common mistakes
for (let i = 0; i < n; i++)runsntimes.- Declare the counter with
let, not without.
Errores comunes
for (let i = 0; i < n; i++)se ejecutanveces.- Declara el contador con
let, no sin él.
Now you try
- Use a
forloop. - Press Check answer to test it.
Ahora tú lo intentas
- Usa un bucle
for. - Pulsa Comprobar respuesta para probarlo.
Use a for loop to log the numbers 1 to · hasta 5, one per line. · Usa un bucle for para registrar los números del 1 al 5, uno por línea.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Use a for loop to add up 1 to · hasta 10, then log the total (it is 55). · Usa un bucle for para sumar del 1 al 10, luego registra el total (es 55).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Use a for loop to log the even numbers 2, 4, 6, one per line (step by 2 with i += 2). · Usa un bucle for para registrar los números pares 2, 4, 6, uno por línea (paso de 2 con i += 2).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.