if / else
Making decisions
if (test) { ... }runs its block only when the test istrue.elsegives the path to take when the test isfalse.
Tomando decisões
if (test) { ... }executa seu bloco apenas quando o teste étrue.elsedefine o caminho a seguir quando o teste éfalse.
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.
Muitos caminhos com else if
- Adicione
else ifpara mais opções. JavaScript verifica cada teste de cima para baixo. - O primeiro teste que é
truevence; os demais são pulados.
let mark = 72;
if (mark >= 70) {
console.log("A"); // → A
} else if (mark >= 50) {
console.log("B");
} else {
console.log("C");
}
Which branch runs? · Qual ramo executa?
Tests are checked top-down; the first · primeiro true one runs and the rest are skipped. · Os testes são verificados de cima para baixo; o primeiro verdadeiro executa e os outros são pulados.
Watch out
- Put the test in
( )and the block in{ }. - Inside a test, compare with
===(day === "Sat"), never a single=.
Atenção
- Coloque o teste em
( )e o bloco em{ }. - Dentro de um teste, compare com
===(day === "Sat"), nunca apenas um=.
Common mistakes
- The condition goes in
( )and the body in{ }. - Compare with
===.
Erros comuns
- A condição vai em
( )e o corpo em{ }. - Compare com
===.
Now you try
- Read the value, then choose with
if/else. - Press Check answer to test it.
Agora você tenta
- Leia o valor, depois escolha com
if/else. - Pressione Check answer para testá-lo.
let n = 5. If n is greater than 0 log positive, otherwise log not positive. (It should log positive.) · let n = 5. Se n for maior que 0 faça log de positive, caso contrário faça log de not positive. (Deveria fazer log de positive.)
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
let mark = 65. Log A for 70 or more, B for 50–69, and C for less. (It should log B.) · let mark = 65. Faça log de A para 70 ou mais, B para 50–69, e C para menos. (Deveria fazer log de B.)
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
let n = 4. Log even if · se n % 2 === 0, otherwise log odd. (It should log even.) · let n = 4. Faça log de even se n % 2 === 0, caso contrário faça log de odd. (Deveria fazer log de even.)
Click Run to see the output here. · Clique em Executar para ver a saída aqui.