Skip to content

Logical operators #401

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
The answer is `2`, that's the first truthy value.
A resposta é `2`, pois é o primeiro valor verdadeiro.

```js run
alert( null || 2 || undefined );
```

Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ importance: 5

---

# What's the result of OR?
# Qual o resultado do *OR* ?

What is the code below going to output?
Qual é a saída do código abaixo?

```js
alert( null || 2 || undefined );
```

12 changes: 6 additions & 6 deletions 1-js/02-first-steps/11-logical-operators/2-alert-or/solution.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
The answer: first `1`, then `2`.
A resposta: primeiro `1`, depois `2`.

```js run
alert( alert(1) || 2 || alert(3) );
```

The call to `alert` does not return a value. Or, in other words, it returns `undefined`.
Ao chamar `alert` não é retornado nenhum valor. Ou seja, é retornado `undefined`.

1. The first OR `||` evaluates its left operand `alert(1)`. That shows the first message with `1`.
2. The `alert` returns `undefined`, so OR goes on to the second operand searching for a truthy value.
3. The second operand `2` is truthy, so the execution is halted, `2` is returned and then shown by the outer alert.
1. O primeiro *OR* `||` avalia o operando da esquerda `alert(1)`. Que mostra a primeira mensagem com `1`.
2. O `alert` retorna `undefined`, então *OR* vai ao segundo operando procurando por um valor verdadeiro.
3. O segundo operando `2` é verdadeiro, então a execução é interrompida, `2` é retornado e, é mostrado pelo `alert` externo.

There will be no `3`, because the evaluation does not reach `alert(3)`.
Não haverá `3`, pois a execução não chega a `alert(3)`.
5 changes: 2 additions & 3 deletions 1-js/02-first-steps/11-logical-operators/2-alert-or/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ importance: 3

---

# What's the result of OR'ed alerts?
# Qual o resultado do alerta de encadeamento de *OR*'s?

What will the code below output?
Qual a saída do código abaixo?

```js
alert( alert(1) || 2 || alert(3) );
```

Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
The answer: `null`, because it's the first falsy value from the list.
Resposta: `null`, pois é o primeiro valor falso da lista.

```js run
alert(1 && null && 2);
```

Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ importance: 5

---

# What is the result of AND?
# Qual o resultado de *AND*?

What is this code going to show?
O que este código irá mostrar?

```js
alert( 1 && null && 2 );
```

Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
The answer: `1`, and then `undefined`.
Resposta: `1`, e depois `undefined`.

```js run
alert( alert(1) && alert(2) );
```

The call to `alert` returns `undefined` (it just shows a message, so there's no meaningful return).

Because of that, `&&` evaluates the left operand (outputs `1`), and immediately stops, because `undefined` is a falsy value. And `&&` looks for a falsy value and returns it, so it's done.
A chamada de `alert` retorna `undefined` (apenas mostra uma mensagem, então não existe nenhum retorno significativo).

Por causa disso, `&&` avalia o operando à esquerda (mostra `1`), e imediatamente interrompe, pois, `undefined` é um valor falso. *AND* `&&` procura por um valor falso e o retorna, então está feito.
5 changes: 2 additions & 3 deletions 1-js/02-first-steps/11-logical-operators/4-alert-and/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ importance: 3

---

# What is the result of AND'ed alerts?
# Qual o resultado dos alerts encadeados em *AND*?

What will this code show?
O que este código irá mostrar?

```js
alert( alert(1) && alert(2) );
```

Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
The answer: `3`.
Resposta: `3`.

```js run
alert( null || 2 && 3 || 4 );
```

The precedence of AND `&&` is higher than `||`, so it executes first.
A precedência de *AND* `&&` é maior que *OR* `||`. Então ele é executado primeiro.

The result of `2 && 3 = 3`, so the expression becomes:
O resultado de `2 && 3 = 3`, então a expressão se torna:

```
null || 3 || 4
```

Now the result is the first truthy value: `3`.

Agora o resultado é o primeiro valor verdadeiro: `3`.
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ importance: 5

---

# The result of OR AND OR
# O resultado de *OR* *AND* *OR*

What will the result be?
Qual será o resultado?

```js
alert( null || 2 && 3 || 4 );
```

Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,3 @@
```js
if (age >= 14 && age <= 90)
```

Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ importance: 3

---

# Check the range between
# Verifique o intervalo entre

Write an `if` condition to check that `age` is between `14` and `90` inclusively.
Escreva uma condição "if" para verificar se `age` está no intervalo fechado de 14 a 90.

"Inclusively" means that `age` can reach the edges `14` or `90`.
"Fechado" significa que `age` pode chegar a ser `14` ou `90`.
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
The first variant:
A primeira variação:

```js
if (!(age >= 14 && age <= 90))
```

The second variant:
A segunda variação:

```js
if (age < 14 || age > 90)
```

Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ importance: 3

---

# Check the range outside
# Verifique o exterior do intervalo

Write an `if` condition to check that `age` is NOT between `14` and `90` inclusively.
Escreva uma condição `if` para verificar se `age` NÃO está no intervalo fechado de 14 a 90.

Create two variants: the first one using NOT `!`, the second one -- without it.
Crie duas variantes: a primeira usando NÃO `!`, e uma segunda -- sem ele.
25 changes: 12 additions & 13 deletions 1-js/02-first-steps/11-logical-operators/8-if-question/solution.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
The answer: the first and the third will execute.
Resposta: o primeiro e o terceiro serão executados.

Details:
Detalhes:

```js run
// Runs.
// The result of -1 || 0 = -1, truthy
if (-1 || 0) alert( 'first' );
// Executa.
// O resultado de -1 || 0 = -1, verdadeiro.
if (-1 || 0) alert( 'primeiro' );

// Doesn't run
// -1 && 0 = 0, falsy
if (-1 && 0) alert( 'second' );
// Não executa.
// -1 && 0 = 0, falso
if (-1 && 0) alert( 'segundo' );

// Executes
// Operator && has a higher precedence than ||
// so -1 && 1 executes first, giving us the chain:
// Executa.
// O operador && tem precedência maior que ||
// então -1 && 1 executa primeiro, nos dando o encadeamento:
// null || -1 && 1 -> null || 1 -> 1
if (null || -1 && 1) alert( 'third' );
if (null || -1 && 1) alert( 'terceiro' );
```

13 changes: 6 additions & 7 deletions 1-js/02-first-steps/11-logical-operators/8-if-question/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ importance: 5

---

# A question about "if"
# Uma questão sobre "if"

Which of these `alert`s are going to execute?
Qual destes `alert`s serão executados?

What will the results of the expressions be inside `if(...)`?
Qual será o resultado das expressões dentro dos `if(...)`s?

```js
if (-1 || 0) alert( 'first' );
if (-1 && 0) alert( 'second' );
if (null || -1 && 1) alert( 'third' );
if (-1 || 0) alert( 'primeiro' );
if (-1 && 0) alert( 'segundo' );
if (null || -1 && 1) alert( 'terceiro' );
```

Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@


```js run demo
let userName = prompt("Who's there?", '');
let userName = prompt("Quem está aí?", '');

if (userName === 'Admin') {

let pass = prompt('Password?', '');
let pass = prompt('Senha?', '');

if (pass === 'TheMaster') {
alert( 'Welcome!' );
alert( 'Bem vindo!' );
} else if (pass === '' || pass === null) {
alert( 'Canceled' );
alert( 'Cancelado.' );
} else {
alert( 'Wrong password' );
alert( 'Senha incorreta.' );
}

} else if (userName === '' || userName === null) {
alert( 'Canceled' );
alert( 'Cancelado' );
} else {
alert( "I don't know you" );
alert( "Eu não conheço você." );
}
```

Note the vertical indents inside the `if` blocks. They are technically not required, but make the code more readable.
Note as indentações verticais dentro dos blocos de `if`s. Tecnicamente, elas não são necessárias, mas tornam o código mais legível.
20 changes: 10 additions & 10 deletions 1-js/02-first-steps/11-logical-operators/9-check-login/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,24 @@ importance: 3

---

# Check the login
# Verifique o login

Write the code which asks for a login with `prompt`.
Escreva o código que irá perguntar por um login com um `prompt`.

If the visitor enters `"Admin"`, then `prompt` for a password, if the input is an empty line or `key:Esc` -- show "Canceled", if it's another string -- then show "I don't know you".
Se o visitante digitar `"Admin"`, então faça `prompt` para uma senha, se a entrada é uma linha vazia ou `key:Esc` -- mostre "Cancelada.", se for qualquer outra `string` -- então mostre "Eu não conheço você.".

The password is checked as follows:
A senha é checada da seguinte forma:

- If it equals "TheMaster", then show "Welcome!",
- Another string -- show "Wrong password",
- For an empty string or cancelled input, show "Canceled"
- Se for igual a "TheMaster", então mostre "Bem vindo!",
- Qualquer outra `string` -- mostre "Senha incorreta",
- Para uma `string` vazia ou cancelada, mostre "Cancelada.".

The schema:
O esquema:

![](ifelse_task.svg)

Please use nested `if` blocks. Mind the overall readability of the code.
Use blocos agrupados de `if`s. Tenha em mente a legibilidade do código.

Hint: passing an empty input to a prompt returns an empty string `''`. Pressing `key:ESC` during a prompt returns `null`.
Dica: passar uma entrada vazia para um `prompt` retorna uma string vazia `''`. Pressionar `key:ESC` durante o `prompt` retorna `null`.

[demo]
Loading