Skip to content

Logical operators #56

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

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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`, que é o primeiro valor verdadeiro.

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

Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
importance: 5
importância: 5

---

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

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

```js
alert( null || 2 || undefined );
```
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • "Qual o resultado do OU OR?"


11 changes: 6 additions & 5 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,14 @@
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 it's 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 OU `||` avalia o operando da esquerda `alert(1)`. Que mostra a primeira mensagem com `1`.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • "O primeiro OU OR..."

2. O `alert` retorna `undefined`, então OU vai ao segundo operando procurando por um valor verdadeiro.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • ", então OU OR vai ao..."

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)`.
7 changes: 3 additions & 4 deletions 1-js/02-first-steps/11-logical-operators/2-alert-or/task.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
importance: 3
importância: 3

---

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

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • "...encadeamento de OU's 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
@@ -1,12 +1,11 @@
importance: 5
importância: 5

---

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

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

-"...resultado de -E- 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,11 @@
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).
A chamada de `alert` retorna `undefined` (apenas mostra uma mensagem, então não existe nenhum retorno significativo).

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.

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

---

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

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • "...alerts encadeados em E por 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 E `&&` é maior do que OU `||`. então ele é executado primeiro.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • "...precedência de E- do AND && é maior do que a do OU OR ||."

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
@@ -1,12 +1,11 @@
importance: 5
importância: 5

---

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

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • "O resultado de OR -E- 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
@@ -1,9 +1,9 @@
importance: 3
importância: 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 `idade` está entre o intervalo fechado `14` e `90`.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • "...está entre o no intervalo fechado de 14 -e- a 90."

"Inclusively" means that `age` can reach the edges `14` or `90`.
"Fechado" significa que `idade` 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:

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • "A primeira variação variante:"

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

The second variant:
A segunda variação:

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • "A segunda variação variante:"

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

Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
importance: 3
importância: 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 `idade` NÃO está entre o intervalo fechado `14` e `90`.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • "...está entre o no intervalo fechado de 14 -e- a 90."

Create two variants: the first one using NOT `!`, the second one -- without it.
Crie duas variações: a primeira usando NÃO `!`, e uma segunda -- sem ele.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • "Crie duas variações variantes: ..."

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' );
```

15 changes: 7 additions & 8 deletions 1-js/02-first-steps/11-logical-operators/8-if-question/task.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
importance: 5
importância: 5

---

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

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • "A Uma questão sobre..."

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 identações verticais dentro dos blocos de `if`s. Tecnicamente, elas não são necessárias, mas fazem o código mais legível.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • "alert( 'Cancelado Cancelada' );" in all
  • "...identações indentações verticais..."

22 changes: 11 additions & 11 deletions 1-js/02-first-steps/11-logical-operators/9-check-login/task.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
importance: 3
importância: 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 a senha, se a entrada é uma linha vazia ou `key:Esc` -- mostre "Cancelado.", se for qualquer outra string -- então mostre "Eu não conheço você.".
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • "...faça prompt para uma senha,".
  • "...mostre "Cancelado." "Cancelada." "


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 "Cancelado.".
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • "Para uma string vazia ou entrada cancelada, mostre "Cancelado." "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