You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
-Greater/less than or equals: <code>a >= b</code>, <code>a <= b</code>.
7
-
-Equals: `a == b` (please note the double equals sign`=`. A single symbol `a = b`would mean an assignment).
8
-
-Not equals. In maths the notation is <code>≠</code>, but in JavaScript it's written as an assignment with an exclamation sign before it: <code>a != b</code>.
-Maior/menor ou igual que: <code>a >= b</code>, <code>a <= b</code>.
7
+
-Igual: `a == b` (observe o sinal de igual duplo`=`. Um único sinal de igual `a = b`significaria uma atribuição).
8
+
-Diferente. Em matemática, a notação é <code>≠</code>, mas em JavaScript é escrita como uma atribuição com um sinal de exclamação antes: <code>a != b</code>.
9
9
10
-
## Boolean is the result
10
+
## Booleano é o resultado
11
11
12
-
Like all other operators, a comparison returns a value. In this case, the value is a boolean.
12
+
Como todos os outros operadores, uma comparação retorna um valor. Nesse caso, o valor é um booleano.
13
13
14
-
-`true` -- means "yes", "correct" or "the truth".
15
-
-`false` -- means "no", "wrong" or "not the truth".
14
+
-`true` -- significa "sim", "correto" ou "verdade".
15
+
-`false` -- significa "não", "errado" ou "falso".
16
16
17
-
For example:
17
+
Por exemplo:
18
18
19
19
```js run
20
20
alert( 2>1 ); // true (correct)
21
21
alert( 2==1 ); // false (wrong)
22
22
alert( 2!=1 ); // true (correct)
23
23
```
24
24
25
-
A comparison result can be assigned to a variable, just like any value:
25
+
Um resultado de comparação pode ser atribuído a uma variável, assim como qualquer valor:
26
26
27
27
```js run
28
28
let result =5>4; // assign the result of the comparison
29
29
alert( result ); // true
30
30
```
31
31
32
-
## String comparison
32
+
## Comparação de strings
33
33
34
-
To see whether a string is greater than another, JavaScript uses the so-called "dictionary" or "lexicographical" order.
34
+
Para ver se uma string é maior que outra, o JavaScript usa o chamado ordem "dicionário" ou "lexicográfico".
35
35
36
-
In other words, strings are compared letter-by-letter.
36
+
Em outras palavras, as strings são comparadas letra a letra.
37
37
38
-
For example:
38
+
Por exemplo:
39
39
40
40
```js run
41
41
alert( 'Z'>'A' ); // true
42
42
alert( 'Glow'>'Glee' ); // true
43
43
alert( 'Bee'>'Be' ); // true
44
44
```
45
45
46
-
The algorithm to compare two strings is simple:
46
+
O algoritmo para comparar duas strings é simples:
47
47
48
-
1. Compare the first character of both strings.
49
-
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.
50
-
3.Otherwise, if both strings' first characters are the same, compare the second characters the same way.
51
-
4.Repeat until the end of either string.
52
-
5.If both strings end at the same length, then they are equal. Otherwise, the longer string is greater.
48
+
1. Compare o primeiro caractere de ambas as strings.
49
+
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
50
+
3.Caso contrário, se os primeiros caracteres das duas sequências forem os mesmos, compare os segundos caracteres da mesma maneira.
51
+
4.Repita até o final de qualquer string.
52
+
5.Se ambas as seqüências terminarem no mesmo comprimento, elas serão iguais. Caso contrário, a string mais longa é maior.
53
53
54
-
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:
54
+
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:
55
55
56
-
1.`G`is the same as`G`.
57
-
2.`l`is the same as`l`.
58
-
3.`o`is greater than`e`. Stop here. The first string is greater.
56
+
1.`G`é o mesmo que`G`.
57
+
2.`l`é o mesmo que`l`.
58
+
3.`o`é maior que`e`. Pare aqui. A primeira string é maior.
59
59
60
60
```smart header="Not a real dictionary, but Unicode order"
61
-
The comparison algorithm given above is roughly equivalent to the one used in dictionaries or phone books, but it's not exactly the same.
61
+
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.
62
62
63
-
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>.
63
+
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 <info:string>.
64
64
```
65
65
66
-
## Comparison of different types
66
+
## Comparação de diferentes tipos
67
67
68
-
When comparing values of different types, JavaScript converts the values to numbers.
68
+
Ao comparar valores de diferentes tipos, o JavaScript converte os valores em números.
69
69
70
-
For example:
70
+
Por exemplo:
71
71
72
72
```js run
73
73
alert( '2'>1 ); // true, string '2' becomes a number 2
74
74
alert( '01'==1 ); // true, string '01' becomes a number 1
75
75
```
76
76
77
-
For boolean values, `true`becomes `1`and`false`becomes `0`.
77
+
Para valores booleanos, `true`torna-se`1`e`false`torna-se`0`.
78
78
79
-
For example:
79
+
Por exemplo:
80
80
81
81
```js run
82
82
alert( true==1 ); // true
83
83
alert( false==0 ); // true
84
84
```
85
85
86
86
````smart header="A funny consequence"
87
-
It is possible that at the same time:
87
+
É possível que ao mesmo tempo:
88
88
89
-
- Two values are equal.
90
-
- One of them is `true` as a boolean and the other one is `false` as a boolean.
89
+
- Dois valores são iguais.
90
+
- Um deles é `true` como booleano e o outro é` false` como booleano.
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.
104
+
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.
105
105
````
106
106
107
-
## Strict equality
107
+
## Igualdade estrita
108
108
109
-
A regular equality check `==`has a problem. It cannot differentiate `0`from `false`:
109
+
Uma verificação de igualdade regular `==`tem um problema. Não é possível diferenciar `0`de`false`:
110
110
111
111
```js run
112
112
alert( 0==false ); // true
113
113
```
114
114
115
-
The same thing happens with an empty string:
115
+
A mesma coisa acontece com uma string vazia:
116
116
117
117
```js run
118
118
alert( ''==false ); // true
119
119
```
120
120
121
-
This happens because operands of different types are converted to numbers by the equality operator`==`. An empty string, just like`false`, becomes a zero.
121
+
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.
122
122
123
-
What to do if we'd like to differentiate `0`from `false`?
123
+
O que fazer se quisermos diferenciar `0`de`false`?
124
124
125
-
**A strict equality operator `===`checks the equality without type conversion.**
125
+
**Um operador de igualdade estrito `===`verifica a igualdade sem conversão de tipo.**
126
126
127
-
In other words, if`a`and`b`are of different types, then`a === b`immediately returns`false`without an attempt to convert them.
127
+
Em outras palavras, se`a`e`b`forem de tipos diferentes, então`a === b`retornará imediatamente`false`sem uma tentativa de convertê-los.
128
128
129
-
Let's try it:
129
+
Vamos tentar:
130
130
131
131
```js run
132
132
alert( 0===false ); // false, because the types are different
133
133
```
134
134
135
-
There is also a "strict non-equality" operator `!==`analogous to`!=`.
135
+
Existe também um operador "diferença estrita" `!==`análogo a`!=`.
136
136
137
-
The strict equality operator is a bit longer to write, but makes it obvious what's going on and leaves less room for errors.
137
+
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.
138
138
139
-
## Comparison with null and undefined
139
+
## Comparação com "null" e "undefined"
140
140
141
-
Let's see more edge cases.
141
+
Vamos ver mais casos extremos.
142
142
143
-
There's a non-intuitive behavior when `null`or `undefined`are compared to other values.
143
+
Existe um comportamento não intuitivo quando `null`ou`undefined`são comparados com outros valores.
144
144
145
145
146
-
For a strict equality check `===`
147
-
: These values are different, because each of them is a different type.
146
+
Para uma verificação de igualdade estrita `===` : Esses valores são diferentes, porque cada um deles é um tipo diferente.
148
147
149
148
```js run
150
149
alert( null === undefined ); // false
151
150
```
152
151
153
-
For a non-strict check `==`
154
-
: There's a special rule. These two are a "sweet couple": they equal each other (in the sense of `==`), but not any other value.
152
+
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.
155
153
156
154
```js run
157
155
alert( null == undefined ); // true
158
156
```
159
157
160
-
For maths and other comparisons `< > <= >=`
161
-
: `null/undefined` are converted to numbers: `null` becomes `0`, while `undefined` becomes `NaN`.
158
+
Para matemática e outras comparações `<> <=> =` : `null/undefined` são convertidos em números: `null` torna-se `0`, enquanto `undefined` torna-se `NaN`.
162
159
163
-
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.
160
+
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.
164
161
165
-
### Strange result: null vs 0
162
+
### Resultado estranho: "null" vs "0"
166
163
167
-
Let's compare`null`with a zero:
164
+
Vamos comparar`null`com um zero:
168
165
169
166
```js run
170
167
alert( null>0 ); // (1) false
171
168
alert( null==0 ); // (2) false
172
169
alert( null>=0 ); // (3) *!*true*/!*
173
170
```
174
171
175
-
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.
172
+
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.
176
173
177
-
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.
174
+
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.
178
175
179
-
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.
176
+
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.
180
177
181
-
### An incomparable undefined
178
+
### Um incomparável "undefined"
182
179
183
-
The value`undefined`shouldn't be compared to other values:
180
+
O valor`undefined`não deve ser comparado a outros valores:
184
181
185
182
```js run
186
183
alert( undefined>0 ); // false (1)
187
184
alert( undefined<0 ); // false (2)
188
185
alert( undefined==0 ); // false (3)
189
186
```
190
187
191
-
Why does it dislike zero so much? Always false!
188
+
Por que não gostam do zero? Sempre falso!
192
189
193
-
We get these results because:
190
+
Obtemos estes resultados porque:
194
191
195
-
-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.
196
-
-The equality check `(3)`returns`false`because `undefined`only equals `null`and no other value.
192
+
-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.
193
+
-A verificação de igualdade `(3)`retorna`false`porque`undefined`somente é igual a `null`e nenhum outro valor.
197
194
198
-
### Evade problems
195
+
### Evitar problemas
199
196
200
-
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:
197
+
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:
201
198
202
-
Just treat any comparison with`undefined/null`except the strict equality `===` with exceptional care.
199
+
Apenas trate qualquer comparação com`undefined / null`exceto a igualdade estrita `===` com cuidado excepcional.
203
200
204
-
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.
201
+
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.
205
202
206
-
## Summary
203
+
## Resumo
207
204
208
-
-Comparison operators return a boolean value.
209
-
-Strings are compared letter-by-letter in the "dictionary" order.
210
-
-When values of different types are compared, they get converted to numbers (with the exclusion of a strict equality check).
211
-
-The values`null`and `undefined`equal`==`each other and do not equal any other value.
212
-
-Be careful when using comparisons like`>`or`<`with variables that can occasionally be `null/undefined`. Checking for `null/undefined` separately is a good idea.
205
+
-Operadores de comparação retornam um valor booleano.
206
+
-As strings são comparadas letra por letra na ordem "dicionário".
207
+
-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).
208
+
-Os valores`null`e`undefined`usando`==`são iguais entre eles e não são iguais a nenhum outro valor.
209
+
-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.
0 commit comments