Skip to content

Commit 8caae40

Browse files
committed
Comparisons
1 parent 876a635 commit 8caae40

File tree

3 files changed

+105
-106
lines changed

3 files changed

+105
-106
lines changed

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

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,19 @@
33
```js no-beautify
44
5 > 4true
55
"apple" > "pineapple"false
6-
"2" > "12"true
7-
undefined == nulltrue
8-
undefined === nullfalse
6+
"2" > "12"true
7+
undefined == nulltrue
8+
undefined === nullfalse
99
null == "\n0\n"false
10-
null === +"\n0\n"false
10+
null === +"\n0\n"false
1111
```
1212

13-
Some of the reasons:
13+
Algunas de las razones:
1414

15-
1. Obviously, true.
16-
2. Dictionary comparison, hence false.
17-
3. Again, dictionary comparison, first char of `"2"` is greater than the first char of `"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. See (4).
21-
7. Strict equality of different types.
15+
1. Obviamente, true.
16+
2. Comparación lexicográfica, por lo tanto false.
17+
3. Una vez más, la comparación lexicográfica, el primer carácter de `"2"` es mayor que el primer carácter de `"1"`.
18+
4. Los valores `null` y `undefined` son iguales entre sí solamente.
19+
5. La igualdad estricta es estricta. Diferentes tipos de ambos lados conducen a false.
20+
6. Ver (4).
21+
7. Igualdad estricta de diferentes tipos.

1-js/02-first-steps/08-comparison/1-comparison-questions/task.md

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

33
---
44

5-
# Comparisons
5+
# Comparaciones
66

7-
What will be the result for these expressions?
7+
¿Cuál será el resultado de las siguientes expresiones?
88

99
```js no-beautify
1010
5 > 4
@@ -15,4 +15,3 @@ undefined === null
1515
null == "\n0\n"
1616
null === +"\n0\n"
1717
```
18-
Lines changed: 91 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -1,95 +1,95 @@
1-
# Comparisons
1+
# Comparaciones
22

3-
We know many comparison operators from maths:
3+
Conocemos muchos operadores de comparación de las matemáticas:
44

5-
- Greater/less than: <code>a &gt; b</code>, <code>a &lt; b</code>.
6-
- Greater/less than or equals: <code>a &gt;= b</code>, <code>a &lt;= 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>&ne;</code>, but in JavaScript it's written as an assignment with an exclamation sign before it: <code>a != b</code>.
5+
- Mayor/menor que: <code>a &gt; b</code>, <code>a &lt; b</code>.
6+
- Mayor/menor o igual que: <code>a &gt;= b</code>, <code>a &lt;= 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>&ne;</code>, pero en JavaScript se escribe como una asignación con un signo de exclamación delante: <code>a != b</code>.
99

10-
## Boolean is the result
10+
## Booleano es el resultado
1111

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.
1313

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".
1616

17-
For example:
17+
Por ejemplo:
1818

1919
```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)
2323
```
2424

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:
2626

2727
```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
2929
alert( result ); // true
3030
```
3131

32-
## String comparison
32+
## Comparación de cadenas
3333

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".
3535

36-
In other words, strings are compared letter-by-letter.
36+
En otras palabras, las cadenas se comparan letra por letra.
3737

38-
For example:
38+
Por ejemplo:
3939

4040
```js run
4141
alert( 'Z' > 'A' ); // true
4242
alert( 'Glow' > 'Glee' ); // true
4343
alert( 'Bee' > 'Be' ); // true
4444
```
4545

46-
The algorithm to compare two strings is simple:
46+
El algoritmo para comparar dos cadenas es simple:
4747

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.
5353

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:
5555

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.
5959

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.
6262
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>.
6464
```
6565

66-
## Comparison of different types
66+
## Comparación de diferentes tipos
6767

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.
6969

70-
For example:
70+
Por ejemplo:
7171

7272
```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
7575
```
7676

77-
For boolean values, `true` becomes `1` and `false` becomes `0`.
77+
Para valores booleanos, `true` se convierte en `1` y `false` en `0`.
7878

79-
For example:
79+
Por ejemplo:
8080

8181
```js run
8282
alert( true == 1 ); // true
8383
alert( false == 0 ); // true
8484
```
8585

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:
8888
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.
9191
92-
For example:
92+
Por ejemplo:
9393
9494
```js run
9595
let a = 0;
@@ -98,115 +98,115 @@ alert( Boolean(a) ); // false
9898
let b = "0";
9999
alert( Boolean(b) ); // true
100100
101-
alert(a == b); // true!
101+
alert( a == b ); // true!
102102
```
103103
104-
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.
105105
````
106106

107-
## Strict equality
107+
## Igualdad estricta
108108

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':
110110

111111
```js run
112112
alert( 0 == false ); // true
113113
```
114114

115-
The same thing happens with an empty string:
115+
Lo mismo sucede con una cadena vacía:
116116

117117
```js run
118118
alert( '' == false ); // true
119119
```
120120

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.
122122

123-
What to do if we'd like to differentiate `0` from `false`?
123+
¿Qué hacer si queremos diferenciar `0` de `false`?
124124

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.**
126126

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.
128128

129-
Let's try it:
129+
Intentémoslo:
130130

131131
```js run
132-
alert( 0 === false ); // false, because the types are different
132+
alert( 0 === false ); // falso, porque los tipos son diferentes
133133
```
134134

135-
There is also a "strict non-equality" operator `!==` analogous to `!=`.
135+
Existe también un operador de "diferencia estricta" `!==` análogo a `!=`.
136136

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.
138138

139-
## Comparison with null and undefined
139+
## Comparación con nulos e indefinidos
140140

141-
Let's see more edge cases.
141+
Veamos más casos extremos.
142142

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.
144144

145145

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.
148148

149149
```js run
150150
alert( null === undefined ); // false
151151
```
152152

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.
155155

156156
```js run
157157
alert( null == undefined ); // true
158158
```
159159

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`.
162162

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.
164164

165-
### Strange result: null vs 0
165+
### Resultado extraño: null vs 0
166166

167-
Let's compare `null` with a zero:
167+
Comparemos `null` con un cero:
168168

169169
```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
172172
alert( null >= 0 ); // (3) *!*true*/!*
173173
```
174174

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.
176176

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.
178178

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.
180180

181-
### An incomparable undefined
181+
### Un indefinido incomparable
182182

183-
The value `undefined` shouldn't be compared to other values:
183+
El valor `undefined` no debe compararse con otros valores:
184184

185185
```js run
186186
alert( undefined > 0 ); // false (1)
187187
alert( undefined < 0 ); // false (2)
188188
alert( undefined == 0 ); // false (3)
189189
```
190190

191-
Why does it dislike zero so much? Always false!
191+
¿Por qué le desagrada tanto el cero? ¡Siempre falso!
192192

193-
We get these results because:
193+
Obtenemos estos resultados porque:
194194

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.
197197

198-
### Evade problems
198+
### Evita los problemas
199199

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:
201201

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.
203203

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.
205205

206-
## Summary
206+
## Resumen
207207

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

Comments
 (0)