From 188b041bbc801bea2a973ab867a62698c9b223f3 Mon Sep 17 00:00:00 2001 From: Andres-ibanez <36300864+Andres-ibanez@users.noreply.github.com> Date: Sun, 2 Jun 2019 05:01:58 -0300 Subject: [PATCH 1/9] Update task.md --- .../08-comparison/1-comparison-questions/task.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/1-js/02-first-steps/08-comparison/1-comparison-questions/task.md b/1-js/02-first-steps/08-comparison/1-comparison-questions/task.md index be7f75ddd..f8c19ebf0 100644 --- a/1-js/02-first-steps/08-comparison/1-comparison-questions/task.md +++ b/1-js/02-first-steps/08-comparison/1-comparison-questions/task.md @@ -2,9 +2,9 @@ importance: 5 --- -# Comparisons +# Comparações -What will be the result for these expressions? +Qual será o resultado das seguintes expressões? ```js no-beautify 5 > 4 From 6f733820253dc7f08f6f5426c2a8418dbced8e12 Mon Sep 17 00:00:00 2001 From: Andres-ibanez <36300864+Andres-ibanez@users.noreply.github.com> Date: Sun, 2 Jun 2019 05:14:37 -0300 Subject: [PATCH 2/9] Update solution.md --- .../1-comparison-questions/solution.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/1-js/02-first-steps/08-comparison/1-comparison-questions/solution.md b/1-js/02-first-steps/08-comparison/1-comparison-questions/solution.md index 5c8bd2bc4..8f6c435c4 100644 --- a/1-js/02-first-steps/08-comparison/1-comparison-questions/solution.md +++ b/1-js/02-first-steps/08-comparison/1-comparison-questions/solution.md @@ -10,12 +10,12 @@ null == "\n0\n" → false null === +"\n0\n" → false ``` -Some of the reasons: +Algumas das razões: -1. Obviously, true. -2. Dictionary comparison, hence false. -3. Again, dictionary comparison, first char of `"2"` is greater than the first char of `"1"`. -4. Values `null` and `undefined` equal each other only. -5. Strict equality is strict. Different types from both sides lead to false. -6. See (4). -7. Strict equality of different types. +1. Obviamente, true. +2. Comparação de dicionário, portanto, false. +3. Novamente, comparação de dicionário, o primeiro caractere de `"2"` é maior que o primeiro caractere de `"1"`. +4. Valores `null` e `undefined` são iguais entre si somente. +5. A igualdade estrita é rigorosa. Diferentes tipos de ambos os lados levam a false. +6. Veja (4). +7. Igualdade estrita de diferentes tipos. From 297e967871607c54d712c6d3f8b4e2578dde587f Mon Sep 17 00:00:00 2001 From: "C@irx" Date: Mon, 3 Jun 2019 03:48:11 -0300 Subject: [PATCH 3/9] translate comparisons --- 1-js/02-first-steps/08-comparison/article.md | 155 +++++++++---------- 1 file changed, 76 insertions(+), 79 deletions(-) diff --git a/1-js/02-first-steps/08-comparison/article.md b/1-js/02-first-steps/08-comparison/article.md index 3d5cc1729..1bde52969 100644 --- a/1-js/02-first-steps/08-comparison/article.md +++ b/1-js/02-first-steps/08-comparison/article.md @@ -1,20 +1,20 @@ -# Comparisons +# Comparações -We know many comparison operators from maths: +Conhecemos muitos operadores de comparação de matemática: -- Greater/less than: a > b, a < b. -- Greater/less than or equals: a >= b, a <= b. -- Equals: `a == b` (please note the double equals sign `=`. A single symbol `a = b` would mean an assignment). -- Not equals. In maths the notation is , but in JavaScript it's written as an assignment with an exclamation sign before it: a != b. +- Maior/menor que: a > b, a < b. +- Maior/menor ou igual que: a >= b, a <= b. +- Igual: `a == b` (observe o sinal de igual duplo `=`. Um único sinal de igual `a = b` significaria uma atribuição). +- Diferente. Em matemática, a notação é , mas em JavaScript é escrita como uma atribuição com um sinal de exclamação antes: a != b. -## Boolean is the result +## Booleano é o resultado -Like all other operators, a comparison returns a value. In this case, the value is a boolean. +Como todos os outros operadores, uma comparação retorna um valor. Nesse caso, o valor é um booleano. -- `true` -- means "yes", "correct" or "the truth". -- `false` -- means "no", "wrong" or "not the truth". +- `true` -- significa "sim", "correto" ou "verdade". +- `false` -- significa "não", "errado" ou "falso". -For example: +Por exemplo: ```js run alert( 2 > 1 ); // true (correct) @@ -22,20 +22,20 @@ alert( 2 == 1 ); // false (wrong) alert( 2 != 1 ); // true (correct) ``` -A comparison result can be assigned to a variable, just like any value: +Um resultado de comparação pode ser atribuído a uma variável, assim como qualquer valor: ```js run let result = 5 > 4; // assign the result of the comparison alert( result ); // true ``` -## String comparison +## Comparação de strings -To see whether a string is greater than another, JavaScript uses the so-called "dictionary" or "lexicographical" order. +Para ver se uma string é maior que outra, o JavaScript usa o chamado ordem "dicionário" ou "lexicográfico". -In other words, strings are compared letter-by-letter. +Em outras palavras, as strings são comparadas letra a letra. -For example: +Por exemplo: ```js run alert( 'Z' > 'A' ); // true @@ -43,40 +43,40 @@ alert( 'Glow' > 'Glee' ); // true alert( 'Bee' > 'Be' ); // true ``` -The algorithm to compare two strings is simple: +O algoritmo para comparar duas strings é simples: -1. Compare the first character of both strings. -2. If the first character from the first string is greater (or less) than the other string's, then the first string is greater (or less) than the second. We're done. -3. Otherwise, if both strings' first characters are the same, compare the second characters the same way. -4. Repeat until the end of either string. -5. If both strings end at the same length, then they are equal. Otherwise, the longer string is greater. +1. Compare o primeiro caractere de ambas as strings. +2. Se o primeiro caractere da primeira string for maior (ou menor que) da outra, a primeira string será maior (ou menor) que a segunda. Nós terminamos +3. Caso contrário, se os primeiros caracteres das duas sequências forem os mesmos, compare os segundos caracteres da mesma maneira. +4. Repita até o final de qualquer string. +5. Se ambas as seqüências terminarem no mesmo comprimento, elas serão iguais. Caso contrário, a string mais longa é maior. -In the examples above, the comparison `'Z' > 'A'` gets to a result at the first step while the strings `"Glow"` and `"Glee"` are compared character-by-character: +Nos exemplos acima, a comparação `'Z' > 'A'` chega a um resultado no primeiro passo enquanto as strings `"Glow"` e `"Glee"`são comparadas caractere por caractere: -1. `G` is the same as `G`. -2. `l` is the same as `l`. -3. `o` is greater than `e`. Stop here. The first string is greater. +1. `G` é o mesmo que `G`. +2. `l` é o mesmo que `l`. +3. `o` é maior que `e`. Pare aqui. A primeira string é maior. ```smart header="Not a real dictionary, but Unicode order" -The comparison algorithm given above is roughly equivalent to the one used in dictionaries or phone books, but it's not exactly the same. +O algoritmo de comparação dado acima é aproximadamente equivalente ao usado em dicionários ou catálogos telefônicos, mas não é exatamente o mesmo. -For instance, case matters. A capital letter `"A"` is not equal to the lowercase `"a"`. Which one is greater? The lowercase `"a"`. Why? Because the lowercase character has a greater index in the internal encoding table JavaScript uses (Unicode). We'll get back to specific details and consequences of this in the chapter . +Por exemplo, um caso importante. Uma letra maiúscula `"A"` não é igual à minúscula `"a"`. Qual delas é maior? A `"a"` minúscula. Por quê? Porque o caractere minúsculo tem um índice maior na tabela de codificação interna que o JavaScript usa (Unicode). Voltaremos a detalhes específicos e conseqüências disso no capítulo . ``` -## Comparison of different types +## Comparação de diferentes tipos -When comparing values of different types, JavaScript converts the values to numbers. +Ao comparar valores de diferentes tipos, o JavaScript converte os valores em números. -For example: +Por exemplo: ```js run alert( '2' > 1 ); // true, string '2' becomes a number 2 alert( '01' == 1 ); // true, string '01' becomes a number 1 ``` -For boolean values, `true` becomes `1` and `false` becomes `0`. +Para valores booleanos, `true` torna-se` 1` e `false` torna-se` 0`. -For example: +Por exemplo: ```js run alert( true == 1 ); // true @@ -84,12 +84,12 @@ alert( false == 0 ); // true ``` ````smart header="A funny consequence" -It is possible that at the same time: +É possível que ao mesmo tempo: -- Two values are equal. -- One of them is `true` as a boolean and the other one is `false` as a boolean. +- Dois valores são iguais. +- Um deles é `true` como booleano e o outro é` false` como booleano. -For example: +Por exemplo: ```js run let a = 0; @@ -101,70 +101,67 @@ alert( Boolean(b) ); // true alert(a == b); // true! ``` -From JavaScript's standpoint, this result is quite normal. An equality check converts values using the numeric conversion (hence `"0"` becomes `0`), while the explicit `Boolean` conversion uses another set of rules. +Do ponto de vista do JavaScript, esse resultado é normal. Uma verificação de igualdade converte valores usando a conversão numérica (portanto `"0"` torna-se `0`), enquanto a conversão explícita de` Boolean` usa outro conjunto de regras. ```` -## Strict equality +## Igualdade estrita -A regular equality check `==` has a problem. It cannot differentiate `0` from `false`: +Uma verificação de igualdade regular `==` tem um problema. Não é possível diferenciar `0` de` false`: ```js run alert( 0 == false ); // true ``` -The same thing happens with an empty string: +A mesma coisa acontece com uma string vazia: ```js run alert( '' == false ); // true ``` -This happens because operands of different types are converted to numbers by the equality operator `==`. An empty string, just like `false`, becomes a zero. +Isso acontece porque operandos de diferentes tipos são convertidos em números pelo operador de igualdade `==`. Uma string vazia, assim como `false`, se torna um zero. -What to do if we'd like to differentiate `0` from `false`? +O que fazer se quisermos diferenciar `0` de` false`? -**A strict equality operator `===` checks the equality without type conversion.** +**Um operador de igualdade estrito `===` verifica a igualdade sem conversão de tipo.** -In other words, if `a` and `b` are of different types, then `a === b` immediately returns `false` without an attempt to convert them. +Em outras palavras, se `a` e `b` forem de tipos diferentes, então `a === b` retornará imediatamente `false` sem uma tentativa de convertê-los. -Let's try it: +Vamos tentar: ```js run alert( 0 === false ); // false, because the types are different ``` -There is also a "strict non-equality" operator `!==` analogous to `!=`. +Existe também um operador "diferença estrita" `!==` análogo a `!=`. -The strict equality operator is a bit longer to write, but makes it obvious what's going on and leaves less room for errors. +O operador de igualdade estrito é um pouco mais longo para escrever, mas torna óbvio o que está acontecendo e deixa menos espaço para erros. -## Comparison with null and undefined +## Comparação com "null" e "undefined" -Let's see more edge cases. +Vamos ver mais casos extremos. -There's a non-intuitive behavior when `null` or `undefined` are compared to other values. +Existe um comportamento não intuitivo quando `null` ou` undefined` são comparados com outros valores. -For a strict equality check `===` -: These values are different, because each of them is a different type. +Para uma verificação de igualdade estrita `===` : Esses valores são diferentes, porque cada um deles é um tipo diferente. ```js run alert( null === undefined ); // false ``` -For a non-strict check `==` -: There's a special rule. These two are a "sweet couple": they equal each other (in the sense of `==`), but not any other value. +Para uma verificação não estrita `==` : Existe uma regra especial. Esses dois são um "lindo casal": eles são iguais (no sentido de "=="), mas com nenhum outro valor. ```js run alert( null == undefined ); // true ``` -For maths and other comparisons `< > <= >=` -: `null/undefined` are converted to numbers: `null` becomes `0`, while `undefined` becomes `NaN`. +Para matemática e outras comparações `<> <=> =` : `null/undefined` são convertidos em números: `null` torna-se `0`, enquanto `undefined` torna-se `NaN`. -Now let's see some funny things that happen when we apply these rules. And, what's more important, how to not fall into a trap with them. +Agora vamos ver algumas coisas engraçadas que acontecem quando aplicamos essas regras. E, o que é mais importante, como não cair em uma armadilha com eles. -### Strange result: null vs 0 +### Resultado estranho: "null" vs "0" -Let's compare `null` with a zero: +Vamos comparar `null` com um zero: ```js run alert( null > 0 ); // (1) false @@ -172,15 +169,15 @@ alert( null == 0 ); // (2) false alert( null >= 0 ); // (3) *!*true*/!* ``` -Mathematically, that's strange. The last result states that "`null` is greater than or equal to zero", so in one of the comparisons above it must be `true`, but they are both false. +Matematicamente, isso é estranho. O último resultado afirma que "`null` é maior que ou igual a zero", então em uma das comparações acima deve ser `true`, mas ambos casos são falsos. -The reason is that an equality check `==` and comparisons `> < >= <=` work differently. Comparisons convert `null` to a number, treating it as `0`. That's why (3) `null >= 0` is true and (1) `null > 0` is false. +A razão é que uma verificação de igualdade `==` e comparações `> < >= <=` funcionam de maneira diferente. Comparações convertem `null` para um número, tratando-o como `0`. É por isso que (3) `null >= 0` é verdadeiro e (1) `null > 0` é falso. -On the other hand, the equality check `==` for `undefined` and `null` is defined such that, without any conversions, they equal each other and don't equal anything else. That's why (2) `null == 0` is false. +Por outro lado, a verificação de igualdade `==` para `undefined` e `null` é definida de tal forma que, sem nenhuma conversão, elas são iguais entre si e não equivalem a qualquer outra coisa. É por isso que (2) `null == 0` é falso. -### An incomparable undefined +### Um incomparável "undefined" -The value `undefined` shouldn't be compared to other values: +O valor `undefined` não deve ser comparado a outros valores: ```js run alert( undefined > 0 ); // false (1) @@ -188,25 +185,25 @@ alert( undefined < 0 ); // false (2) alert( undefined == 0 ); // false (3) ``` -Why does it dislike zero so much? Always false! +Por que não gostam do zero? Sempre falso! -We get these results because: +Obtemos estes resultados porque: -- Comparisons `(1)` and `(2)` return `false` because `undefined` gets converted to `NaN` and `NaN` is a special numeric value which returns `false` for all comparisons. -- The equality check `(3)` returns `false` because `undefined` only equals `null` and no other value. +- Comparações `(1)` e `(2)` retornam `false` porque` undefined` é convertido para `NaN` e` NaN` é um valor numérico especial que retorna `false` para todas as comparações. +- A verificação de igualdade `(3)` retorna `false` porque` undefined` somente é igual a `null` e nenhum outro valor. -### Evade problems +### Evitar problemas -Why did we go over these examples? Should we remember these peculiarities all the time? Well, not really. Actually, these tricky things will gradually become familiar over time, but there's a solid way to evade problems with them: +Por que nós examinamos esses exemplos? Devemos nos lembrar dessas peculiaridades o tempo todo? Bem, na verdade não. Na verdade, essas coisas complicadas gradualmente se tornarão familiares ao longo do tempo, mas há uma maneira sólida de evitar problemas com elas: -Just treat any comparison with `undefined/null` except the strict equality `===` with exceptional care. +Apenas trate qualquer comparação com `undefined / null` exceto a igualdade estrita ` === ` com cuidado excepcional. -Don't use comparisons `>= > < <=` with a variable which may be `null/undefined`, unless you're really sure of what you're doing. If a variable can have these values, check for them separately. +Não use comparações `> => <<=` com uma variável que pode ser `null / undefined`, a menos que você tenha certeza do que está fazendo. Se uma variável puder ter esses valores, verifique-os separadamente. -## Summary +## Resumo -- Comparison operators return a boolean value. -- Strings are compared letter-by-letter in the "dictionary" order. -- When values of different types are compared, they get converted to numbers (with the exclusion of a strict equality check). -- The values `null` and `undefined` equal `==` each other and do not equal any other value. -- Be careful when using comparisons like `>` or `<` with variables that can occasionally be `null/undefined`. Checking for `null/undefined` separately is a good idea. +- Operadores de comparação retornam um valor booleano. +- As strings são comparadas letra por letra na ordem "dicionário". +- Quando valores de diferentes tipos são comparados, eles são convertidos em números (com a exclusão de uma verificação de igualdade estrita). +- Os valores `null` e` undefined` usando `==` são iguais entre eles e não são iguais a nenhum outro valor. +- Tenha cuidado ao usar comparações como `>` ou `<` com variáveis que ocasionalmente podem ser 'null / undefined'. Verificar se há "null / undefined" separadamente é uma boa ideia. From 48b58abfd4a70d89aeaedc2b64dfa4dbae7ee4bc Mon Sep 17 00:00:00 2001 From: "C@irx" Date: Mon, 3 Jun 2019 05:55:50 -0300 Subject: [PATCH 4/9] translate operators --- .../1-increment-order/solution.md | 10 +- .../07-operators/1-increment-order/task.md | 4 +- .../2-assignment-result/solution.md | 6 +- .../07-operators/2-assignment-result/task.md | 4 +- 1-js/02-first-steps/07-operators/article.md | 335 +++++++++--------- 5 files changed, 179 insertions(+), 180 deletions(-) diff --git a/1-js/02-first-steps/07-operators/1-increment-order/solution.md b/1-js/02-first-steps/07-operators/1-increment-order/solution.md index 8a44d798e..27669c4ac 100644 --- a/1-js/02-first-steps/07-operators/1-increment-order/solution.md +++ b/1-js/02-first-steps/07-operators/1-increment-order/solution.md @@ -1,5 +1,5 @@ -The answer is: +A resposta é: - `a = 2` - `b = 2` @@ -9,10 +9,10 @@ The answer is: ```js run no-beautify let a = 1, b = 1; -alert( ++a ); // 2, prefix form returns the new value -alert( b++ ); // 1, postfix form returns the old value +alert( ++a ); // 2, a forma prefixo retorna o novo valor +alert( b++ ); // 1, a forma sufijo retorna o valor antigo -alert( a ); // 2, incremented once -alert( b ); // 2, incremented once +alert( a ); // 2, incrementado uma vez +alert( b ); // 2, incrementado uma vez ``` diff --git a/1-js/02-first-steps/07-operators/1-increment-order/task.md b/1-js/02-first-steps/07-operators/1-increment-order/task.md index 7db092389..057f25e73 100644 --- a/1-js/02-first-steps/07-operators/1-increment-order/task.md +++ b/1-js/02-first-steps/07-operators/1-increment-order/task.md @@ -2,9 +2,9 @@ importance: 5 --- -# The postfix and prefix forms +# As formas de sufixo e prefixo -What are the final values of all variables `a`, `b`, `c` and `d` after the code below? +Quais são os valores finais de todas as variáveis `a`, `b`, `c` e `d` após o código abaixo? ```js let a = 1, b = 1; diff --git a/1-js/02-first-steps/07-operators/2-assignment-result/solution.md b/1-js/02-first-steps/07-operators/2-assignment-result/solution.md index e3113b4cd..b6842ba1c 100644 --- a/1-js/02-first-steps/07-operators/2-assignment-result/solution.md +++ b/1-js/02-first-steps/07-operators/2-assignment-result/solution.md @@ -1,5 +1,5 @@ -The answer is: +A resposta é: -- `a = 4` (multiplied by 2) -- `x = 5` (calculated as 1 + 4) +- `a = 4` (multiplicado por 2) +- `x = 5` (calculado como 1 + 4) diff --git a/1-js/02-first-steps/07-operators/2-assignment-result/task.md b/1-js/02-first-steps/07-operators/2-assignment-result/task.md index 5345c9485..144bb6093 100644 --- a/1-js/02-first-steps/07-operators/2-assignment-result/task.md +++ b/1-js/02-first-steps/07-operators/2-assignment-result/task.md @@ -2,9 +2,9 @@ importance: 3 --- -# Assignment result +# Resultado da atribuição -What are the values of `a` and `x` after the code below? +Quais são os valores de `a` e `x` depois do código abaixo? ```js let a = 2; diff --git a/1-js/02-first-steps/07-operators/article.md b/1-js/02-first-steps/07-operators/article.md index 74b27e871..7228b45fa 100644 --- a/1-js/02-first-steps/07-operators/article.md +++ b/1-js/02-first-steps/07-operators/article.md @@ -1,15 +1,15 @@ -# Operators +# Operadores -We know many operators from school. They are things like addition `+`, multiplication `*`, subtraction `-`, and so on. +Conhecemos muitos operadores da escola. São coisas como adição `+`, multiplicação `*`, subtração `-` e assim por diante. -In this chapter, we'll concentrate on aspects of operators that are not covered by school arithmetic. +Neste capítulo, nos concentraremos em aspectos de operadores que não são cobertos pela aritmética da escola. -## Terms: "unary", "binary", "operand" +## Termos: "unário", "binário", "operando" -Before we move on, let's grasp some common terminology. +Antes de prosseguirmos, vamos entender algumas terminologias comuns. -- *An operand* -- is what operators are applied to. For instance, in the multiplication of `5 * 2` there are two operands: the left operand is `5` and the right operand is `2`. Sometimes, people call these "arguments" instead of "operands". -- An operator is *unary* if it has a single operand. For example, the unary negation `-` reverses the sign of a number: +- *Um operando* - é ao que os operadores são aplicados. Por exemplo, na multiplicação de `5 * 2` existem dois operandos: o operando esquerdo é `5` e o operando direito é `2`. Às vezes, as pessoas chamam eles de "argumentos" em vez de "operandos". +- Um operador é *unário* se tiver um único operando. Por exemplo, a negação unária `-` inverte o sinal de um número: ```js run let x = 1; @@ -17,67 +17,67 @@ Before we move on, let's grasp some common terminology. *!* x = -x; */!* - alert( x ); // -1, unary negation was applied + alert( x ); // -1, negação unária foi aplicada ``` -- An operator is *binary* if it has two operands. The same minus exists in binary form as well: +- Um operador é *binário* se tiver dois operandos. O mesmo menos também existe na forma binária: ```js run no-beautify let x = 1, y = 3; - alert( y - x ); // 2, binary minus subtracts values + alert( y - x ); // 2, binário menos subtrai valores ``` - Formally, we're talking about two different operators here: the unary negation (single operand: reverses the sign) and the binary subtraction (two operands: subtracts). + Formalmente, estamos falando de dois operadores diferentes aqui: a negação unária (operando único: inverte o sinal) e a subtração binária (dois operandos: subtrai). -## String concatenation, binary + +## Concatenação de string, binário + -Now, let's see special features of JavaScript operators that are beyond school arithmetics. +Agora, vamos ver recursos especiais de operadores de JavaScript que estão além da aritmética da escola. -Usually, the plus operator `+` sums numbers. +Normalmente, o operador mais `+` soma números. -But, if the binary `+` is applied to strings, it merges (concatenates) them: +Mas, se o binário `+` é aplicado às strings, ele mescla (concatena) elas: ```js -let s = "my" + "string"; -alert(s); // mystring +let s = "minha" + "string"; +alert(s); // minhastring ``` -Note that if one of the operands is a string, the other one is converted to a string too. +Observe que, se um dos operandos for uma string, o outro também será convertido em uma string. -For example: +Por exemplo: ```js run alert( '1' + 2 ); // "12" alert( 2 + '1' ); // "21" ``` -See, it doesn't matter whether the first operand is a string or the second one. The rule is simple: if either operand is a string, the other one is converted into a string as well. +Veja, não importa se o primeiro operando é uma string ou o segundo. A regra é simples: se um dos operandos é uma string, o outro é convertido em uma string também. -However, note that operations run from left to right. If there are two numbers followed by a string, the numbers will be added before being converted to a string: +No entanto, observe que as operações são executadas da esquerda para a direita. Se houver dois números seguidos por uma string, os números serão adicionados antes de serem convertidos em uma string: ```js run -alert(2 + 2 + '1' ); // "41" and not "221" +alert(2 + 2 + '1' ); // "41" e não "221" ``` -String concatenation and conversion is a special feature of the binary plus `+`. Other arithmetic operators work only with numbers and always convert their operands to numbers. +A concatenação e conversão de strings é uma característica especial do binário mais `+`. Outros operadores aritméticos trabalham apenas com números e sempre convertem seus operandos em números. -For instance, subtraction and division: +Por exemplo, subtração e divisão: ```js run alert( 2 - '1' ); // 1 alert( '6' / '2' ); // 3 ``` -## Numeric conversion, unary + +## Conversão numérica, unário + -The plus `+` exists in two forms: the binary form that we used above and the unary form. +O mais '+' existe em duas formas: a forma binária que usamos acima e a forma unária. -The unary plus or, in other words, the plus operator `+` applied to a single value, doesn't do anything to numbers. But if the operand is not a number, the unary plus converts it into a number. +O unário mais ou, em outras palavras, o operador mais `+` aplicado a um único valor, não faz nada para números. Mas se o operando não é um número, o unário mais o converte em um número. -For example: +Por exemplo: ```js run -// No effect on numbers +// Nenhum efeito nos números let x = 1; alert( +x ); // 1 @@ -85,78 +85,78 @@ let y = -2; alert( +y ); // -2 *!* -// Converts non-numbers +// Converte não números alert( +true ); // 1 alert( +"" ); // 0 */!* ``` -It actually does the same thing as `Number(...)`, but is shorter. +Realmente faz a mesma coisa que `Number (...)`, mas é mais curto. -The need to convert strings to numbers arises very often. For example, if we are getting values from HTML form fields, they are usually strings. +A necessidade de converter seqüências de caracteres em números surge com muita freqüência. Por exemplo, se estamos obtendo valores de campos de formulário HTML, eles geralmente são strings. -What if we want to sum them? +E se quisermos somar? -The binary plus would add them as strings: +O binário plus os adicionaria como strings: ```js run -let apples = "2"; -let oranges = "3"; +let macas = "2"; +let laranjas = "3"; -alert( apples + oranges ); // "23", the binary plus concatenates strings +alert( macas + laranjas ); // "23", o binário mais concatena strings ``` -If we want to treat them as numbers, we need to convert and then sum them: +Se quisermos tratá-los como números, precisamos convertê-los e depois somar: ```js run -let apples = "2"; -let oranges = "3"; +let macas = "2"; +let laranjas = "3"; *!* -// both values converted to numbers before the binary plus -alert( +apples + +oranges ); // 5 +// ambos os valores convertidos em números antes do binário mais +alert( +macas + +laranjas ); // 5 */!* -// the longer variant -// alert( Number(apples) + Number(oranges) ); // 5 +// a variante mais longa +// alert( Number(macas) + Number(laranjas) ); // 5 ``` -From a mathematician's standpoint, the abundance of pluses may seem strange. But from a programmer's standpoint, there's nothing special: unary pluses are applied first, they convert strings to numbers, and then the binary plus sums them up. +Do ponto de vista de um matemático, a abundância de vantagens pode parecer estranha. Mas, do ponto de vista de um programador, não há nada de especial: vantagens absolutas são aplicadas primeiro, elas convertem sequências de caracteres em números e, em seguida, o binário acrescenta-as. -Why are unary pluses applied to values before the binary ones? As we're going to see, that's because of their *higher precedence*. +Por que as vantagens unárias são aplicadas aos valores antes dos binários? Como vamos ver, isso é por causa de sua *precedência mais alta*. -## Operator precedence +## Operador precedente -If an expression has more than one operator, the execution order is defined by their *precedence*, or, in other words, the implicit priority order of operators. +Se uma expressão tiver mais de um operador, a ordem de execução é definida por sua *precedência* ou, em outras palavras, a ordem de prioridade implícita dos operadores. -From school, we all know that the multiplication in the expression `1 + 2 * 2` should be calculated before the addition. That's exactly the precedence thing. The multiplication is said to have *a higher precedence* than the addition. +Da escola, todos nós sabemos que a multiplicação na expressão `1 + 2 * 2` deve ser calculada antes da adição. Isso é exatamente a coisa precedente. Diz-se que a multiplicação tem *uma precedência mais alta* do que a adição. -Parentheses override any precedence, so if we're not satisfied with the implicit order, we can use them to change it. For example: `(1 + 2) * 2`. +Os parênteses anulam qualquer precedência, portanto, se não estivermos satisfeitos com a ordem implícita, podemos usá-los para alterá-la. Por exemplo: `(1 + 2) * 2`. -There are many operators in JavaScript. Every operator has a corresponding precedence number. The one with the larger number executes first. If the precedence is the same, the execution order is from left to right. +Existem muitos operadores em JavaScript. Todo operador tem um número de precedência correspondente. Aquele com o maior número é executado primeiro. Se a precedência é a mesma, a ordem de execução é da esquerda para a direita. -Here's an extract from the [precedence table](https://developer.mozilla.org/en/JavaScript/Reference/operators/operator_precedence) (you don't need to remember this, but note that unary operators are higher than corresponding binary ones): +Aqui está um extrato da [tabela de precedência](https://developer.mozilla.org/en/JavaScript/Reference/operators/operator_precedence) (você não precisa se lembrar disso, mas observe que os operadores unários são mais altos que os binários): -| Precedence | Name | Sign | +| Precedência | Nome | Sinal | |------------|------|------| | ... | ... | ... | -| 16 | unary plus | `+` | -| 16 | unary negation | `-` | -| 14 | multiplication | `*` | -| 14 | division | `/` | -| 13 | addition | `+` | -| 13 | subtraction | `-` | +| 16 | Positivo Unário | `+` | +| 16 | Negativo Unário | `-` | +| 14 | Multiplicação | `*` | +| 14 | Divisão | `/` | +| 13 | Adição | `+` | +| 13 | Subtração | `-` | | ... | ... | ... | -| 3 | assignment | `=` | +| 3 | Atribuição | `=` | | ... | ... | ... | -As we can see, the "unary plus" has a priority of `16` which is higher than the `13` of "addition" (binary plus). That's why, in the expression `"+apples + +oranges"`, unary pluses work before the addition. +Como podemos ver, o "positivo unário" tem uma prioridade de `16` que é maior que o `13` de "adição" (positivo binário). É por isso que, na expressão `+macas + +laranjas`, os positivos unários trabalham antes da adição. -## Assignment +## Atribuição -Let's note that an assignment `=` is also an operator. It is listed in the precedence table with the very low priority of `3`. +Vamos notar que uma atribuição `=` também é um operador. Está listado na tabela de precedência com a prioridade muito baixa de `3`. -That's why, when we assign a variable, like `x = 2 * 2 + 1`, the calculations are done first and then the `=` is evaluated, storing the result in `x`. +É por isso que, quando atribuímos uma variável, como `x = 2 * 2 + 1`, os cálculos são feitos primeiro e depois o `=`é avaliado, armazenando o resultado em `x`. ```js let x = 2 * 2 + 1; @@ -164,7 +164,7 @@ let x = 2 * 2 + 1; alert( x ); // 5 ``` -It is possible to chain assignments: +É possível atribuições em cadeia: ```js run let a, b, c; @@ -178,14 +178,14 @@ alert( b ); // 4 alert( c ); // 4 ``` -Chained assignments evaluate from right to left. First, the rightmost expression `2 + 2` is evaluated and then assigned to the variables on the left: `c`, `b` and `a`. At the end, all the variables share a single value. +Atribuições encadeadas avaliadas da direita para a esquerda. Primeiro, a expressão mais à direita `2 + 2` é avaliada e depois atribuída às variáveis à esquerda: `c`, `b` e `a`. No final, todas as variáveis compartilham um único valor. -````smart header="The assignment operator `\"=\"` returns a value" -An operator always returns a value. That's obvious for most of them like addition `+` or multiplication `*`. But the assignment operator follows this rule too. +````smart header="The assignment operator `\"=\"` retorna um valor" +Um operador sempre retorna um valor. Isso é óbvio para a maioria deles, como adição `+` ou multiplicação `*`. Mas o operador de atribuição também segue essa regra. -The call `x = value` writes the `value` into `x` *and then returns it*. +A chamada `x = value` escreve o `value` em `x` *e depois o retorna*. -Here's a demo that uses an assignment as part of a more complex expression: +Aqui está uma demonstração que usa uma atribuição como parte de uma expressão mais complexa: ```js run let a = 1; @@ -199,168 +199,167 @@ alert( a ); // 3 alert( c ); // 0 ``` -In the example above, the result of `(a = b + 1)` is the value which is assigned to `a` (that is `3`). It is then used to subtract from `3`. +No exemplo acima, o resultado de `(a = b + 1)` é o valor que é atribuído a `a` (isto é `3`). É então usado para subtrair de `3`. -Funny code, isn't it? We should understand how it works, because sometimes we see it in 3rd-party libraries, but shouldn't write anything like that ourselves. Such tricks definitely don't make code clearer or readable. +Código engraçado, não é? Devemos entender como funciona, porque às vezes vemos em bibliotecas de terceiros, mas não devemos escrever nada assim. Esses truques definitivamente não tornam o código mais claro ou legível. ```` -## Remainder % +## Restante % -The remainder operator `%`, despite its appearance, is not related to percents. +O operador restante `%`, apesar de sua aparência, não está relacionado a porcentagens. -The result of `a % b` is the remainder of the integer division of `a` by `b`. +O resultado de `a % b` é o restante da divisão inteira de `a` por `b`. -For instance: +Por exemplo: ```js run -alert( 5 % 2 ); // 1 is a remainder of 5 divided by 2 -alert( 8 % 3 ); // 2 is a remainder of 8 divided by 3 -alert( 6 % 3 ); // 0 is a remainder of 6 divided by 3 +alert( 5 % 2 ); // 1 é o restante de 5 dividido por 2 +alert( 8 % 3 ); // 2 é o restante de 8 dividido por 3 +alert( 6 % 3 ); // 0 é o restante de 6 dividido por 3 ``` -## Exponentiation ** +## Exponenciação ** -The exponentiation operator `**` is a recent addition to the language. +O operador de exponenciação `**` é uma adição recente ao idioma. -For a natural number `b`, the result of `a ** b` is `a` multiplied by itself `b` times. - -For instance: +Para um número natural `b`, o resultado de `a ** b` é `a` multiplicado por si mesmo `b` vezes. +Por exemplo: ```js run alert( 2 ** 2 ); // 4 (2 * 2) alert( 2 ** 3 ); // 8 (2 * 2 * 2) alert( 2 ** 4 ); // 16 (2 * 2 * 2 * 2) ``` -The operator works for non-integer numbers as well. +O operador também trabalha para números não inteiros. -For instance: +Por exemplo: ```js run -alert( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root, that's maths) -alert( 8 ** (1/3) ); // 2 (power of 1/3 is the same as a cubic root) +alert( 4 ** (1/2) ); // 2 (potência1/2 é o mesmo que uma raiz quadrada, isso é matemática) +alert( 8 ** (1/3) ); // 2 (potência de 1/3 é o mesmo que uma raiz cúbica) ``` -## Increment/decrement +## Incremento/decremento - + -Increasing or decreasing a number by one is among the most common numerical operations. +Aumentar ou diminuir um número por um está entre as operações numéricas mais comuns. -So, there are special operators for it: +Então, existem operadores especiais para isso: -- **Increment** `++` increases a variable by 1: +- **Incremento** `++` aumenta uma variável por 1: ```js run no-beautify - let counter = 2; - counter++; // works the same as counter = counter + 1, but is shorter - alert( counter ); // 3 + let contador = 2; + contador++; // funciona da mesma forma que o contador = contador + 1, mas é mais curto + alert( contador ); // 3 ``` -- **Decrement** `--` decreases a variable by 1: +- **Decremento** `--` diminui uma variável por 1: ```js run no-beautify - let counter = 2; - counter--; // works the same as counter = counter - 1, but is shorter - alert( counter ); // 1 + let contador = 2; + contador--; // funciona da mesma forma que o contador = contador - 1, mas é mais curto + alert( contador ); // 1 ``` -```warn -Increment/decrement can only be applied to variables. Trying to use it on a value like `5++` will give an error. +```aviso +Incremento/decremento só pode ser aplicado a variáveis. Tentando usá-lo em um valor como `5 ++` irá dar um erro. ``` -The operators `++` and `--` can be placed either before or after a variable. +Os operadores `++` e `--` podem ser colocados antes ou depois de uma variável. -- When the operator goes after the variable, it is in "postfix form": `counter++`. -- The "prefix form" is when the operator goes before the variable: `++counter`. +- Quando o operador vai atrás da variável, está na "forma sufixo": `contador++`. +- A "forma prefixo" é quando o operador vai antes da variável: `++contador`. -Both of these statements do the same thing: increase `counter` by `1`. +Ambas as declarações fazem a mesma coisa: aumentar `contador` por `1`. -Is there any difference? Yes, but we can only see it if we use the returned value of `++/--`. +Existe alguma diferença? Sim, mas só podemos vê-lo se usarmos o valor retornado de `++/--`. -Let's clarify. As we know, all operators return a value. Increment/decrement is no exception. The prefix form returns the new value while the postfix form returns the old value (prior to increment/decrement). +Vamos esclarecer. Como sabemos, todos os operadores retornam um valor. Incremento/decremento não é exceção. O formulário de prefixo retorna o novo valor enquanto o formulário de postfix retorna o valor antigo (antes do incremento / decremento). -To see the difference, here's an example: +Para ver a diferença, aqui está um exemplo: ```js run -let counter = 1; -let a = ++counter; // (*) +let contador = 1; +let a = ++contador; // (*) alert(a); // *!*2*/!* ``` -In the line `(*)`, the *prefix* form `++counter` increments `counter` and returns the new value, `2`. So, the `alert` shows `2`. +Na linha `(*)`, a forma *prefixo* `++contador` incrementa `contador` e retorna o novo valor, `2`. Então, o `alert` mostra `2`. -Now, let's use the postfix form: +Agora vamos usar a forma sufixo: ```js run -let counter = 1; -let a = counter++; // (*) changed ++counter to counter++ +let contador = 1; +let a = contador++; // (*) altere ++contador a contador++ alert(a); // *!*1*/!* ``` -In the line `(*)`, the *postfix* form `counter++` also increments `counter` but returns the *old* value (prior to increment). So, the `alert` shows `1`. +Na linha `(*)`, a forma *sufixo* `contador++` também incrementa `contador` mas retorna o valor *antigo* (antes do incremento). Então, o `alert` mostra `1`. -To summarize: +Para resumir: -- If the result of increment/decrement is not used, there is no difference in which form to use: +- Se o resultado de incremento/decremento não for usado, não há diferença em qual formulário usar: ```js run - let counter = 0; - counter++; - ++counter; - alert( counter ); // 2, the lines above did the same + let contador = 0; + contador++; + ++contador; + alert( contador ); // 2, as linhas acima fizeram o mesmo ``` -- If we'd like to increase a value *and* immediately use the result of the operator, we need the prefix form: +- Se quisermos aumentar um valor *e* imediatamente usar o resultado do operador, precisamos da forma prefixo: ```js run - let counter = 0; - alert( ++counter ); // 1 + let contador = 0; + alert( ++contador ); // 1 ``` -- If we'd like to increment a value but use its previous value, we need the postfix form: +- Se quisermos incrementar um valor, mas usar seu valor anterior, precisamos da forma sufixo: ```js run - let counter = 0; - alert( counter++ ); // 0 + let contador = 0; + alert( contador++ ); // 0 ``` ````smart header="Increment/decrement among other operators" -The operators `++/--` can be used inside expressions as well. Their precedence is higher than most other arithmetical operations. +Os operadores `++/--` também podem ser usados dentro de expressões. Sua precedência é maior do que a maioria das outras operações aritméticas. -For instance: +Por exemplo: ```js run -let counter = 1; -alert( 2 * ++counter ); // 4 +let contador = 1; +alert( 2 * ++contador ); // 4 ``` -Compare with: +Compare com: ```js run -let counter = 1; -alert( 2 * counter++ ); // 2, because counter++ returns the "old" value +let contador = 1; +alert( 2 * contador++ ); // 2, porque contador++ retorna o valor "antigo" ``` -Though technically okay, such notation usually makes code less readable. One line does multiple things -- not good. +Embora tecnicamente bem, essa notação geralmente torna o código menos legível. Uma linha faz várias coisas -- não é boa. -While reading code, a fast "vertical" eye-scan can easily miss something like `counter++` and it won't be obvious that the variable increased. +Durante a leitura do código, uma rápida varredura ocular "vertical" pode facilmente perder algo como "contador ++" e não será óbvio que a variável tenha aumentado. -We advise a style of "one line -- one action": +Aconselhamos um estilo de "uma linha -- uma ação": ```js run -let counter = 1; -alert( 2 * counter ); -counter++; +let contador = 1; +alert( 2 * contador ); +contador++; ``` ```` -## Bitwise operators +## Operadores bit a bit -Bitwise operators treat arguments as 32-bit integer numbers and work on the level of their binary representation. +Operadores bit a bit tratam argumentos como números inteiros de 32 bits e trabalham no nível de sua representação binária. -These operators are not JavaScript-specific. They are supported in most programming languages. +Esses operadores não são específicos do JavaScript. Eles são suportados na maioria das linguagens de programação. -The list of operators: +A lista de operadores: - AND ( `&` ) - OR ( `|` ) @@ -370,13 +369,13 @@ The list of operators: - RIGHT SHIFT ( `>>` ) - ZERO-FILL RIGHT SHIFT ( `>>>` ) -These operators are used very rarely. To understand them, we need to delve into low-level number representation and it would not be optimal to do that right now, especially since we won't need them any time soon. If you're curious, you can read the [Bitwise Operators](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators) article on MDN. It would be more practical to do that when a real need arises. +Esses operadores são usados muito raramente. Para entendê-los, precisamos nos aprofundar na representação numérica de baixo nível e não seria ideal fazer isso agora, especialmente porque não precisaremos deles em breve. Se você está curioso, você pode ler o artigo [Bitwise Operators](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators) no MDN. Seria mais prático fazer isso quando surgir uma necessidade real. -## Modify-in-place +## Modificar-no-local -We often need to apply an operator to a variable and store the new result in that same variable. +Geralmente, precisamos aplicar um operador a uma variável e armazenar o novo resultado nessa mesma variável. -For example: +Por exemplo: ```js let n = 2; @@ -384,63 +383,63 @@ n = n + 5; n = n * 2; ``` -This notation can be shortened using the operators `+=` and `*=`: +Esta notação pode ser encurtada usando os operadores `+=` e `*=`: ```js run let n = 2; -n += 5; // now n = 7 (same as n = n + 5) -n *= 2; // now n = 14 (same as n = n * 2) +n += 5; // agora n = 7 (igual a n = n + 5) +n *= 2; // agora n = 14 (igual a n = n * 2) alert( n ); // 14 ``` -Short "modify-and-assign" operators exist for all arithmetical and bitwise operators: `/=`, `-=`, etc. +Operadores curtos de "modificar e atribuir" existem para todos os operadores aritméticos e bit a bit: `/=`, `-=`, etc. -Such operators have the same precedence as a normal assignment, so they run after most other calculations: +Esses operadores têm a mesma precedência que uma atribuição normal, portanto, eles são executados após a maioria dos outros cálculos: ```js run let n = 2; n *= 3 + 5; -alert( n ); // 16 (right part evaluated first, same as n *= 8) +alert( n ); // 16 (parte direita avaliada primeiro, o mesmo que n *= 8) ``` -## Comma +## Vírgula -The comma operator `,` is one of the rarest and most unusual operators. Sometimes, it's used to write shorter code, so we need to know it in order to understand what's going on. +O operador de vírgula `,` é um dos operadores mais raros e incomuns. Às vezes, é usado para escrever códigos mais curtos, então precisamos conhecê-lo para entender o que está acontecendo. -The comma operator allows us to evaluate several expressions, dividing them with a comma `,`. Each of them is evaluated but only the result of the last one is returned. +O operador vírgula nos permite avaliar várias expressões, dividindo-as com uma vírgula `,`. Cada um deles é avaliado, mas somente o resultado do último é retornado. -For example: +Por exemplo: ```js run *!* let a = (1 + 2, 3 + 4); */!* -alert( a ); // 7 (the result of 3 + 4) +alert( a ); // 7 (o resultado de 3 + 4) ``` -Here, the first expression `1 + 2` is evaluated and its result is thrown away. Then, `3 + 4` is evaluated and returned as the result. +Aqui, a primeira expressão `1 + 2` é avaliada e seu resultado é descartado. Então, `3 + 4` é avaliado e retornado como resultado. ```smart header="Comma has a very low precedence" -Please note that the comma operator has very low precedence, lower than `=`, so parentheses are important in the example above. +Por favor, note que o operador vírgula tem precedência muito baixa, menor que `=`, então parênteses são importantes no exemplo acima. -Without them: `a = 1 + 2, 3 + 4` evaluates `+` first, summing the numbers into `a = 3, 7`, then the assignment operator `=` assigns `a = 3`, and finally the number after the comma, `7`, is not processed so it's ignored. +Sem eles: `a = 1 + 2, 3 + 4` avalia primeiro o `+`, somando os números em `a = 3, 7`, então o operador de atribuição `=` atribui `a = 3` e finalmente o número depois da vírgula, `7`, não é processado, então é ignorado. ``` -Why do we need an operator that throws away everything except the last part? +Por que precisamos de um operador que jogue fora tudo, exceto a última parte? -Sometimes, people use it in more complex constructs to put several actions in one line. +Às vezes, as pessoas usam em construções mais complexas para colocar várias ações em uma linha. -For example: +Por exemplo: ```js -// three operations in one line +// três operações em uma linha for (*!*a = 1, b = 3, c = a * b*/!*; a < 10; a++) { ... } ``` -Such tricks are used in many JavaScript frameworks. That's why we're mentioning them. But, usually, they don't improve code readability so we should think well before using them. +Esses truques são usados em muitos frameworks JavaScript. É por isso que estamos mencionando eles. Mas, geralmente, eles não melhoram a legibilidade do código, então devemos pensar bem antes de usá-los. From c5b7bfc75aa6d466e3280205857eeeef82104f52 Mon Sep 17 00:00:00 2001 From: "C@irx" Date: Mon, 3 Jun 2019 06:09:15 -0300 Subject: [PATCH 5/9] translate operators --- 1-js/02-first-steps/07-operators/article.md | 62 ++++++++++----------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/1-js/02-first-steps/07-operators/article.md b/1-js/02-first-steps/07-operators/article.md index 7228b45fa..87288ae08 100644 --- a/1-js/02-first-steps/07-operators/article.md +++ b/1-js/02-first-steps/07-operators/article.md @@ -251,16 +251,16 @@ Então, existem operadores especiais para isso: - **Incremento** `++` aumenta uma variável por 1: ```js run no-beautify - let contador = 2; - contador++; // funciona da mesma forma que o contador = contador + 1, mas é mais curto - alert( contador ); // 3 + let counter = 2; + counter++; // funciona da mesma forma que o counter = counter + 1, mas é mais curto + alert( counter ); // 3 ``` - **Decremento** `--` diminui uma variável por 1: ```js run no-beautify - let contador = 2; - contador--; // funciona da mesma forma que o contador = contador - 1, mas é mais curto - alert( contador ); // 1 + let counter = 2; + counter--; // funciona da mesma forma que o counter = counter - 1, mas é mais curto + alert( counter ); // 1 ``` ```aviso @@ -269,10 +269,10 @@ Incremento/decremento só pode ser aplicado a variáveis. Tentando usá-lo em um Os operadores `++` e `--` podem ser colocados antes ou depois de uma variável. -- Quando o operador vai atrás da variável, está na "forma sufixo": `contador++`. -- A "forma prefixo" é quando o operador vai antes da variável: `++contador`. +- Quando o operador vai atrás da variável, está na "forma sufixo": `counter++`. +- A "forma prefixo" é quando o operador vai antes da variável: `++counter`. -Ambas as declarações fazem a mesma coisa: aumentar `contador` por `1`. +Ambas as declarações fazem a mesma coisa: aumentar `counter` por `1`. Existe alguma diferença? Sim, mas só podemos vê-lo se usarmos o valor retornado de `++/--`. @@ -281,46 +281,46 @@ Vamos esclarecer. Como sabemos, todos os operadores retornam um valor. Increment Para ver a diferença, aqui está um exemplo: ```js run -let contador = 1; -let a = ++contador; // (*) +let counter = 1; +let a = ++counter; // (*) alert(a); // *!*2*/!* ``` -Na linha `(*)`, a forma *prefixo* `++contador` incrementa `contador` e retorna o novo valor, `2`. Então, o `alert` mostra `2`. +Na linha `(*)`, a forma *prefixo* `++counter` incrementa `counter` e retorna o novo valor, `2`. Então, o `alert` mostra `2`. Agora vamos usar a forma sufixo: ```js run -let contador = 1; -let a = contador++; // (*) altere ++contador a contador++ +let counter = 1; +let a = counter++; // (*) altere ++counter a counter++ alert(a); // *!*1*/!* ``` -Na linha `(*)`, a forma *sufixo* `contador++` também incrementa `contador` mas retorna o valor *antigo* (antes do incremento). Então, o `alert` mostra `1`. +Na linha `(*)`, a forma *sufixo* `counter++` também incrementa `counter` mas retorna o valor *antigo* (antes do incremento). Então, o `alert` mostra `1`. Para resumir: - Se o resultado de incremento/decremento não for usado, não há diferença em qual formulário usar: ```js run - let contador = 0; - contador++; - ++contador; - alert( contador ); // 2, as linhas acima fizeram o mesmo + let counter = 0; + counter++; + ++counter; + alert( counter ); // 2, as linhas acima fizeram o mesmo ``` - Se quisermos aumentar um valor *e* imediatamente usar o resultado do operador, precisamos da forma prefixo: ```js run - let contador = 0; - alert( ++contador ); // 1 + let counter = 0; + alert( ++counter ); // 1 ``` - Se quisermos incrementar um valor, mas usar seu valor anterior, precisamos da forma sufixo: ```js run - let contador = 0; - alert( contador++ ); // 0 + let counter = 0; + alert( counter++ ); // 0 ``` ````smart header="Increment/decrement among other operators" @@ -329,27 +329,27 @@ Os operadores `++/--` também podem ser usados dentro de expressões. Sua preced Por exemplo: ```js run -let contador = 1; -alert( 2 * ++contador ); // 4 +let counter = 1; +alert( 2 * ++counter ); // 4 ``` Compare com: ```js run -let contador = 1; -alert( 2 * contador++ ); // 2, porque contador++ retorna o valor "antigo" +let counter = 1; +alert( 2 * counter++ ); // 2, porque counter++ retorna o valor "antigo" ``` Embora tecnicamente bem, essa notação geralmente torna o código menos legível. Uma linha faz várias coisas -- não é boa. -Durante a leitura do código, uma rápida varredura ocular "vertical" pode facilmente perder algo como "contador ++" e não será óbvio que a variável tenha aumentado. +Durante a leitura do código, uma rápida varredura ocular "vertical" pode facilmente perder algo como "counter ++" e não será óbvio que a variável tenha aumentado. Aconselhamos um estilo de "uma linha -- uma ação": ```js run -let contador = 1; -alert( 2 * contador ); -contador++; +let counter = 1; +alert( 2 * counter ); +counter++; ``` ```` From 5b0f45eb8904feeea5dce9d7c17a5a18c94f05d0 Mon Sep 17 00:00:00 2001 From: "C@irx" Date: Thu, 6 Jun 2019 02:26:50 -0300 Subject: [PATCH 6/9] Translate article --- .../11-logical-operators/article.md | 198 +++++++++--------- 1 file changed, 99 insertions(+), 99 deletions(-) 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 4932020ae..072c1e9aa 100644 --- a/1-js/02-first-steps/11-logical-operators/article.md +++ b/1-js/02-first-steps/11-logical-operators/article.md @@ -1,47 +1,47 @@ -# Logical operators +# Operadores lógicos -There are three logical operators in JavaScript: `||` (OR), `&&` (AND), `!` (NOT). +Existem três operadores lógicos em JavaScript: `||` (OR), `&&` (AND), `!` (NOT). -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", eles podem ser aplicados a valores de qualquer tipo, não apenas booleanos. Seu resultado também pode 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 linhas verticais: ```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`. +Na programação clássica, o OR lógico é destinado a manipular apenas valores booleanos. Se algum de seus argumentos for `true`, ele retornará `true`, caso contrário, retornará `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, o operador é um pouco mais complicado e mais poderoso. Mas primeiro, vamos ver o que acontece com valores booleanos. -There are four possible logical combinations: +Existem quatro combinações lógicas possíveis: ```js run -alert( true || true ); // true -alert( false || true ); // true -alert( true || false ); // true -alert( false || false ); // false +alert( true || true ); // verdadeiro +alert( false || true ); // verdadeiro +alert( true || false ); // verdadeiro +alert( false || false ); // falso ``` -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 no caso em que ambos os 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 booleano, ele é convertido em booleano para a avaliação. -For instance, the number `1` is treated as `true`, the number `0` as `false`: +Por exemplo, o número `1` é tratado como `true`, o número `0` como `false`: ```js run -if (1 || 0) { // works just like if( true || false ) +if (1 || 0) { // funciona como se( verdadeiro || falso ) alert( 'truthy!' ); } ``` -Most of the time, OR `||` is used in an `if` statement to test if *any* of the given conditions is `true`. +Na maior parte do tempo, OR `||` é usado em uma instrução `if` para testar se *any* das condições dadas é `true`. -For example: +Por exemplo: ```js run let hour = 9; @@ -53,57 +53,57 @@ if (hour < 10 || hour > 18) { } ``` -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( 'The office is closed.' ); // É fim de semana } ``` -## OR finds the first truthy value +## OR encontra o primeiro valor verdadeiro -The logic described above is somewhat classical. Now, let's bring in the "extra" features of JavaScript. +A lógica descrita acima é um pouco clássica. Agora, vamos trazer os recursos "extras" do JavaScript. -The extended algorithm works as follows. +O algoritmo estendido funciona da seguinte maneira. -Given multiple OR'ed values: +Dado vários valores OR'ed: ```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 operandos da esquerda para a direita. +- Para cada operando, converte para booleano. Se o resultado for `true`, parará e retornará o valor original desse operando. +- Se todos os operandos foram avaliados (ou seja, todos eram `false`), retorna o último operando. -A value is returned in its original form, without the conversion. +Um valor é retornado em sua forma original, sem a conversão. -In other words, a chain of OR `"||"` returns the first truthy value or the last one if no such value is found. +Em outras palavras, uma cadeia de OU `"||"` retorna o primeiro valor verdadeiro ou o último caso nenhum valor seja encontrado. -For instance: +Por exemplo: ```js run -alert( 1 || 0 ); // 1 (1 is truthy) -alert( true || 'no matter what' ); // (true is truthy) +alert( 1 || 0 ); // 1 (1 é verdadeiro) +alert( true || 'no matter what' ); // (verdadeiro é verdadeira) -alert( null || 1 ); // 1 (1 is the first truthy value) -alert( null || 0 || 1 ); // 1 (the first truthy value) -alert( undefined || null || 0 ); // 0 (all falsy, returns the last value) +alert( null || 1 ); // 1 (1 é o primeiro valor verdadeiro ) +alert( null || 0 || 1 ); // 1 (o primeiro valor verdadeiro) +alert( undefined || null || 0 ); // 0 (todas falsas, retorna o último valor) ``` -This leads to some interesting usage compared to a "pure, classical, boolean-only OR". +Isso leva a um uso interessante em comparação com uma "OR pura, clássica, apenas booleana". -1. **Getting the first truthy value from a list of variables or expressions.** +1. **Obtendo o primeiro valor verdadeiro a partir de uma lista de variáveis ou expressões.** - Imagine we have several variables which can either contain data or be `null/undefined`. How can we find the first one with data? + Imagine que temos várias variáveis que podem conter dados ou ser `null/undefined`. Como podemos encontrar o primeiro com dados? - We can use OR `||`: + Nós podemos usar OR `||`: ```js run let currentUser = null; @@ -113,27 +113,27 @@ This leads to some interesting usage compared to a "pure, classical, boolean-onl let name = currentUser || defaultUser || "unnamed"; */!* - alert( name ); // selects "John" – the first truthy value + alert( name ); // seleciona "John" - o primeiro valor verdadeiro ``` - If both `currentUser` and `defaultUser` were falsy, `"unnamed"` would be the result. -2. **Short-circuit evaluation.** + Se ambos `currentUser` e `defaultUser` forem falsos, `"unnamed"` seria o resultado. +2. **Avaliação de curto-circuito.** - Operands can be not only values, but arbitrary expressions. OR evaluates and tests them from left to right. The evaluation stops when a truthy value is reached, and the value is returned. This process is called "a short-circuit evaluation" because it goes as short as possible from left to right. + Operandos não precisam ser apenas valores, mas expressões arbitrárias. OR avalia e testa da esquerda para a direita. A avaliação é interrompida quando um valor geral é atingido e o valor é retornado. Esse processo é chamado de "avaliação de curto-circuito", porque é o mais curto possível da esquerda para a direita. - This is clearly seen when the expression given as the second argument has a side effect like a variable assignment. + Isto é claramente visto quando a expressão dada como o segundo argumento tem um efeito colateral como uma atribuição de variável. - In the example below, `x` does not get assigned: + No exemplo abaixo, `x` não é atribuído: ```js run no-beautify let x; *!*true*/!* || (x = 1); - alert(x); // undefined, because (x = 1) not evaluated + alert(x); // indefinido, porque (x = 1) não foi avaliado ``` - If, instead, the first argument is `false`, `||` evaluates the second one, thus running the assignment: + Se, em vez disso, o primeiro argumento for `false`, `||` avaliará o segundo, executando assim a atribuição: ```js run no-beautify let x; @@ -143,30 +143,30 @@ This leads to some interesting usage compared to a "pure, classical, boolean-onl alert(x); // 1 ``` - An assignment is a simple case. Other side effects can also be involved. + Uma atribuição é um caso simples. Outros efeitos colaterais também podem estar envolvidos. - As we can see, such a use case is a "shorter way of doing `if`". The first operand is converted to boolean. If it's false, the second one is evaluated. + Como podemos ver, tal caso de uso é um "modo mais curto de fazer `if`". O primeiro operando é convertido em booleano. Se é falso, o segundo é avaliado. - Most of time, it's better to use a "regular" `if` to keep the code easy to understand, but sometimes this can be handy. + Na maioria das vezes, é melhor usar um "regular" `if` para manter o código fácil de entender, mas às vezes isso pode ser útil. ## && (AND) -The AND operator is represented with two ampersands `&&`: +O operador AND é representado por dois e comerciais `&&`: ```js result = a && b; ``` -In classical programming, AND returns `true` if both operands are truthy and `false` otherwise: +Na programação clássica, AND retorna `true` se ambos os operandos forem verdadeiros e `false` caso contrário: ```js run -alert( true && true ); // true -alert( false && true ); // false -alert( true && false ); // false -alert( false && false ); // false +alert( true && true ); // verdadeiro +alert( false && true ); // falso +alert( true && false ); // falso +alert( false && false ); // falso ``` -An example with `if`: +Um exemplo com `if`: ```js run let hour = 12; @@ -177,68 +177,68 @@ if (hour == 12 && minute == 30) { } ``` -Just as with OR, any value is allowed as an operand of AND: +Assim como com OR, qualquer valor é permitido como um operando de AND: ```js run -if (1 && 0) { // evaluated as true && false +if (1 && 0) { // avaliado como verdadeiro && falso alert( "won't work, because the result is falsy" ); } ``` -## AND finds the first falsy value +## AND encontra o primeiro valor falso -Given multiple AND'ed values: +Dado vários valores AND'ed: ```js result = value1 && value2 && value3; ``` -The AND `&&` operator does the following: +O operador AND `&&` 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 operandos da esquerda para a direita. +- Para cada operando, converte para um booleano. Se o resultado for `false`, parará e retornará o valor original desse operando. +- Se todos os operandos tiverem sido avaliados (isto é, todos foram 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 foi encontrado. -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 semelhantes a 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 operando for verdadeiro, +// AND retorna o segundo operando: 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 operando for falso, +// AND o retorna. E o segundo operando é ignorado alert( null && 5 ); // null alert( 0 && "no matter what" ); // 0 ``` -We can also pass several values in a row. See how the first falsy one is returned: +Nós também podemos passar vários valores em uma linha. 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 os valores são verdadeiros, o último valor é retornado: ```js run -alert( 1 && 2 && 3 ); // 3, the last one +alert( 1 && 2 && 3 ); // 3, o último ``` ````smart header="Precedence of AND `&&` is higher than OR `||`" -The precedence of AND `&&` operator is higher than OR `||`. +A precedência do AND `&&` operator é maior que OR `||`. -So the code `a && b || c && d` is essentially the same as if the `&&` expressions were in parentheses: `(a && b) || (c && d)`. +Então o código `a && b || c && d` é essencialmente o mesmo que se as expressões `&&` estivessem entre parênteses: `(a && b) || (c & d)`. ```` -Just like OR, the AND `&&` operator can sometimes replace `if`. +Assim como OR, o operador AND `&&` pode algumas vezes substituir `if`. -For instance: +Por exemplo: ```js run let x = 1; @@ -246,9 +246,9 @@ let x = 1; (x > 0) && alert( 'Greater than 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 de `&&` só seria executada se a avaliação alcançasse. Isto é, somente se `(x> 0)` for verdadeiro. -So we basically have an analogue for: +Então, basicamente, temos um análogo para: ```js run let x = 1; @@ -258,46 +258,46 @@ if (x > 0) { } ``` -The variant with `&&` appears shorter. But `if` is more obvious and tends to be a little bit more readable. +A variante com `&&` parece mais curta. Mas `if` é mais óbvio e tende a ser um pouco mais legível. -So we recommend using every construct for its purpose: use `if` if we want if and use `&&` if we want AND. +Por isso recomendamos usar cada constructo para o seu propósito: use `if` se quisermos usar if e usar `&&` se quisermos AND. ## ! (NOT) -The boolean NOT operator is represented with an exclamation sign `!`. +O operador booleano NOT é representado por um sinal de exclamação `!`. -The syntax is pretty simple: +A 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 em um tipo booleano: `true/false`. +2. Retorna o valor inverso. -For instance: +Por exemplo: ```js run -alert( !true ); // false -alert( !0 ); // true +alert( !true ); // falso +alert( !0 ); // verdadeiro ``` -A double NOT `!!` is sometimes used for converting a value to boolean type: +Um double NOT `!!` às vezes é usado para converter um valor em um tipo booleano: ```js run -alert( !!"non-empty string" ); // true -alert( !!null ); // false +alert( !!"non-empty string" ); // verdadeiro +alert( !!null ); // falso ``` -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 em booleano e retorna o inverso, e o segundo NÃO o inverte novamente. No final, temos uma conversão simples de valor em booleano. -There's a little more verbose way to do the same thing -- a built-in `Boolean` function: +Há uma maneira um pouco mais detalhada de fazer a mesma coisa -- uma função `Boolean` incorporada: ```js run -alert( Boolean("non-empty string") ); // true +alert( Boolean("non-empty string") ); // verdadeiro 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 de NOT `!` é o maior de todos os operadores lógicos, então ele sempre executa primeiro, antes de `&&` ou `||`. From 42feb24aa5007586c34e241708f12da7cf894282 Mon Sep 17 00:00:00 2001 From: "C@irx" Date: Thu, 6 Jun 2019 02:27:57 -0300 Subject: [PATCH 7/9] Translate tasks and solutions --- .../1-alert-null-2-undefined/solution.md | 2 +- .../1-alert-null-2-undefined/task.md | 4 ++-- .../2-alert-or/solution.md | 12 +++++------ .../11-logical-operators/2-alert-or/task.md | 4 ++-- .../3-alert-1-null-2/solution.md | 2 +- .../3-alert-1-null-2/task.md | 4 ++-- .../4-alert-and/solution.md | 6 +++--- .../11-logical-operators/4-alert-and/task.md | 4 ++-- .../5-alert-and-or/solution.md | 8 ++++---- .../5-alert-and-or/task.md | 4 ++-- .../6-check-if-in-range/task.md | 6 +++--- .../7-check-if-out-range/solution.md | 4 ++-- .../7-check-if-out-range/task.md | 6 +++--- .../8-if-question/solution.md | 20 +++++++++---------- .../8-if-question/task.md | 6 +++--- .../9-check-login/solution.md | 2 +- .../9-check-login/task.md | 20 +++++++++---------- 17 files changed, 57 insertions(+), 57 deletions(-) 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..adcee6265 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,4 +1,4 @@ -The answer is `2`, that's the first truthy value. +A resposta é "2", esse é 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..fbc927813 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,9 +2,9 @@ importance: 5 --- -# What's the result of OR? +# Qual é o resultado de OR? -What is the code below going to output? +Qual é a saída para o 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 8f4d664e8..3ccfde941 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`. +A chamada para `alert` não retorna um valor. Ou, em outras palavras, retorna `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 OR `||` avalia seu operando esquerdo `alert (1)`. Isso mostra a primeira mensagem com `1`. +2. O `alert` retorna `undefined`, então OR passa para o segundo operando procurando por um valor geral. +3. O segundo operando `2` é verdadeiro, então a execução é interrompida, `2` é retornado e então mostrado pelo alerta externo. -There will be no `3`, because the evaluation does not reach `alert(3)`. +Não haverá `3`, porque a avaliação não alcanç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..104485279 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,9 +2,9 @@ importance: 3 --- -# What's the result of OR'ed alerts? +# Qual é o resultado dos alertas OR? -What will the code below output? +Qual será 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 5c2455ef4..e7c96b5dd 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,4 +1,4 @@ -The answer: `null`, because it's the first falsy value from the list. +A resposta: `null`, porque é 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..f3f4b97ee 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,9 +2,9 @@ importance: 5 --- -# What is the result of AND? +# Qual é o resultado de AND? -What is this code going to show? +O que o código vai 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..aa55503ea 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,10 @@ -The answer: `1`, and then `undefined`. +A resposta: `1` e, em seguida, `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 para `alert` retorna `undefined` (apenas mostra uma mensagem, portanto não há 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, o `&&` avalia o operando da esquerda (mostra o `1`), e imediatamente para, porque `undefined` é um valor falso. E `&&` procura por um valor falso e o retorna, então está pronto. 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..61b19776d 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,9 +2,9 @@ importance: 3 --- -# What is the result of AND'ed alerts? +# Qual é o resultado dos alertas do AND? -What will this code show? +O que esse código 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..c3b41d97c 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,16 @@ -The answer: `3`. +A 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 `||`, portanto, é executada 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..727e807b4 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,9 +2,9 @@ importance: 5 --- -# The result of OR AND OR +# O resultado de OR E 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/task.md b/1-js/02-first-steps/11-logical-operators/6-check-if-in-range/task.md index cc00ca9fc..66d9e0016 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' esta entre `14` e` 90` inclusive. -"Inclusively" means that `age` can reach the edges `14` or `90`. +"Inclusivamente" significa que "idade" pode atingir as arestas "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..689def986 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,10 +1,10 @@ -The first variant: +A primeira variante: ```js if (!(age >= 14 && age <= 90)) ``` -The second variant: +A segunda variante: ```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 7c22d6ad1..f8f0c2e26 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 intervalo fora -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 esta entre 14 e 90, inclusive. -Create two variants: the first one using NOT `!`, the second one -- without it. +Crie duas variantes: a primeira usando NOT `!`, A segunda -- sem ela. \ No newline at end of file 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..17e3fee3d 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,20 @@ -The answer: the first and the third will execute. +A resposta: o primeiro e o terceiro serão executados. -Details: +Detalhes: ```js run -// Runs. -// The result of -1 || 0 = -1, truthy +// Corre. +// O resultado de -1 || 0 = -1, verdadeiro if (-1 || 0) alert( 'first' ); -// Doesn't run -// -1 && 0 = 0, falsy +// Não corre +// -1 && 0 = 0, falso if (-1 && 0) alert( 'second' ); -// Executes -// Operator && has a higher precedence than || -// so -1 && 1 executes first, giving us the chain: -// null || -1 && 1 -> null || 1 -> 1 +// Executa +// Operador && tem uma precedência maior que || +// então -1 && 1 executa primeiro, nos dando a cadeia: +// null || -1 && 1 -> null || 1 -> 1 if (null || -1 && 1) alert( 'third' ); ``` 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..5dc6d748b 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,11 +2,11 @@ importance: 5 --- -# A question about "if" +# Uma pergunta sobre "if" -Which of these `alert`s are going to execute? +Quais destes `alert`s serão executados? -What will the results of the expressions be inside `if(...)`? +Quais serão os resultados das expressões dentro de `if (...)`? ```js if (-1 || 0) alert( 'first' ); 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 b535650ec..82cbeeaa5 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 @@ -22,4 +22,4 @@ if (userName == 'Admin') { } ``` -Note the vertical indents inside the `if` blocks. They are technically not required, but make the code more readable. +Observe os recuos verticais dentro dos blocos `if`. Eles não são tecnicamente necessários, 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 780e674a9..90809dd1e 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 pede um login com o `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 inserir `"Admin"`, então `prompt` para uma senha, se a entrada for uma linha vazia ou `key: Esc` -- mostre "Canceled.", Se for outra string - então mostre "eu don conheço você ". -The password is checked as follows: +A senha é verificada 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 "Welcome!", +- Outra string - mostra "Senha incorreta", +- Para uma sequência vazia ou entrada cancelada, mostre "Cancelado". -The schema: +O esquema: ![](ifelse_task.png) -Please use nested `if` blocks. Mind the overall readability of the code. +Por favor use blocos `if` aninhados. Observe a legibilidade geral 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 `''`. Pressionando a `key:ESC` durante um prompt retorna `null`. [demo] From ea8ae846df98471affe0e462ed044a7cf728e989 Mon Sep 17 00:00:00 2001 From: "C@irx" Date: Thu, 6 Jun 2019 13:49:09 -0300 Subject: [PATCH 8/9] updae --- .../07-operators/1-increment-order/solution.md | 2 +- 1-js/02-first-steps/08-comparison/article.md | 2 +- 1-js/02-first-steps/11-logical-operators/article.md | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/1-js/02-first-steps/07-operators/1-increment-order/solution.md b/1-js/02-first-steps/07-operators/1-increment-order/solution.md index 27669c4ac..2c36d1931 100644 --- a/1-js/02-first-steps/07-operators/1-increment-order/solution.md +++ b/1-js/02-first-steps/07-operators/1-increment-order/solution.md @@ -10,7 +10,7 @@ A resposta é: let a = 1, b = 1; alert( ++a ); // 2, a forma prefixo retorna o novo valor -alert( b++ ); // 1, a forma sufijo retorna o valor antigo +alert( b++ ); // 1, a forma sufixo retorna o valor antigo alert( a ); // 2, incrementado uma vez alert( b ); // 2, incrementado uma vez diff --git a/1-js/02-first-steps/08-comparison/article.md b/1-js/02-first-steps/08-comparison/article.md index 1bde52969..91f6b88f5 100644 --- a/1-js/02-first-steps/08-comparison/article.md +++ b/1-js/02-first-steps/08-comparison/article.md @@ -31,7 +31,7 @@ alert( result ); // true ## Comparação de strings -Para ver se uma string é maior que outra, o JavaScript usa o chamado ordem "dicionário" ou "lexicográfico". +Para ver se uma string é maior que outra, o JavaScript usa o chamada ordem "dicionário" ou "lexicográfica". Em outras palavras, as strings são comparadas letra a letra. 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 072c1e9aa..a26129c10 100644 --- a/1-js/02-first-steps/11-logical-operators/article.md +++ b/1-js/02-first-steps/11-logical-operators/article.md @@ -39,7 +39,7 @@ if (1 || 0) { // funciona como se( verdadeiro || falso ) } ``` -Na maior parte do tempo, OR `||` é usado em uma instrução `if` para testar se *any* das condições dadas é `true`. +Na maior parte do tempo, OR `||` é usado em uma instrução `if` para testar se *qualquer* das condições dadas é `true`. Por exemplo: @@ -147,7 +147,7 @@ Isso leva a um uso interessante em comparação com uma "OR pura, clássica, ape Como podemos ver, tal caso de uso é um "modo mais curto de fazer `if`". O primeiro operando é convertido em booleano. Se é falso, o segundo é avaliado. - Na maioria das vezes, é melhor usar um "regular" `if` para manter o código fácil de entender, mas às vezes isso pode ser útil. + Na maioria das vezes, é melhor usar um `if` "regular" para manter o código fácil de entender, mas às vezes isso pode ser útil. ## && (AND) @@ -231,7 +231,7 @@ alert( 1 && 2 && 3 ); // 3, o último ``` ````smart header="Precedence of AND `&&` is higher than OR `||`" -A precedência do AND `&&` operator é maior que OR `||`. +A precedência do operador AND `&&` é maior que OR `||`. Então o código `a && b || c && d` é essencialmente o mesmo que se as expressões `&&` estivessem entre parênteses: `(a && b) || (c & d)`. ```` @@ -284,7 +284,7 @@ alert( !true ); // falso alert( !0 ); // verdadeiro ``` -Um double NOT `!!` às vezes é usado para converter um valor em um tipo booleano: +Um duplo NOT `!!` às vezes é usado para converter um valor em um tipo booleano: ```js run alert( !!"non-empty string" ); // verdadeiro From 3d04877bd6e926f906466e624d9f83909e75cf3f Mon Sep 17 00:00:00 2001 From: "C@irx" Date: Thu, 6 Jun 2019 13:55:41 -0300 Subject: [PATCH 9/9] update translate --- .../07-operators/1-increment-order/solution.md | 2 +- 1-js/02-first-steps/08-comparison/article.md | 2 +- 1-js/02-first-steps/11-logical-operators/article.md | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/1-js/02-first-steps/07-operators/1-increment-order/solution.md b/1-js/02-first-steps/07-operators/1-increment-order/solution.md index 2c36d1931..27669c4ac 100644 --- a/1-js/02-first-steps/07-operators/1-increment-order/solution.md +++ b/1-js/02-first-steps/07-operators/1-increment-order/solution.md @@ -10,7 +10,7 @@ A resposta é: let a = 1, b = 1; alert( ++a ); // 2, a forma prefixo retorna o novo valor -alert( b++ ); // 1, a forma sufixo retorna o valor antigo +alert( b++ ); // 1, a forma sufijo retorna o valor antigo alert( a ); // 2, incrementado uma vez alert( b ); // 2, incrementado uma vez diff --git a/1-js/02-first-steps/08-comparison/article.md b/1-js/02-first-steps/08-comparison/article.md index 91f6b88f5..1bde52969 100644 --- a/1-js/02-first-steps/08-comparison/article.md +++ b/1-js/02-first-steps/08-comparison/article.md @@ -31,7 +31,7 @@ alert( result ); // true ## Comparação de strings -Para ver se uma string é maior que outra, o JavaScript usa o chamada ordem "dicionário" ou "lexicográfica". +Para ver se uma string é maior que outra, o JavaScript usa o chamado ordem "dicionário" ou "lexicográfico". Em outras palavras, as strings são comparadas letra a letra. 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 a26129c10..072c1e9aa 100644 --- a/1-js/02-first-steps/11-logical-operators/article.md +++ b/1-js/02-first-steps/11-logical-operators/article.md @@ -39,7 +39,7 @@ if (1 || 0) { // funciona como se( verdadeiro || falso ) } ``` -Na maior parte do tempo, OR `||` é usado em uma instrução `if` para testar se *qualquer* das condições dadas é `true`. +Na maior parte do tempo, OR `||` é usado em uma instrução `if` para testar se *any* das condições dadas é `true`. Por exemplo: @@ -147,7 +147,7 @@ Isso leva a um uso interessante em comparação com uma "OR pura, clássica, ape Como podemos ver, tal caso de uso é um "modo mais curto de fazer `if`". O primeiro operando é convertido em booleano. Se é falso, o segundo é avaliado. - Na maioria das vezes, é melhor usar um `if` "regular" para manter o código fácil de entender, mas às vezes isso pode ser útil. + Na maioria das vezes, é melhor usar um "regular" `if` para manter o código fácil de entender, mas às vezes isso pode ser útil. ## && (AND) @@ -231,7 +231,7 @@ alert( 1 && 2 && 3 ); // 3, o último ``` ````smart header="Precedence of AND `&&` is higher than OR `||`" -A precedência do operador AND `&&` é maior que OR `||`. +A precedência do AND `&&` operator é maior que OR `||`. Então o código `a && b || c && d` é essencialmente o mesmo que se as expressões `&&` estivessem entre parênteses: `(a && b) || (c & d)`. ```` @@ -284,7 +284,7 @@ alert( !true ); // falso alert( !0 ); // verdadeiro ``` -Um duplo NOT `!!` às vezes é usado para converter um valor em um tipo booleano: +Um double NOT `!!` às vezes é usado para converter um valor em um tipo booleano: ```js run alert( !!"non-empty string" ); // verdadeiro