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>.
-Mayor/menor o igual que: <code>a >= b</code>, <code>a <= b</code>.
7
+
-Igual: `a == b` (ten en cuenta el doble signo`=`. Un solo símbolo`a = b`significaría una asignación).
8
+
-Distinto. En matemáticas la notación es <code>≠</code>, pero en JavaScript se escribe como una asignación con un signo de exclamación delante: <code>a != b</code>.
9
9
10
-
## Boolean is the result
10
+
## Booleano es el resultado
11
11
12
-
Like all other operators, a comparison returns a value. In this case, the value is a boolean.
12
+
Como todos los demás operadores, una comparación retorna un valor. En este caso, el valor es un booleano.
13
13
14
-
-`true` -- means "yes", "correct" or "the truth".
15
-
-`false` -- means "no", "wrong" or "not the truth".
14
+
-`true` -- significa "sí", "correcto" o "verdad".
15
+
-`false` -- significa "no", "equivocado" o " no verdad".
16
16
17
-
For example:
17
+
Por ejemplo:
18
18
19
19
```js run
20
-
alert( 2>1 ); // true (correct)
21
-
alert( 2==1 ); // false (wrong)
22
-
alert( 2!=1 ); // true (correct)
20
+
alert( 2>1 ); // true (correcto)
21
+
alert( 2==1 ); // false (incorrecto)
22
+
alert( 2!=1 ); // true (correcto)
23
23
```
24
24
25
-
A comparison result can be assigned to a variable, just like any value:
25
+
El resultado de una comparación puede asignarse a una variable, igual que cualquier valor:
26
26
27
27
```js run
28
-
let result =5>4; //assign the result of the comparison
28
+
let result =5>4; //asignar el resultado de la comparación
29
29
alert( result ); // true
30
30
```
31
31
32
-
## String comparison
32
+
## Comparación de cadenas
33
33
34
-
To see whether a string is greater than another, JavaScript uses the so-called "dictionary" or "lexicographical" order.
34
+
Para ver si una cadena es "mayor" que otra, JavaScript utiliza el llamado orden "diccionario" u "lexicográfico".
35
35
36
-
In other words, strings are compared letter-by-letter.
36
+
En otras palabras, las cadenas se comparan letra por letra.
37
37
38
-
For example:
38
+
Por ejemplo:
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
+
El algoritmo para comparar dos cadenas es simple:
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 el primer carácter de ambas cadenas.
49
+
2.Si el primer carácter de la primera cadena es mayor (o menor) que el de la otra cadena, entonces la primera cadena es mayor (o menor) que la segunda. Hemos terminado.
50
+
3.De lo contrario, si los primeros caracteres de ambas cadenas son los mismos, compare los segundos caracteres de la misma manera.
51
+
4.Repita hasta el final de cada cadena.
52
+
5.Si ambas cadenas tienen la misma longitud, entonces son iguales. De lo contrario, la cadena más larga es mayor.
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
+
En los ejemplos anteriores, la comparación`'Z' > 'A'`llega a un resultado en el primer paso, mientras que las cadenas `"Glow"`y`"Glee"`se comparan carácter por carácter:
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`es igual que`G`.
57
+
2.`l`es igual que`l`.
58
+
3.`o`es mayor que`e`. Detente aquí. La primera cadena es mayor.
59
59
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.
60
+
```smart header="No es un diccionario real, sino un orden Unicode"
61
+
El algoritmo de comparación dado arriba es aproximadamente equivalente al utilizado en los diccionarios o guías telefónicas, pero no es exactamente el mismo.
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 ejemplo, las mayúsculas importan. Una letra mayúscula `"A"` no es igual a la minúscula `"a"`. ¿Cuál es mayor? La `"a"` minúscula. ¿Por qué? Porque el carácter en minúsculas tiene un mayor índice en la tabla de codificación interna que utiliza JavaScript (Unicode). Volveremos a los detalles específicos y las consecuencias de esto en el capítulo <info:string>.
64
64
```
65
65
66
-
## Comparison of different types
66
+
## Comparación de diferentes tipos
67
67
68
-
When comparing values of different types, JavaScript converts the values to numbers.
68
+
Al comparar valores de diferentes tipos, JavaScript convierte los valores a números.
69
69
70
-
For example:
70
+
Por ejemplo:
71
71
72
72
```js run
73
-
alert( '2'>1 ); // true, string '2' becomes a number 2
74
-
alert( '01'==1 ); // true, string '01' becomes a number 1
73
+
alert( '2'>1 ); // true, la cadena '2' se convierte en el número 2
74
+
alert( '01'==1 ); // true, la cadena '01' se convierte en el número 1
75
75
```
76
76
77
-
For boolean values, `true`becomes `1`and`false`becomes`0`.
77
+
Para valores booleanos, `true`se convierte en `1`y`false`en`0`.
78
78
79
-
For example:
79
+
Por ejemplo:
80
80
81
81
```js run
82
82
alert( true==1 ); // true
83
83
alert( false==0 ); // true
84
84
```
85
85
86
-
````smart header="A funny consequence"
87
-
It is possible that at the same time:
86
+
````smart header="Una consecuencia graciosa"
87
+
Es posible que al mismo tiempo:
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
+
- Dos valores sean iguales.
90
+
- Uno de ellos sea `true` como booleano y el otro sea `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
+
Desde el punto de vista de JavaScript, este resultado es bastante normal. Una comparación de igualdad convierte valores utilizando la conversión numérica (de ahí que `"0"` se convierta en `0`), mientras que la conversión explícita `Boolean` utiliza otro conjunto de reglas.
105
105
````
106
106
107
-
## Strict equality
107
+
## Igualdad estricta
108
108
109
-
A regular equality check`==`has a problem. It cannot differentiate`0`from `false`:
109
+
Una comparación regular de igualdad`==`tiene un problema. No puede diferenciar`0`de `falso':
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
+
Lo mismo sucede con una cadena vacía:
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
+
Esto sucede porque los operandos de diferentes tipos son convertidos a números por el operador de igualdad `==`. Una cadena vacía, al igual que `false`, se convierte en un cero.
122
122
123
-
What to do if we'd like to differentiate `0`from`false`?
123
+
¿Qué hacer si queremos diferenciar `0`de`false`?
124
124
125
-
**A strict equality operator `===`checks the equality without type conversion.**
125
+
**Un operador de igualdad estricto `===`comprueba la igualdad sin conversión 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
+
En otras palabras, si`a`y`b`son de diferentes tipos, entonces`a === b`retorna inmediatamente`false`sin intentar convertirlos.
128
128
129
-
Let's try it:
129
+
Intentémoslo:
130
130
131
131
```js run
132
-
alert( 0===false ); //false, because the types are different
132
+
alert( 0===false ); //falso, porque los tipos son diferentes
133
133
```
134
134
135
-
There is also a "strict non-equality" operator `!==`analogous to`!=`.
135
+
Existe también un operador de "diferencia estricta" `!==`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
+
El operador de igualdad estricta es un poco más largo de escribir, pero hace obvio lo que está pasando y deja menos espacio a errores.
138
138
139
-
## Comparison with null and undefined
139
+
## Comparación con nulos e indefinidos
140
140
141
-
Let's see more edge cases.
141
+
Veamos más casos extremos.
142
142
143
-
There's a non-intuitive behavior when `null`or`undefined`are compared to other values.
143
+
Hay un comportamiento no intuitivo cuando se compara `null`o`undefined`con otros 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 un control de igualdad estricto`===`
147
+
: Estos valores son diferentes, porque cada uno de ellos es de un tipo diferente.
148
148
149
149
```js run
150
150
alert( null === undefined ); // false
151
151
```
152
152
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.
153
+
Para una camparación no estricta`==`
154
+
: Hay una regla especial. Estos dos son una " pareja dulce ": son iguales entre sí (en el sentido de`==`), pero no a ningún otro valor.
155
155
156
156
```js run
157
157
alert( null == undefined ); // true
158
158
```
159
159
160
-
For maths and other comparisons`< > <= >=`
161
-
: `null/undefined`are converted to numbers: `null`becomes `0`, while `undefined`becomes`NaN`.
160
+
Para matemáticas y otras comparaciones`< > <= >=`
161
+
: `null/undefined`se convierten en números: `null`se convierte en `0`, mientras que `undefined`se convierte en`NaN`.
162
162
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.
163
+
Ahora veamos algunos hechos graciosas que suceden cuando aplicamos estas reglas. Y, lo que es más importante, cómo no caer en una trampa con ellas.
164
164
165
-
### Strange result: null vs 0
165
+
### Resultado extraño: null vs 0
166
166
167
-
Let's compare `null`with a zero:
167
+
Comparemos `null` con un cero:
168
168
169
169
```js run
170
-
alert( null>0 ); // (1) false
171
-
alert( null==0 ); // (2) false
170
+
alert( null>0 ); /// (1) false
171
+
alert( null==0 ); /// (2) false
172
172
alert( null>=0 ); // (3) *!*true*/!*
173
173
```
174
174
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.
175
+
Matemáticamente, eso es extraño. El último resultado afirma que "`null`es mayor o igual a cero", así que en una de las comparaciones anteriores debe ser`true`, pero ambas son falsas.
176
176
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.
177
+
La razón es que una comparación de igualdad `==`y las comparaciones `> < >= <=`funcionan de manera diferente. Las comparaciones convierten a `null`en un número, tratándolo como `0`. Es por eso que (3) `null >= 0`es verdadero y (1) `null > 0`es falso.
178
178
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.
179
+
Por otro lado, el control de igualdad `==`para`undefined`y`null`se define de tal manera que, sin ninguna conversión, son iguales entre sí y no son iguales a nada más. Es por eso que (2) `null == 0`es falso.
180
180
181
-
### An incomparable undefined
181
+
### Un indefinido incomparable
182
182
183
-
The value`undefined`shouldn't be compared to other values:
183
+
El valor`undefined`no debe compararse con otros valores:
184
184
185
185
```js run
186
186
alert( undefined>0 ); // false (1)
187
187
alert( undefined<0 ); // false (2)
188
188
alert( undefined==0 ); // false (3)
189
189
```
190
190
191
-
Why does it dislike zero so much? Always false!
191
+
¿Por qué le desagrada tanto el cero? ¡Siempre falso!
192
192
193
-
We get these results because:
193
+
Obtenemos estos resultados porque:
194
194
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.
195
+
-Las comparaciones `(1)`y`(2)`retornan `falso` porque `no definido` se convierte en`NaN`y`NaN`es un valor numérico especial que retorna `falso` para todas las comparaciones.
196
+
-La comparación de igualdad `(3)`retorna `falso` porque`undefined`sólo equivale a `null`y a ningún otro valor.
197
197
198
-
### Evade problems
198
+
### Evita los problemas
199
199
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:
200
+
¿Por qué repasamos estos ejemplos? ¿Deberíamos recordar estas peculiaridades todo el tiempo? Bueno, en realidad no. En realidad, estas cosas difíciles se volverán familiares con el tiempo, pero hay una manera sólida de evadir los problemas con ellas:
201
201
202
-
Just treat any comparison with `undefined/null`except the strict equality`===`with exceptional care.
202
+
Trata cualquier comparación con `undefined/null`excepto la igualdad estricta`===`con sumo cuidado.
203
203
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.
204
+
No uses comparaciones`>= > < <=`con una variable que puede ser`null/undefined`, a menos que estés realmente seguro de lo que estás haciendo. Si una variable puede tener estos valores, verifícalos por separado.
205
205
206
-
## Summary
206
+
## Resumen
207
207
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.
208
+
-Los operadores de comparación retornan un valor booleano.
209
+
-Las cadenas se comparan letra por letra en el orden del "diccionario".
210
+
-Cuando se comparan valores de diferentes tipos, se convierten en números (con la exclusión de un control de igualdad estricta).
211
+
-Los valores`null`y`undefined`son iguales `==`entre sí y no equivalen a ningún otro valor.
212
+
-Ten cuidado al usar comparaciones como`>`o`<`con variables que ocasionalmente pueden ser`null/undefined`. Revisar por separado si hay `null/undefined`es una buena idea.
0 commit comments