if / else
Making decisions
if (test) { ... }runs its block only when the test istrue.elsegives the path to take when the test isfalse.
Tomar decisiones
if (test) { ... }ejecuta su bloque solo cuando la prueba estrue.elsedefine el camino a seguir cuando la prueba esfalse.
let age = 20;
if (age >= 18) {
console.log("adult"); // → adult
} else {
console.log("minor");
}
Many paths with else if
- Add
else iffor more choices. JavaScript checks each test top to bottom. - The first test that is
truewins; the rest are skipped.
Múltiples caminos con else if
- Añade
else ifpara tener más opciones. JavaScript evalúa cada prueba de arriba hacia abajo. - La primera prueba que sea
truegana; las restantes se omiten.
let mark = 72;
if (mark >= 70) {
console.log("A"); // → A
} else if (mark >= 50) {
console.log("B");
} else {
console.log("C");
}
Which branch runs? · ¿Qué rama se ejecuta?
Tests are checked top-down; the first · primero true one runs and the rest are skipped. · Las pruebas se verifican de arriba hacia abajo; la primera que sea verdadera se ejecuta y el resto se omite.
Watch out
- Put the test in
( )and the block in{ }. - Inside a test, compare with
===(day === "Sat"), never a single=.
Ten cuidado
- Coloca la prueba entre paréntesis
( )y el bloque entre llaves{ }. - Dentro de una prueba, compara usando
===(day === "Sat"), nunca un solo igual=.
Common mistakes
- The condition goes in
( )and the body in{ }. - Compare with
===.
Errores comunes
- La condición va entre paréntesis
( )y el cuerpo entre llaves{ }. - Compara con
===.
Now you try
- Read the value, then choose with
if/else. - Press Check answer to test it.
Ahora tú intentas
- Lee el valor, luego elige con
if/else. - Pulsa Check answer para comprobarlo.
let n = 5. If n is greater than 0 log positive, otherwise log not positive. (It should log positive.) · let n = 5. Si n es mayor que 0, imprime positive, de lo contrario imprime not positive. (Debería imprimir positive.)
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
let mark = 65. Log A for 70 or more, B for 50–69, and C for less. (It should log B.) · let mark = 65. Imprime A para 70 o más, B para 50–69, y C para menos. (Debería imprimir B.)
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
let n = 4. Log even if n % 2 === 0, otherwise log odd. (It should log even.) · let n = 4. Imprime even si n % 2 === 0, de lo contrario imprime odd. (Debería imprimir even.)
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.