Skip to content

Commit e4c7754

Browse files
Comparisons
Comparisons by @jonnathan-ls
2 parents 769acd2 + a6fd6a8 commit e4c7754

File tree

2 files changed

+100
-100
lines changed

2 files changed

+100
-100
lines changed

1-js/02-first-steps/09-comparison/1-comparison-questions/solution.md

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,20 @@
22

33
```js no-beautify
44
5 > 4true
5-
"apple" > "pineapple"false
5+
"maça" > "abacaxi"true
66
"2" > "12"true
77
undefined == nulltrue
88
undefined === nullfalse
99
null == "\n0\n"false
1010
null === +"\n0\n"false
1111
```
1212

13-
Some of the reasons:
13+
Alguns dos motivos:
1414

15-
1. Obviously, true.
16-
2. Dictionary comparison, hence false. `"a"` is smaller than `"p"`.
17-
3. Again, dictionary comparison, first char `"2"` is greater than the first char `"1"`.
18-
4. Values `null` and `undefined` equal each other only.
19-
5. Strict equality is strict. Different types from both sides lead to false.
20-
6. Similar to `(4)`, `null` only equals `undefined`.
21-
7. Strict equality of different types.
15+
1. Obviamente, verdadeiro.
16+
2. Comparação de dicionário, portanto, verdadeiro. `"m"` é maior que `"a"`.
17+
3. Novamente, comparação de dicionário, primeiro caractere `"2"` é maior que o primeiro caractere `"1"`.
18+
4. Os valores `null` e `undefined` são iguais apenas entre si.
19+
5. Igualdade estrita é estrita. Diferentes tipos de ambos os lados levam a falso.
20+
6. Semelhante no `(4)`, `null` só é igual a `undefined`.
21+
7. Igualdade estrita de diferentes tipos.
Lines changed: 91 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -1,103 +1,103 @@
1-
# Comparisons
1+
# Comparações
22

3-
We know many comparison operators from maths.
3+
Conhecemos muitos operadores de comparação de matemática:
44

5-
In JavaScript they are written like this:
5+
Em JavaScript eles são escritos assim:
66

7-
- Greater/less than: <code>a &gt; b</code>, <code>a &lt; b</code>.
8-
- Greater/less than or equals: <code>a &gt;= b</code>, <code>a &lt;= b</code>.
9-
- Equals: `a == b`, please note the double equality sign `==` means the equality test, while a single one `a = b` means an assignment.
10-
- Not equals: In maths the notation is <code>&ne;</code>, but in JavaScript it's written as <code>a != b</code>.
7+
- Maior/menor que: <code>a &gt; b</code>, <code>a &lt; b</code>.
8+
- Maior/menor ou igual: <code>a &gt;= b</code>, <code>a &lt;= b</code>.
9+
- Igual: `a == b`, observe o sinal de igualdade duplo `==` significa o teste de igualdade, enquanto um único `a = b` significa uma atribuição.
10+
- Diferente: Em matemática a notação é <code>&ne;</code>, mas em JavaScript é escrita como <code>a != b</code>.
1111

12-
In this article we'll learn more about different types of comparisons, how JavaScript makes them, including important peculiarities.
12+
Neste artigo vamos aprender mais sobre diferentes tipos de comparações, como o JavaScript as processa, incluindo peculiaridades importantes.
1313

14-
At the end you'll find a good recipe to avoid "JavaScript quirks"-related issues.
14+
No final, você encontrará uma boa receita para evitar problemas relacionados a "peculiaridades do JavaScript".
1515

16-
## Boolean is the result
16+
## Booleano é o resultado
1717

18-
All comparison operators return a boolean value:
18+
Todos os operadores de comparação retornam um valor booleano:
1919

20-
- `true` -- means "yes", "correct" or "the truth".
21-
- `false` -- means "no", "wrong" or "not the truth".
20+
- `true` -- significa "sim", "correto" ou "verdadeiro".
21+
- `false` -- significa "não", "errado" ou "falso".
2222

23-
For example:
23+
Por exemplo:
2424

2525
```js run
26-
alert( 2 > 1 ); // true (correct)
27-
alert( 2 == 1 ); // false (wrong)
28-
alert( 2 != 1 ); // true (correct)
26+
alert( 2 > 1 ); // true (verdadeiro)
27+
alert( 2 == 1 ); // false (falso)
28+
alert( 2 != 1 ); // true (verdadeiro)
2929
```
3030

31-
A comparison result can be assigned to a variable, just like any value:
31+
Um resultado de comparação pode ser atribuído a uma variável, exatamente como qualquer valor:
3232

3333
```js run
34-
let result = 5 > 4; // assign the result of the comparison
34+
let result = 5 > 4; // atribui o resultado da comparação
3535
alert( result ); // true
3636
```
3737

38-
## String comparison
38+
## Comparação de strings
3939

40-
To see whether a string is greater than another, JavaScript uses the so-called "dictionary" or "lexicographical" order.
40+
Para ver se uma string é maior que outra, o JavaScript usa a chamada ordem "dicionário" ou "lexicográfica".
4141

42-
In other words, strings are compared letter-by-letter.
42+
Em outras palavras, as strings são comparadas letra a letra.
4343

44-
For example:
44+
Por exemplo:
4545

4646
```js run
4747
alert( 'Z' > 'A' ); // true
4848
alert( 'Glow' > 'Glee' ); // true
4949
alert( 'Bee' > 'Be' ); // true
5050
```
5151

52-
The algorithm to compare two strings is simple:
52+
O algoritmo para comparar duas strings é simples:
5353

54-
1. Compare the first character of both strings.
55-
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.
56-
3. Otherwise, if both strings' first characters are the same, compare the second characters the same way.
57-
4. Repeat until the end of either string.
58-
5. If both strings end at the same length, then they are equal. Otherwise, the longer string is greater.
54+
1. Compare o primeiro caractere de ambas as strings.
55+
2. Se o primeiro caractere da primeira string for maior (ou menor) que o da outra string, então a primeira string será maior (ou menor) que a segunda e a operação será concluída.
56+
3. Caso contrário, se os primeiros caracteres de ambas as strings forem iguais, compare os segundos caracteres da mesma maneira.
57+
4. Repita até o final de uma das strings.
58+
5. Se ambas as strings terminarem com o mesmo comprimento, elas serão iguais. Caso contrário, a string mais longa é maior.
5959

60-
In the first example above, the comparison `'Z' > 'A'` gets to a result at the first step.
60+
No primeiro exemplo acima, a comparação `'Z' > 'A'` obtém um resultado na primeira etapa.
6161

62-
The second comparison `'Glow'` and `'Glee'` needs more steps as strings are compared character-by-character:
62+
A segunda comparação `'Glow'` e `'Glee'` precisa de mais etapas, pois as strings são comparadas caractere por caractere:
6363

64-
1. `G` is the same as `G`.
65-
2. `l` is the same as `l`.
66-
3. `o` is greater than `e`. Stop here. The first string is greater.
64+
1. `G` é o mesmo que `G`.
65+
2. `l` é o mesmo que `l`.
66+
3. `o` é maior que `e`. Pare aqui. A primeira string é maior.
6767

68-
```smart header="Not a real dictionary, but Unicode order"
69-
The comparison algorithm given above is roughly equivalent to the one used in dictionaries or phone books, but it's not exactly the same.
68+
```smart header="Não é um dicionário real, mas ordem Unicode"
69+
O algoritmo de comparação fornecido acima é aproximadamente equivalente ao usado em dicionários ou listas telefônicas, mas não é exatamente o mesmo.
7070
71-
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 <info:string>.
71+
Por exemplo, um caso relevante. Uma letra maiúscula `"A"` não é igual à letra minúscula `"a"`. Qual é maior? A letra minúscula `"a"`. 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 consequências disso no capítulo <info:string>.
7272
```
7373

74-
## Comparison of different types
74+
## Comparação de diferentes tipos
7575

76-
When comparing values of different types, JavaScript converts the values to numbers.
76+
Quando comparado valores de tipos diferentes, o JavaScript converte os valores em números.
7777

78-
For example:
78+
Por exemplo:
7979

8080
```js run
81-
alert( '2' > 1 ); // true, string '2' becomes a number 2
82-
alert( '01' == 1 ); // true, string '01' becomes a number 1
81+
alert( '2' > 1 ); // true, string '2' se torna no número 2
82+
alert( '01' == 1 ); // true, string '01' se torna no número 1
8383
```
8484

85-
For boolean values, `true` becomes `1` and `false` becomes `0`.
85+
Para valores booleanos, `true` torna-se `1` e `false` torna-se `0`.
8686

87-
For example:
87+
Por exemplo:
8888

8989
```js run
9090
alert( true == 1 ); // true
9191
alert( false == 0 ); // true
9292
```
9393

94-
````smart header="A funny consequence"
95-
It is possible that at the same time:
94+
````smart header="Uma consequência engraçada"
95+
É possível que ao mesmo tempo:
9696
97-
- Two values are equal.
98-
- One of them is `true` as a boolean and the other one is `false` as a boolean.
97+
- Dois valores são iguais.
98+
- Um deles é `true` como booleano e o outro é `falso` como booleano.
9999
100-
For example:
100+
Por exemplo:
101101
102102
```js run
103103
let a = 0;
@@ -109,108 +109,108 @@ alert( Boolean(b) ); // true
109109
alert(a == b); // true!
110110
```
111111
112-
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.
112+
Do ponto de vista do JavaScript, esse resultado é bastante normal. Uma verificação de igualdade converte valores usando a conversão numérica (portanto, `"0"` se torna `0`), enquanto a conversão `Boolean` explícita usa outro conjunto de regras.
113113
````
114114

115-
## Strict equality
115+
## Igualdade estrita
116116

117-
A regular equality check `==` has a problem. It cannot differentiate `0` from `false`:
117+
Uma verificação de igualdade regular `==` tem um problema. Ela não pode diferenciar `0` de `false`:
118118

119119
```js run
120120
alert( 0 == false ); // true
121121
```
122122

123-
The same thing happens with an empty string:
123+
A mesma coisa acontece com uma string vazia:
124124

125125
```js run
126126
alert( '' == false ); // true
127127
```
128128

129-
This happens because operands of different types are converted to numbers by the equality operator `==`. An empty string, just like `false`, becomes a zero.
129+
Isso acontece porque operandos de tipos diferentes são convertidos em números pelo operador de igualdade `==`. Uma string vazia, assim como `false`, torna-se em um zero.
130130

131-
What to do if we'd like to differentiate `0` from `false`?
131+
O que fazer se quisermos diferenciar `0` de `false`?
132132

133-
**A strict equality operator `===` checks the equality without type conversion.**
133+
**Um operador de igualdade estrita `===` verifica a igualdade sem conversão de tipo.**
134134

135-
In other words, if `a` and `b` are of different types, then `a === b` immediately returns `false` without an attempt to convert them.
135+
Em outras palavras, se `a` e `b` forem de tipos diferentes, então `a === b` retornará imediatamente `false` sem tentar convertê-los.
136136

137-
Let's try it:
137+
Vamos tentar:
138138

139139
```js run
140-
alert( 0 === false ); // false, because the types are different
140+
alert( 0 === false ); // false, porque os tipos são diferentes
141141
```
142142

143-
There is also a "strict non-equality" operator `!==` analogous to `!=`.
143+
Há também um operador de "desigualdade estrita" `!==` análogo a `!=`.
144144

145-
The strict equality operator is a bit longer to write, but makes it obvious what's going on and leaves less room for errors.
145+
O operador de igualdade estrita é um pouco mais longo para escrever, mas torna óbvio o que está acontecendo e deixa menos espaço para erros.
146146

147-
## Comparison with null and undefined
147+
## Comparação com null e undefined
148148

149-
There's a non-intuitive behavior when `null` or `undefined` are compared to other values.
149+
Há um comportamento não intuitivo quando `null` ou `undefined` são comparados a outros valores.
150150

151-
For a strict equality check `===`
152-
: These values are different, because each of them is a different type.
151+
Para uma verificação de igualdade estrita `===`
152+
: Esses valores diferem, porque cada um deles é de um tipo diferente.
153153

154154
```js run
155155
alert( null === undefined ); // false
156156
```
157157

158-
For a non-strict check `==`
159-
: There's a special rule. These two are a "sweet couple": they equal each other (in the sense of `==`), but not any other value.
158+
Para uma verificação não estrita `==`
159+
: Há uma regra especial. Esses dois são um "casal doce": eles se igualam (no sentido de `==`), mas não a qualquer outro valor.
160160

161161
```js run
162162
alert( null == undefined ); // true
163163
```
164164

165-
For maths and other comparisons `< > <= >=`
166-
: `null/undefined` are converted to numbers: `null` becomes `0`, while `undefined` becomes `NaN`.
165+
Para matemática e outras comparações `< > <= >=`
166+
: `null/undefined` são convertidos em números: `null` torna-se `0`, enquanto `undefined` torna-se `NaN`.
167167

168-
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.
168+
Agora vamos ver algumas coisas engraçadas que acontecem quando aplicamos essas regras. E, o que é mais importante, como não cair numa armadilha com eles.: Esses valores diferem, porque cada um deles é de um tipo diferente.
169169

170-
### Strange result: null vs 0
170+
### Resultado estranho: null vs 0
171171

172-
Let's compare `null` with a zero:
172+
Vamos comparar `null` com zero:
173173

174174
```js run
175175
alert( null > 0 ); // (1) false
176176
alert( null == 0 ); // (2) false
177177
alert( null >= 0 ); // (3) *!*true*/!*
178178
```
179179

180-
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.
180+
Matematicamente, isso é estranho. O último resultado afirma que "`null` é maior ou igual a zero", então em uma das comparações acima deve ser `true`, mas ambos são falsos.
181181

182-
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.
182+
A razão é que uma verificação de igualdade `==` e comparações `> < >= <=` funcionam de forma diferente. As comparações convertem `null` em um número, tratando-o como `0`. É por isso que (3) `null >= 0` é verdadeiro e (1) `null > 0` é falso.
183183

184-
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.
184+
Por outro lado, a verificação de igualdade `==` para `undefined` e `null` é definida de tal forma que, sem nenhuma conversão, eles são iguais entre si, e não são iguais a mais nada. É por isso que (2) `null == 0` é falso.
185185

186-
### An incomparable undefined
186+
### Um incomparável "undefined"
187187

188-
The value `undefined` shouldn't be compared to other values:
188+
O valor `undefined` (indefinido) não deve ser comparado a outros valores:
189189

190190
```js run
191191
alert( undefined > 0 ); // false (1)
192192
alert( undefined < 0 ); // false (2)
193193
alert( undefined == 0 ); // false (3)
194194
```
195195

196-
Why does it dislike zero so much? Always false!
196+
Por que não gostam do zero? Sempre falso!
197197

198-
We get these results because:
198+
Obtemos esses resultados porque:
199199

200-
- 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.
201-
- The equality check `(3)` returns `false` because `undefined` only equals `null`, `undefined`, and no other value.
200+
- Comparações `(1)` e `(2)` retornam `false` porque `undefined` é convertido em `NaN`, e `NaN` é um valor numérico especial que retorna `false` para todas as comparações.
201+
- A verificação de igualdade `(3)` retorna `false` porque `undefined` só é igual a `null`, `undefined` e nenhum outro valor.
202202

203-
### Avoid problems
203+
### Evite problemas
204204

205-
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 avoid problems with them:
205+
Por que examinamos esses exemplos? Devemos nos lembrar dessas peculiaridades o tempo todo? Bem, na verdade, não. Essas coisas complicadas gradualmente se tornarão familiares com o tempo, mas há uma maneira sólida de evitar problemas com elas:
206206

207-
- Treat any comparison with `undefined/null` except the strict equality `===` with exceptional care.
208-
- 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.
207+
- Trate qualquer comparação com `undefined/null` exceto a igualdade estrita `===` com cuidado excepcional.
208+
- Não use comparações `>= > < <=` com uma variável que pode ser `null/undefined`, a menos que você tenha a certeza do que está fazendo. Se uma variável tiver `null` ou `undefined`, verifique-os separadamente.
209209

210-
## Summary
210+
## Resumo
211211

212-
- Comparison operators return a boolean value.
213-
- Strings are compared letter-by-letter in the "dictionary" order.
214-
- When values of different types are compared, they get converted to numbers (with the exclusion of a strict equality check).
215-
- The values `null` and `undefined` equal `==` each other and do not equal any other value.
216-
- Be careful when using comparisons like `>` or `<` with variables that can occasionally be `null/undefined`. Checking for `null/undefined` separately is a good idea.
212+
- Os operadores de comparação retornam um valor booleano.
213+
- As strings são comparadas letra a letra na ordem do "dicionário".
214+
- Quando valores de tipos diferentes são comparados, eles são convertidos em números (com a exclusão de uma verificação de igualdade estrita).
215+
- Os valores `null` e `undefined` são iguais `==` entre si e não são iguais a nenhum outro valor.
216+
- Tenha cuidado ao usar comparações, como `>` ou `<`, com variáveis ​​que possam ocasionalmente ser `null/undefined`. Verificar por `null/undefined` separadamente é uma boa ideia.

0 commit comments

Comments
 (0)