Repetir sin escribir mil veces
Los computadores son increíblemente buenos para hacer lo mismo una y otra vez sin aburrirse. Acá aprendes a aprovecharlo.
Repeating without writing it a thousand times
Computers are extraordinarily good at doing the same thing over and over without getting bored. Here you learn to use that.
Imagina que quieres mostrar los números del 1 al 5. Podrías escribir cinco líneas. ¿Y del 1 al 1000?
Para eso está el bucle: escribes la instrucción una vez y dices cuántas veces repetirla.
Imagine you want to show the numbers 1 to 5. You could write five lines. And 1 to 1000?
That is what a loop is for: you write the instruction once and say how many times to repeat it.
Ese paréntesis con dos puntos y coma asusta al principio, pero son solo tres instrucciones separadas:
for (let i = 1 ; i <= 5 ; i++)
↑ ↑ ↑
dónde hasta cómo
empieza cuándo avanza
let i = 1— crea un contador que parte en 1.i <= 5— mientras esto sea cierto, sigue repitiendo.i++— al terminar cada vuelta, súmale 1. Es atajo dei = i + 1.
La i viene de índice. Podrías llamarla como quieras, pero todo el
mundo usa i y conviene seguir la costumbre.
Ojo: es tradición empezar en 0, no en 1. Lo
verás mucho, y tiene su razón — la vemos cuando lleguemos a las listas.
Those brackets with two semicolons look scary at first, but they are just three separate instructions:
for (let i = 1 ; i <= 5 ; i++)
↑ ↑ ↑
where until how it
it starts when advances
let i = 1— creates a counter starting at 1.i <= 5— while this is true, keep repeating.i++— after each pass, add 1. Shorthand fori = i + 1.
i stands for index. You could call it anything, but everyone uses
i and it is worth following the convention.
Note: it is traditional to start at 0, not 1.
You will see it constantly, and there is a reason — we cover it when we reach lists.
for sirve cuando sabes cuántas vueltas dar. while sirve cuando
no lo sabes: repite mientras se cumpla una condición.
"Sigue rebotando mientras le quede energía". "Sigue pidiendo la clave mientras esté mal".
for is for when you know how many passes. while is for when you
do not: it repeats while a condition holds.
"Keep bouncing while it still has energy". "Keep asking for the password while it is wrong".
No sabíamos de antemano que serían 6 botes. El programa lo
descubrió solo. El .toFixed(1) es un extra para mostrar un solo decimal.
We did not know beforehand it would be 6 bounces. The program
worked it out. The .toFixed(1) is a bonus that shows a single decimal.
Acá va la advertencia importante. Si la condición nunca deja de cumplirse, el bucle no para jamás y el navegador se congela.
El caso típico: se te olvida hacer avanzar el contador.
let i = 0;
while (i < 5) {
console.log(i);
// falta el i++ → i vale 0 para siempre
}
Ese código no lo puse en un recuadro editable a propósito: colgaría esta página. Si algún día te pasa en tu computador, cierra la pestaña y revisa que algo dentro del bucle acerque la condición a volverse falsa.
Es un error que le pasa a todo el mundo. No es señal de nada malo.
Here comes the important warning. If the condition never stops being true, the loop never ends and the browser freezes.
The classic case: forgetting to advance the counter.
let i = 0;
while (i < 5) {
console.log(i);
// the i++ is missing → i stays 0 forever
}
I deliberately did not put that in an editable box: it would hang this page. If it ever happens on your computer, close the tab and check that something inside the loop moves the condition towards false.
It happens to everyone. It means nothing bad about you.
Acá se juntan las dos ideas que ya sabes. Un bucle que decide en cada vuelta:
Here the two ideas you already know come together. A loop that decides on each pass:
El símbolo % no es porcentaje: es el resto de
la división. 9 % 3 da 0 porque 9 se divide exacto por 3. Se usa muchísimo
para preguntar "¿es múltiplo de?" o "¿es par?" — un número es par si n % 2 === 0.
The % symbol is not percentage: it is the
remainder of a division. 9 % 3 gives 0 because 9 divides exactly
by 3. It is used constantly to ask "is it a multiple of?" or "is it even?" — a number is even
if n % 2 === 0.
for para repetir un número conocido de veces, while para repetir
hasta que algo cambie. Cómo avanzar de dos en dos o hacia atrás. Qué es un bucle infinito y
cómo evitarlo. Y el operador %.
Con variables, decisiones y bucles ya tienes las tres piezas fundamentales. Cualquier programa del mundo, por grande que sea, está hecho de esto. Falta una cuarta que no es obligatoria pero cambia todo: las funciones.
for to repeat a known number of times, while to repeat until
something changes. How to step by two or go backwards. What an infinite loop is and how to
avoid it. And the % operator.
With variables, decisions and loops you now have the three fundamental pieces. Every program in the world, however large, is made of these. One more is not mandatory but changes everything: functions.