diff --git a/1-js/02-first-steps/11-logical-operators/1-alert-null-2-undefined/solution.md b/1-js/02-first-steps/11-logical-operators/1-alert-null-2-undefined/solution.md index 8869d32e6..995f9b23e 100644 --- a/1-js/02-first-steps/11-logical-operators/1-alert-null-2-undefined/solution.md +++ b/1-js/02-first-steps/11-logical-operators/1-alert-null-2-undefined/solution.md @@ -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 ); ``` - diff --git a/1-js/02-first-steps/11-logical-operators/1-alert-null-2-undefined/task.md b/1-js/02-first-steps/11-logical-operators/1-alert-null-2-undefined/task.md index a7c9addfc..f20931c2b 100644 --- a/1-js/02-first-steps/11-logical-operators/1-alert-null-2-undefined/task.md +++ b/1-js/02-first-steps/11-logical-operators/1-alert-null-2-undefined/task.md @@ -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 ); ``` - diff --git a/1-js/02-first-steps/11-logical-operators/2-alert-or/solution.md b/1-js/02-first-steps/11-logical-operators/2-alert-or/solution.md index f85b56366..050dab82c 100644 --- a/1-js/02-first-steps/11-logical-operators/2-alert-or/solution.md +++ b/1-js/02-first-steps/11-logical-operators/2-alert-or/solution.md @@ -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)`. diff --git a/1-js/02-first-steps/11-logical-operators/2-alert-or/task.md b/1-js/02-first-steps/11-logical-operators/2-alert-or/task.md index 3908fa2ec..6904e3f2a 100644 --- a/1-js/02-first-steps/11-logical-operators/2-alert-or/task.md +++ b/1-js/02-first-steps/11-logical-operators/2-alert-or/task.md @@ -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) ); ``` - diff --git a/1-js/02-first-steps/11-logical-operators/3-alert-1-null-2/solution.md b/1-js/02-first-steps/11-logical-operators/3-alert-1-null-2/solution.md index 368b59409..6239b8836 100644 --- a/1-js/02-first-steps/11-logical-operators/3-alert-1-null-2/solution.md +++ b/1-js/02-first-steps/11-logical-operators/3-alert-1-null-2/solution.md @@ -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); ``` - diff --git a/1-js/02-first-steps/11-logical-operators/3-alert-1-null-2/task.md b/1-js/02-first-steps/11-logical-operators/3-alert-1-null-2/task.md index 043d431e4..d94531b1e 100644 --- a/1-js/02-first-steps/11-logical-operators/3-alert-1-null-2/task.md +++ b/1-js/02-first-steps/11-logical-operators/3-alert-1-null-2/task.md @@ -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 ); ``` - diff --git a/1-js/02-first-steps/11-logical-operators/4-alert-and/solution.md b/1-js/02-first-steps/11-logical-operators/4-alert-and/solution.md index b6fb10d72..0253dd223 100644 --- a/1-js/02-first-steps/11-logical-operators/4-alert-and/solution.md +++ b/1-js/02-first-steps/11-logical-operators/4-alert-and/solution.md @@ -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. diff --git a/1-js/02-first-steps/11-logical-operators/4-alert-and/task.md b/1-js/02-first-steps/11-logical-operators/4-alert-and/task.md index 69f877b95..90004c99a 100644 --- a/1-js/02-first-steps/11-logical-operators/4-alert-and/task.md +++ b/1-js/02-first-steps/11-logical-operators/4-alert-and/task.md @@ -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) ); ``` - diff --git a/1-js/02-first-steps/11-logical-operators/5-alert-and-or/solution.md b/1-js/02-first-steps/11-logical-operators/5-alert-and-or/solution.md index 25e3568f8..aa3846de5 100644 --- a/1-js/02-first-steps/11-logical-operators/5-alert-and-or/solution.md +++ b/1-js/02-first-steps/11-logical-operators/5-alert-and-or/solution.md @@ -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`. diff --git a/1-js/02-first-steps/11-logical-operators/5-alert-and-or/task.md b/1-js/02-first-steps/11-logical-operators/5-alert-and-or/task.md index b18bb9c51..1ae350000 100644 --- a/1-js/02-first-steps/11-logical-operators/5-alert-and-or/task.md +++ b/1-js/02-first-steps/11-logical-operators/5-alert-and-or/task.md @@ -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 ); ``` - diff --git a/1-js/02-first-steps/11-logical-operators/6-check-if-in-range/solution.md b/1-js/02-first-steps/11-logical-operators/6-check-if-in-range/solution.md index 87c733b22..02c994050 100644 --- a/1-js/02-first-steps/11-logical-operators/6-check-if-in-range/solution.md +++ b/1-js/02-first-steps/11-logical-operators/6-check-if-in-range/solution.md @@ -3,4 +3,3 @@ ```js if (age >= 14 && age <= 90) ``` - diff --git a/1-js/02-first-steps/11-logical-operators/6-check-if-in-range/task.md b/1-js/02-first-steps/11-logical-operators/6-check-if-in-range/task.md index fc9e336c1..136e7cbf1 100644 --- a/1-js/02-first-steps/11-logical-operators/6-check-if-in-range/task.md +++ b/1-js/02-first-steps/11-logical-operators/6-check-if-in-range/task.md @@ -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`. diff --git a/1-js/02-first-steps/11-logical-operators/7-check-if-out-range/solution.md b/1-js/02-first-steps/11-logical-operators/7-check-if-out-range/solution.md index d1946a967..fa1b36657 100644 --- a/1-js/02-first-steps/11-logical-operators/7-check-if-out-range/solution.md +++ b/1-js/02-first-steps/11-logical-operators/7-check-if-out-range/solution.md @@ -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) ``` - diff --git a/1-js/02-first-steps/11-logical-operators/7-check-if-out-range/task.md b/1-js/02-first-steps/11-logical-operators/7-check-if-out-range/task.md index 9b947d00f..0db61abd5 100644 --- a/1-js/02-first-steps/11-logical-operators/7-check-if-out-range/task.md +++ b/1-js/02-first-steps/11-logical-operators/7-check-if-out-range/task.md @@ -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. diff --git a/1-js/02-first-steps/11-logical-operators/8-if-question/solution.md b/1-js/02-first-steps/11-logical-operators/8-if-question/solution.md index 210509758..b6f568df1 100644 --- a/1-js/02-first-steps/11-logical-operators/8-if-question/solution.md +++ b/1-js/02-first-steps/11-logical-operators/8-if-question/solution.md @@ -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' ); ``` - diff --git a/1-js/02-first-steps/11-logical-operators/8-if-question/task.md b/1-js/02-first-steps/11-logical-operators/8-if-question/task.md index 55987121b..4019fc6d6 100644 --- a/1-js/02-first-steps/11-logical-operators/8-if-question/task.md +++ b/1-js/02-first-steps/11-logical-operators/8-if-question/task.md @@ -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' ); ``` - diff --git a/1-js/02-first-steps/11-logical-operators/9-check-login/solution.md b/1-js/02-first-steps/11-logical-operators/9-check-login/solution.md index 604606259..e5121af66 100644 --- a/1-js/02-first-steps/11-logical-operators/9-check-login/solution.md +++ b/1-js/02-first-steps/11-logical-operators/9-check-login/solution.md @@ -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. diff --git a/1-js/02-first-steps/11-logical-operators/9-check-login/task.md b/1-js/02-first-steps/11-logical-operators/9-check-login/task.md index 290a52642..043a2685a 100644 --- a/1-js/02-first-steps/11-logical-operators/9-check-login/task.md +++ b/1-js/02-first-steps/11-logical-operators/9-check-login/task.md @@ -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] diff --git a/1-js/02-first-steps/11-logical-operators/article.md b/1-js/02-first-steps/11-logical-operators/article.md index 78c4fd2f1..1be108f04 100644 --- a/1-js/02-first-steps/11-logical-operators/article.md +++ b/1-js/02-first-steps/11-logical-operators/article.md @@ -1,24 +1,24 @@ -# Logical operators +# Operadores lógicos -There are four logical operators in JavaScript: `||` (OR), `&&` (AND), `!` (NOT), `??` (Nullish Coalescing). Here we cover the first three, the `??` operator is in the next article. +Existem quatro operadores lógicos em JavaScript: `||` (*OR*), `&&` (*AND*), `!` (*NOT*), `??` (*Nullish Coalescing*). Aqui cobrimos os três primeiros, o operador `??` está no próximo artigo. -Although they are called "logical", they can be applied to values of any type, not only boolean. Their result can also be of any type. +Embora eles sejam chamados de "lógicos", podem ser aplicados a valores de qualquer tipo, não apenas ao tipo `boolean`. Seus resultados também podem ser de qualquer tipo. -Let's see the details. +Vamos ver os detalhes. ## || (OR) -The "OR" operator is represented with two vertical line symbols: +O operador "*OR*" é representado por dois símbolos de linha vertical: ```js result = a || b; ``` -In classical programming, the logical OR is meant to manipulate boolean values only. If any of its arguments are `true`, it returns `true`, otherwise it returns `false`. +Em programação clássica, o operador *OR* é utilizado para manipular apenas valores do tipo `boolean`. Se qualquer um dos seus argumentos for `true`, ele retorna `true`, se não, retorna `false`. -In JavaScript, the operator is a little bit trickier and more powerful. But first, let's see what happens with boolean values. +Em JavaScript, este operador é um pouco mais útil e poderoso. Mas primeiro, vamos ver o que acontece com valores do tipo `boolean`. -There are four possible logical combinations: +Existem quatro combinações lógicas possíveis: ```js run alert( true || true ); // true @@ -27,83 +27,83 @@ alert( true || false ); // true alert( false || false ); // false ``` -As we can see, the result is always `true` except for the case when both operands are `false`. +Como podemos ver, o resultado é sempre `true`, exceto para o caso onde os dois operandos são `false`. -If an operand is not a boolean, it's converted to a boolean for the evaluation. +Se um operando não é um `boolean`, ele é convertido em um `boolean` para ser avaliado. -For instance, the number `1` is treated as `true`, the number `0` as `false`: +Por exemplo, o número `1` é tratado com `true` e o número `0` como `false`. ```js run -if (1 || 0) { // works just like if( true || false ) - alert( 'truthy!' ); +if (1 || 0) { // funciona como if( true || false) + alert( 'verdadeiro!'); } ``` -Most of the time, OR `||` is used in an `if` statement to test if *any* of the given conditions is `true`. +Na maioria das vezes, *OR* `||` é usado dentro de uma expressão `if` para testar se *qualquer* uma das condições dadas é `true`. -For example: +Por exemplo: ```js run -let hour = 9; +let hour = 0; *!* if (hour < 10 || hour > 18) { */!* - alert( 'The office is closed.' ); + alert( 'O escritório está fechado.' ); } ``` -We can pass more conditions: +Nós podemos passar mais condições: ```js run let hour = 12; let isWeekend = true; if (hour < 10 || hour > 18 || isWeekend) { - alert( 'The office is closed.' ); // it is the weekend + alert( 'O escritório está fechado.' ); // é final de semana } ``` -## OR "||" finds the first truthy value [#or-finds-the-first-truthy-value] +## *OR* "||" encontra o primeiro valor verdadeiro [#or-finds-the-first-truthy-value] -The logic described above is somewhat classical. Now, let's bring in the "extra" features of JavaScript. +A lógica descrita acima é algo clássica. Agora, vamos ver as funcionalidades "extras" do JavaScript. -The extended algorithm works as follows. +O algoritmo estendido funciona da seguinte forma. -Given multiple OR'ed values: +Dando múltiplos valores encadeados em OR's: ```js result = value1 || value2 || value3; ``` -The OR `||` operator does the following: +O operador *OR* `||` faz o seguinte: -- Evaluates operands from left to right. -- For each operand, converts it to boolean. If the result is `true`, stops and returns the original value of that operand. -- If all operands have been evaluated (i.e. all were `false`), returns the last operand. +- Avalia os operandos da esquerda para a direita. +- Para cada operando, o converte para o tipo `boolean`. Se o resultado é `true`, para e retorna o valor original daquele operando. +- Se todos os operandos foram avaliados (i.e. todos são `false`), retorna o último operando. -A value is returned in its original form, without the conversion. +Um valor é retornado na sua forma original, sem conversão. -In other words, a chain of OR `||` returns the first truthy value or the last one if no truthy value is found. +Em outras palavras, uma cadeia de *OR* `"||"`, retorna o primeiro valor verdadeiro ou o último se nenhum `true` for encontrado. -For instance: +Por exemplo: ```js run -alert( 1 || 0 ); // 1 (1 is truthy) +alert( 1 || 0 ); // 1 (1 é verdadeiro) -alert( null || 1 ); // 1 (1 is the first truthy value) -alert( null || 0 || 1 ); // 1 (the first truthy value) +alert( null || 1 ); // 1 (1 é o primeiro valor verdadeiro) +alert( null || 0 || 1 ); // 1 (o primeiro valor verdadeiro) -alert( undefined || null || 0 ); // 0 (all falsy, returns the last value) +alert( undefined || null || 0 ); // 0 (todos falsos, retorna o último valor) ``` -This leads to some interesting usage compared to a "pure, classical, boolean-only OR". +Isso nos mostra algumas utilidades interessantes comparadas ao "puro, clássico, apenas-booleano OR". -1. **Getting the first truthy value from a list of variables or expressions.** +1. **Obtendo o primeiro valor verdadeiro de uma lista de variáveis ou expressões.** - For instance, we have `firstName`, `lastName` and `nickName` variables, all optional (i.e. can be undefined or have falsy values). + Por exemplo, temos as variáveis ​​`firstName`, `lastName` e `nickName`, todas opcionais (ou seja, podem ser indefinidas ou ter valores falsos). - Let's use OR `||` to choose the one that has the data and show it (or `"Anonymous"` if nothing set): + Vamos usar *OR* `||` para escolher aquele que tem os dados e mostrá-lo (ou `"Anonymous"` se nada for definido): ```js run let firstName = ""; @@ -114,37 +114,37 @@ This leads to some interesting usage compared to a "pure, classical, boolean-onl alert( firstName || lastName || nickName || "Anonymous"); // SuperCoder */!* ``` + + Se todas as variáveis ​​fossem falsas, apareceria `"Anonymous"`. - If all variables were falsy, `"Anonymous"` would show up. +2. **Avaliação em curto-circuito.** -2. **Short-circuit evaluation.** + Outra característica do operador *OR* `||` é a chamado de avaliação em "curto-circuito". - Another feature of OR `||` operator is the so-called "short-circuit" evaluation. + Isso significa que `||` processa seus argumentos até que o primeiro valor verdadeiro seja alcançado, e então o valor é retornado imediatamente, sem sequer tocar no outro argumento. - It means that `||` processes its arguments until the first truthy value is reached, and then the value is returned immediately, without even touching the other argument. + A importância desse recurso torna-se óbvia se um operando não for apenas um valor, mas uma expressão com um efeito colateral, como uma atribuição de variável ou uma chamada de função. - The importance of this feature becomes obvious if an operand isn't just a value, but an expression with a side effect, such as a variable assignment or a function call. - - In the example below, only the second message is printed: + No exemplo abaixo, apenas a segunda mensagem é impressa: ```js run no-beautify - *!*true*/!* || alert("not printed"); - *!*false*/!* || alert("printed"); + *!*true*/!* || alert("não impresso"); + *!*false*/!* || alert("impresso"); ``` - In the first line, the OR `||` operator stops the evaluation immediately upon seeing `true`, so the `alert` isn't run. + Na primeira linha, o operador *OR* `||` interrompe a avaliação imediatamente ao ver `true`, portanto, o `alert` não é executado. - Sometimes, people use this feature to execute commands only if the condition on the left part is falsy. + Às vezes, as pessoas usam esse recurso para executar comandos apenas se a condição na parte esquerda for falsa. ## && (AND) -The AND operator is represented with two ampersands `&&`: +O operador *AND* (E) é representado por dois e's comerciais `&&`: ```js result = a && b; ``` -In classical programming, AND returns `true` if both operands are truthy and `false` otherwise: +Em programação clássica, *AND* retorna `true` se ambos os operandos forem verdadeiros ou `false`, caso contrário: ```js run alert( true && true ); // true @@ -153,137 +153,138 @@ alert( true && false ); // false alert( false && false ); // false ``` -An example with `if`: +Um exemplo com `if`: ```js run let hour = 12; let minute = 30; if (hour == 12 && minute == 30) { - alert( 'The time is 12:30' ); + alert( 'Agora são 12:30' ); } ``` -Just as with OR, any value is allowed as an operand of AND: +Da mesma forma que o OR, qualquer valor é permitido como um operando de AND: ```js run -if (1 && 0) { // evaluated as true && false - alert( "won't work, because the result is falsy" ); +if (1 && 0) { // avaliado como true && false + alert( "não funciona, pois o resultado é falso" ); } ``` -## AND "&&" finds the first falsy value +## "*AND*" encontra o primeiro valor falso -Given multiple AND'ed values: +Dados múltiplos valores encadeados em AND's: ```js result = value1 && value2 && value3; ``` -The AND `&&` operator does the following: +O operador `&&` faz o seguinte: -- Evaluates operands from left to right. -- For each operand, converts it to a boolean. If the result is `false`, stops and returns the original value of that operand. -- If all operands have been evaluated (i.e. all were truthy), returns the last operand. +- Avalia os operandos da esquerda para a direita. +- Para cada operando, o converte para o tipo `boolean`. Se o resultado for `false`, interrompe e retorna o valor original daquele operando. +- Se todos os operandos foram avaliados (i.e. todos são verdadeiros), retorna o último operando. -In other words, AND returns the first falsy value or the last value if none were found. +Em outras palavras, *AND* retorna o primeiro valor falso ou o último valor se nenhum for falso. -The rules above are similar to OR. The difference is that AND returns the first *falsy* value while OR returns the first *truthy* one. +As regras acima são similares ao OR. A diferença é que *AND* retorna o primeiro valor *falso* enquanto *OR* retorna o primeiro valor *verdadeiro*. -Examples: +Exemplos: ```js run -// if the first operand is truthy, -// AND returns the second operand: +// se o primeiro valor for verdadeiro, +// AND retorna o segundo parâmetro: alert( 1 && 0 ); // 0 alert( 1 && 5 ); // 5 -// if the first operand is falsy, -// AND returns it. The second operand is ignored +// se o primeiro valor é falso, +// AND retorna ele. O segundo operando é ignorado. alert( null && 5 ); // null -alert( 0 && "no matter what" ); // 0 +alert( 0 && "não importa o quê" ); // 0 ``` -We can also pass several values in a row. See how the first falsy one is returned: +Nós podemos também passar vários valores em cadeia. Veja como o primeiro falso é retornado: ```js run alert( 1 && 2 && null && 3 ); // null ``` -When all values are truthy, the last value is returned: +Quando todos valores são falsos, o último valor é retornado: ```js run -alert( 1 && 2 && 3 ); // 3, the last one +alert( 1 && 2 && 3 ); // 3, que é o último ``` -````smart header="Precedence of AND `&&` is higher than OR `||`" -The precedence of AND `&&` operator is higher than OR `||`. +````smart header="Precedência do *AND* `&&` é maior do que do *OR* `||`" +A precedência do operador *AND* `&&` é maior do que do *OR* `||`. -So the code `a && b || c && d` is essentially the same as if the `&&` expressions were in parentheses: `(a && b) || (c && d)`. +Portanto, o código `a && b || c && d` é essencialmente o mesmo como se as expressões `&&` estivessem entre parênteses: `(a && b) || (c && d)`. ```` -````warn header="Don't replace `if` with `||` or `&&`" -Sometimes, people use the AND `&&` operator as a "shorter way to write `if`". +````warn header="Não substitua `if` por `||` ou `&&`" +Às vezes, as pessoas usam o operador AND `&&` como uma "maneira mais curta de escrever `if`". +```` -For instance: +Por exemplo: ```js run let x = 1; -(x > 0) && alert( 'Greater than zero!' ); +(x > 0) && alert( 'Maior que zero!' ); ``` -The action in the right part of `&&` would execute only if the evaluation reaches it. That is, only if `(x > 0)` is true. +A ação na parte direita do `&&` executaria somente se a avaliação chegasse até ela. Ou seja, apenas se `(x > 0)` fosse verdade. -So we basically have an analogue for: +Então, basicamente temos uma analogia para: ```js run let x = 1; -if (x > 0) alert( 'Greater than zero!' ); +if (x > 0) { + alert( 'Maior que zero!' ); +} ``` -Although, the variant with `&&` appears shorter, `if` is more obvious and tends to be a little bit more readable. So we recommend using every construct for its purpose: use `if` if we want `if` and use `&&` if we want AND. -```` - +Embora a variante com `&&` pareça mais curta, `if` é mais óbvia e tende a ser um pouco mais legível. Portanto, recomendamos usar cada construção para seu propósito: use `if` se quisermos `if` e use `&&` se quisermos AND. -## ! (NOT) +## ! (NÃO) -The boolean NOT operator is represented with an exclamation sign `!`. +O operador booleano NÃO é representado por um sinal de exclamação `!`. -The syntax is pretty simple: +Sua sintaxe é bem simples: ```js result = !value; ``` -The operator accepts a single argument and does the following: +O operador aceita um único argumento e faz o seguinte: -1. Converts the operand to boolean type: `true/false`. -2. Returns the inverse value. +1. Converte o operando para um tipo `boolean`: `true/false`. +2. Retorna o seu valor inverso. -For instance: +Por exemplo: ```js run alert( !true ); // false -alert( !0 ); // true +alert( !0 ); // true ``` -A double NOT `!!` is sometimes used for converting a value to boolean type: +Uma repetição do NÃO `!!` às vezes é usada para converter um valor para o tipo `boolean`: ```js run -alert( !!"non-empty string" ); // true -alert( !!null ); // false +alert( !!"string não vazia" ); // true +alert( !!null ); // false ``` -That is, the first NOT converts the value to boolean and returns the inverse, and the second NOT inverses it again. In the end, we have a plain value-to-boolean conversion. +Ou seja, o primeiro NÃO converte o valor para o tipo `boolean` e retorna o seu inverso e o segundo NÃO o inverte de novo. No final, nós temos uma conversão do valor para o tipo `boolean`. -There's a little more verbose way to do the same thing -- a built-in `Boolean` function: +Existe uma outra forma mais extensas de se fazer a mesma coisa -- a função incorporada `Boolean`: ```js run -alert( Boolean("non-empty string") ); // true +alert( Boolean("string não vazia") ); // true alert( Boolean(null) ); // false ``` -The precedence of NOT `!` is the highest of all logical operators, so it always executes first, before `&&` or `||`. +A precedência do NÃO `!` é a mais alta entre todos os operadores lógicos, então ele é executado primeiro, antes que `&&` ou `||`. diff --git a/images.yml b/images.yml index 84d9832b7..72f85ffff 100644 --- a/images.yml +++ b/images.yml @@ -2,3 +2,25 @@ proto-constructor-animal-rabbit.svg: White Rabbit: text: Coelho Branco position: center +ifelse_task.svg: + Begin: + text: Início + position: center + Who's there?: + text: Quem está aí? + position: center + Password?: + text: Senha? + position: center + Welcome!: + text: Bem vindo! + position: center + Canceled: + text: Cancelado + position: center + Wrong Password: + text: Senha incorreta + position: center + I don't know you: + text: Eu não conheço você +