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..9cd356a62 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. +La respuesta es `2`, ese es el primer valor verdadero. ```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..2bf460f1d 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? +# ¿Cuál es el resultado de OR? -What is the code below going to output? +¿Cuál será la salida del siguiente código? ```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..e7ef801f5 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`. +La repuesta: primero `1`, después `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`. +La llamada a `alert` no retorna un valor. O, en otras palabras, 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. El primer OR `||` evalua el operando de la izquierda `alert(1)`. Eso muestra el primer mensaje con `1`. +2. El `alert` retorna `undefined`, por lo que OR se dirige al segundo operando buscando un valor verdadero. +3. El segundo operando `2` es un valor verdadero, por lo que se detiene la ejecución, se retorna `2` y es mostrado por el alert exterior. -There will be no `3`, because the evaluation does not reach `alert(3)`. +No habrá `3` debido a que la evaluación no alcanza 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..4b5519fbb 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? +# ¿Cuál es el resultado de las alertas aplicadas al operador OR? -What will the code below output? +¿Cuál será la salida del siguiente código? ```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..0af868958 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. +La respuesta: `null`, porque es el primer valor falso de la 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..910a417e0 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? +# ¿Cuál es el resultado de AND? -What is this code going to show? +¿Cuál será la salida del siguiente código? ```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..72099de38 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,9 @@ -The answer: `1`, and then `undefined`. +La respuesta: `1` y después `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). - -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. +La llamada a `alert` retorna `undefined` (solo muestra un mensaje, así que no hay un valor que retornar relevante) +Debido a ello, `&&` evalua el operando de la izquierda (imprime `1`) e inmediatamente se detiene porque `undefined` es un valor falso. Como `&&` busca un valor falso y lo retorna, terminamos. 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..e3c318884 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? +# ¿Cuál es el resultado de las alertas aplicadas al operador AND? -What will this code show? +¿Cuál será la salida del siguiente código? ```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..4903143d7 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`. +La respuesta: `3`. ```js run alert( null || 2 && 3 || 4 ); ``` -The precedence of AND `&&` is higher than `||`, so it executes first. +La precedencia de AND `&&` es mayor que la de `||`, así que se ejecuta primero. -The result of `2 && 3 = 3`, so the expression becomes: +El resultado de `2 && 3 = 3`, por lo que la expresión se convierte en: ``` null || 3 || 4 ``` -Now the result is the first truthy value: `3`. +Ahora el resultado será el primer valor verdadero: `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..2e97e602a 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 +# El resultado de OR AND OR -What will the result be? +¿Cuál será el 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..5cae495a8 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 +# Comprueba el rango por dentro -Write an "if" condition to check that `age` is between `14` and `90` inclusively. +Escribe una condición "if" para comprobar que `age`(edad) está entre `14` y `90` inclusivamente. -"Inclusively" means that `age` can reach the edges `14` or `90`. +"Inclusivamente" significa que `age` puede llegar a ser uno de los extremos, `14` o `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..dd8c08364 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: +La primer variante: ```js if (!(age >= 14 && age <= 90)) ``` -The second variant: +La 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..c97e08312 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 +# Comprueba el rango por fuera -Write an `if` condition to check that `age` is NOT between 14 and 90 inclusively. +Escribe una condición `if` para comprobar que `age` NO está entre 14 y 90 inclusivemente. -Create two variants: the first one using NOT `!`, the second one -- without it. +Crea dos variantes: la primera usando NOT `!`, y la segunda -- sin usarlo. 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..f9ce47b32 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. +La respuesta: el primero y el tercero serán ejecutados. -Details: +Detalles: ```js run -// Runs. -// The result of -1 || 0 = -1, truthy -if (-1 || 0) alert( 'first' ); +// Corre. +// El resultado de -1 || 0 = -1, valor verdadero +if (-1 || 0) alert( "primero" ); -// Doesn't run -// -1 && 0 = 0, falsy -if (-1 && 0) alert( 'second' ); +// No corre. +// -1 && 0 = 0, valor falso +if (-1 && 0) alert( "segundo" ); -// Executes -// Operator && has a higher precedence than || -// so -1 && 1 executes first, giving us the chain: +// Se ejecuta +// El operador && tiene mayor precedencia que || +// Así que -1 && 1 se ejecuta primero, dándonos la cadena: // null || -1 && 1 -> null || 1 -> 1 -if (null || -1 && 1) alert( 'third' ); +if (null || -1 && 1) alert( "tercero" ); ``` 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..e909805c1 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,15 +2,15 @@ importance: 5 --- -# A question about "if" +# Un pregunta acerca de "if" -Which of these `alert`s are going to execute? +¿Cuáles de estos `alert`s va a ejecutarse? -What will the results of the expressions be inside `if(...)`? +¿Cuáles serán los resultados de las expresiones dentro de `if(...)`? ```js -if (-1 || 0) alert( 'first' ); -if (-1 && 0) alert( 'second' ); -if (null || -1 && 1) alert( 'third' ); +if (-1 || 0) alert( "primero" ); +if (-1 && 0) alert( "segundo" ); +if (null || -1 && 1) alert( "tercero" ); ``` 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..b2168dc84 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 @@ -1,25 +1,25 @@ ```js run demo -let userName = prompt("Who's there?", ''); +let userName = prompt("Quién está ahí?", ""); -if (userName == 'Admin') { +if (userName == "Admin") { + + let pass = prompt("Contraseña?", ""); - let pass = prompt('Password?', ''); - - if (pass == 'TheMaster') { - alert( 'Welcome!' ); - } else if (pass == '' || pass == null) { - alert( 'Canceled.' ); - } else { - alert( 'Wrong password' ); - } - -} else if (userName == '' || userName == null) { - alert( 'Canceled' ); + if (pass == "TheMaster") { + alert( "Bienvenido!" ); + } else if (pass == "" || pass == null) { + alert( "Cancelado." ); + } else { + alert( "Contraseña incorrecta" ); + } + +} else if (userName == "" || userName == null) { + alert( "Canceledo" ); } else { - alert( "I don't know you" ); + alert( "No te conozco" ); } ``` -Note the vertical indents inside the `if` blocks. They are technically not required, but make the code more readable. +Nota las sangrías verticales dentro de los bloques `if`. Técnicamente no son necesarias, pero facilitan la lectura del código. 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..5c0481711 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 +# Comprueba el inicio de sesión -Write the code which asks for a login with `prompt`. +Escribe un código que pregunte por el inicio de sesión con `propmt`. -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". +Si el visitante ingresa `"Admin"`, entonces `prompt`(pregunta) por una contraseña, si la entrada es una linea vacía o `key:Esc` -- muestra "Cancelado.", si es otra cadena de texto -- entonces muestra "No te conozco". -The password is checked as follows: +La contraseña se comprueba de la siguiente manera: -- If it equals "TheMaster", then show "Welcome!", -- Another string -- show "Wrong password", -- For an empty string or cancelled input, show "Canceled." +- Si es igual a "TheMaster", entonces muestra "Bienvenido!", +- Si es otra cadena de texto -- muetra "Contraseña incorrecta", +- Para una cadena de texto vacía o una entrada cancelada, muestra "Cancelado." -The schema: +El esquema: ![](ifelse_task.png) -Please use nested `if` blocks. Mind the overall readability of the code. +Por favor usa bloques anidados de `if`. Piensa en la legibilidad general del código. -Hint: passing an empty input to a prompt returns an empty string `''`. Pressing `key:ESC` during a prompt returns `null`. +Pista: si se le pasa una entrada vacía a un prompt, retorna una cadena de texto vacía `''`. Presionando `key:ESC` durante un prompt retorna `null`. [demo] 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..ca88dc510 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). +Hay tres operadores lógicos en JavaScript: `||` (OR (O)), `&&` (AND (Y)), `!` (NOT (NO)). -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. +Aunque sean llamados lógicos, pueden ser aplicados a valores de cualquier tipo, no solo booleanos. El resultado también puede ser de cualquier tipo. -Let's see the details. +Veamos los detalles. ## || (OR) -The "OR" operator is represented with two vertical line symbols: +El operador `OR` se representa con dos simbolos de linea vertical: ```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`. +En la programación clasica, el OR lógico esta pensado para manipular solo valores booleanos. Si cualquiera de sus argumentos es `true`, retorna `true`, de lo contrario retorna `false`. -In JavaScript, the operator is a little bit trickier and more powerful. But first, let's see what happens with boolean values. +En JavaScript, el operador es un poco más complicado y poderoso. Pero primero, veamos qué pasa con los valores booleanos. -There are four possible logical combinations: +Hay cuatro combinaciones lógicas posibles: ```js run -alert( true || true ); // true -alert( false || true ); // true -alert( true || false ); // true -alert( false || false ); // false +alert(true || true); // true (verdadero) +alert(false || true); // true +alert(true || false); // true +alert(false || false); // false (falso) ``` -As we can see, the result is always `true` except for the case when both operands are `false`. +Como podemos ver, el resultado es siempre `true` excepto cuando ambos operandos son `false`. -If an operand is not a boolean, it's converted to a boolean for the evaluation. +Si un operando no es un booleano, se lo convierte a booleano para la evaluación. -For instance, the number `1` is treated as `true`, the number `0` as `false`: +Por ejemplo, el número `1` es tratado como `true`, el número `0` como `false`: ```js run -if (1 || 0) { // works just like if( true || false ) - alert( 'truthy!' ); +if (1 || 0) { // Funciona como if( true || false ) + alert("valor verdadero!"); } ``` -Most of the time, OR `||` is used in an `if` statement to test if *any* of the given conditions is `true`. +La mayoría de las veces, OR `||` es usado en una declaración `if` para probar si *cualquiera* de las condiciones dadas es `true`. -For example: +Por ejemplo: ```js run let hour = 9; @@ -49,255 +49,257 @@ let hour = 9; *!* if (hour < 10 || hour > 18) { */!* - alert( 'The office is closed.' ); + alert( 'La oficina esta cerrada.' ); } ``` -We can pass more conditions: +Podemos pasar mas condiciones: ```js run let hour = 12; let isWeekend = true; if (hour < 10 || hour > 18 || isWeekend) { - alert( 'The office is closed.' ); // it is the weekend + alert("La oficina esta cerrada."); // Es fin de semana } ``` -## OR finds the first truthy value +## OR encuentra el primer valor verdadero -The logic described above is somewhat classical. Now, let's bring in the "extra" features of JavaScript. +La lógica descrita arriba es algo clásica. Ahora, mostremos las características "extra" de JavaScript. -The extended algorithm works as follows. +El algoritmo extendido trabaja de la siguiente forma. -Given multiple OR'ed values: +Dado múltiples valores aplicados al operador OR: ```js result = value1 || value2 || value3; ``` -The OR `||` operator does the following: +El operador OR `||` realiza lo siguiente: -- 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. +- Evalua los operandos de izquierda a derecha. +- Para cada operando, convierte el valor a booleano. Si el resultado es `true`, se detiene y retorna el valor orginal de ese operando. +- Si todos los operandos han sido evaluados (todos eran `false`), retorna el ultimo operando. -A value is returned in its original form, without the conversion. +Un valor es retornado en su forma original, sin la conversión. -In other words, a chain of OR `"||"` returns the first truthy value or the last one if no such value is found. +En otras palabras, una cadena de OR `"||"` retorna el primer valor verdadero o el último valor en caso de que ningún verdadero sea encontrado. -For instance: +Por ejemplo: ```js run -alert( 1 || 0 ); // 1 (1 is truthy) -alert( true || 'no matter what' ); // (true is truthy) +alert(1 || 0); // 1 (1 es un valor verdado) +alert(true || "cualquier valor"); // (true es un valor verdadero) -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 es el primer valor verdadero) +alert(null || 0 || 1); // 1 (el primer valor verdadero) +alert(undefined || null || 0); // 0 (todos son valores falsos, retorna el último valor) ``` -This leads to some interesting usage compared to a "pure, classical, boolean-only OR". +Esto brinda varios usos interesantes comparados al "OR puro, clásico, de solo booleanos". -1. **Getting the first truthy value from a list of variables or expressions.** +1. **Consiguiendo el primer valor verdadero de una lista de variables o expresiones.** - Imagine we have several variables which can either contain data or be `null/undefined`. How can we find the first one with data? + Imagina que tenemos múltiples variables que pueden contener datos o bien ser `null/undefined`. ¿Cómo podemos encontrar el primer valor que contenga datos? - We can use OR `||`: + Podemos usar OR `||`: - ```js run - let currentUser = null; - let defaultUser = "John"; + ```js run + let currentUser = null; + let defaultUser = "John"; - *!* - let name = currentUser || defaultUser || "unnamed"; - */!* + *!* + let name = currentUser || defaultUser || "sin nombre"; + */!* - alert( name ); // selects "John" – the first truthy value - ``` + alert( name ); // selecciona "John" – el primer valor verdadero + ``` - If both `currentUser` and `defaultUser` were falsy, `"unnamed"` would be the result. -2. **Short-circuit evaluation.** + Si tanto `currentUser` como `defaultUser` hubieran sido valores falsos, `"sin nombre"` hubiera sido el resultado. - 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. +2. **Evaluación de cortocircuito.** - This is clearly seen when the expression given as the second argument has a side effect like a variable assignment. + Los operandos no solo pueden ser valores, sino que tambien expresiones arbitrarias. OR los evalua y comprueba de izquierda a derecha. La evaluación termina cuando un valor verdadero es alcanzado, y dicho valor es retornado. Este proceso es llamado "evaluación de cortocircuito" porque avanza lo menos posible de izquierda a derecha. - In the example below, `x` does not get assigned: + Esto se ve claramente cuando la expresión dada como segundo argumento tiene un efecto secundario como una asignación de variable. - ```js run no-beautify - let x; + En el ejemplo debajo, `x` no es asignada: - *!*true*/!* || (x = 1); + ```js run no-beautify + let x; - alert(x); // undefined, because (x = 1) not evaluated - ``` + *!*true*/!* || (x = 1); - If, instead, the first argument is `false`, `||` evaluates the second one, thus running the assignment: + alert(x); // undefined, porque (x = 1) no es evaluado. + ``` - ```js run no-beautify - let x; + Si, en cambio, el primer argumento fuera `false`, `||` evaluaría el segundo, realizando la asignación. - *!*false*/!* || (x = 1); + ```js run no-beautify + let x; - alert(x); // 1 - ``` + *!*false*/!* || (x = 1); - An assignment is a simple case. Other side effects can also be involved. + alert(x); // 1 + ``` - 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. + Una asignación es un caso simple. Puede haber efectos secundarios, los cuales no se notarán si la evaluación no los alcanza. - Most of time, it's better to use a "regular" `if` to keep the code easy to understand, but sometimes this can be handy. + Como podemos ver, tal caso de uso es una "manera más corta de usar `if`". El primer operando es convertido a booleano. Si el primero es falso, el segundo sera evaluado. + + La mayor parte del tiempo, es mejor usar un `if` "normal" para mantener el código fácil de entender, pero a veces esto puede ser útil. ## && (AND) -The AND operator is represented with two ampersands `&&`: +El operador AND es representado con `&&`: ```js result = a && b; ``` -In classical programming, AND returns `true` if both operands are truthy and `false` otherwise: +En la programación clasica, AND retorna `true` si ambos operandos son valores verdaderos y falso en cualquier otro caso. ```js run -alert( true && true ); // true -alert( false && true ); // false -alert( true && false ); // false -alert( false && false ); // false +alert(true && true); // true +alert(false && true); // false +alert(true && false); // false +alert(false && false); // false ``` -An example with `if`: +Un ejemplo con `if`: ```js run let hour = 12; let minute = 30; if (hour == 12 && minute == 30) { - alert( 'The time is 12:30' ); + alert("La hora es 12:30"); } ``` -Just as with OR, any value is allowed as an operand of AND: +Al igual que con OR, cualquier valor es permitido como operando de AND: ```js run -if (1 && 0) { // evaluated as true && false - alert( "won't work, because the result is falsy" ); +if (1 && 0) { // evaluado como true && false + alert( "no funcionará porque el resultado es un valor falso" ); } ``` +## AND encuentra el primer valor verdadero -## AND finds the first falsy value - -Given multiple AND'ed values: +Dado múltiples valores aplicados al operador AND: ```js result = value1 && value2 && value3; ``` -The AND `&&` operator does the following: +El operador AND `&&` realiza lo siguiente: -- 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. +- Evalua los operandos de izquierda a derecha. +- Para cada operando, los convierte a un booleano. Si el resultado es `false`, se detiene y retorna el valor original de dicho operando. +- Si todos los operandos han sido evaluados (todos fueron valores verdaderos), retorna el último operando. -In other words, AND returns the first falsy value or the last value if none were found. +En otras palabras, AND retorna el primer valor falso o el último valor si ninguno fue 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. +Las reglas anteriores son similares a las de OR. La difierence es que AND retorna el primer valor *falso* mientras que OR retorna el primer valor *verdadero*. -Examples: +Ejemplo: ```js run -// if the first operand is truthy, -// AND returns the second operand: -alert( 1 && 0 ); // 0 -alert( 1 && 5 ); // 5 - -// if the first operand is falsy, -// AND returns it. The second operand is ignored -alert( null && 5 ); // null -alert( 0 && "no matter what" ); // 0 +// si el primer operando es un valor verdadero, +// AND retorna el segundo operando: +alert(1 && 0); // 0 +alert(1 && 5); // 5 + +// si el primer operando es un valor falso, +// AND lo retorna. El segundo operando es ignorado +alert(null && 5); // null +alert(0 && "cualquier valor"); // 0 ``` -We can also pass several values in a row. See how the first falsy one is returned: +También podemos pasar varios valores de una vez. Observa como el primer valor falso es retornado: ```js run -alert( 1 && 2 && null && 3 ); // null +alert(1 && 2 && null && 3); // null ``` -When all values are truthy, the last value is returned: +Cuando todos los valores son verdaderos, el último valor es retornado: ```js run -alert( 1 && 2 && 3 ); // 3, the last one +alert(1 && 2 && 3); // 3, el último. ``` -````smart header="Precedence of AND `&&` is higher than OR `||`" -The precedence of AND `&&` operator is higher than OR `||`. +```smart header="La precedencia de AND `&&` es mayor que la de OR `||`" -So the code `a && b || c && d` is essentially the same as if the `&&` expressions were in parentheses: `(a && b) || (c && d)`. -```` +La precedencia del operador AND `&&` es mayor que la de OR `||`. + +Así que el código `a && b || c && d` es básicamente el mismo que si la expresiones `&&` estuvieran entre paréntesis: `(a && b) || (c && d)` +``` -Just like OR, the AND `&&` operator can sometimes replace `if`. +Justo como en OR, el operador AND `&&` puede reemplazar en ocasiones al `if`. -For instance: +Por ejemplo: ```js run let x = 1; -(x > 0) && alert( 'Greater than zero!' ); -``` +(x > 0) && alert("Mayor que cero!"); +```` -The action in the right part of `&&` would execute only if the evaluation reaches it. That is, only if `(x > 0)` is true. +La acción en la parte derecha de `&&` sería ejecutada sólo si la evaluación la alcanza. Eso es, solo si `(x > 0)` es verdadero. -So we basically have an analogue for: +Así que básicamente tenemos un análogo para: ```js run let x = 1; if (x > 0) { - alert( 'Greater than zero!' ); + alert("Mayor que cero!"); } ``` -The variant with `&&` appears shorter. But `if` is more obvious and tends to be a little bit more readable. +La variante con `&&` parece más corta. Pero `if` es más obvio y tiende a ser un poco más legible. -So we recommend using every construct for its purpose: use `if` if we want if and use `&&` if we want AND. +Así que recomendamos usar cada construcción para su propósito: usar `if` si queremos if y usar `&&` si queremos AND. ## ! (NOT) -The boolean NOT operator is represented with an exclamation sign `!`. +El operador booleano NOT se representa con un signo de exclamación `!`. -The syntax is pretty simple: +La sintaxis es bastante simple: ```js result = !value; ``` -The operator accepts a single argument and does the following: +El operador acepta un solo argumento y realiza lo siguiente: -1. Converts the operand to boolean type: `true/false`. -2. Returns the inverse value. +1. Convierte el operando al tipo booleano: `true/false`. +2. Retorna el valor contrario. -For instance: +Por ejemplo: ```js run -alert( !true ); // false -alert( !0 ); // true +alert(!true); // false +alert(!0); // true ``` -A double NOT `!!` is sometimes used for converting a value to boolean type: +Un doble NOT `!!` es a veces usado para convertir un valor al tipo booleano: ```js run -alert( !!"non-empty string" ); // true -alert( !!null ); // false +alert(!!"cadena de texto no vacía"); // true +alert(!!null); // false ``` -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. +Eso es, el primer NOT convierte el valor a booleano y retorna el inverso, y el segundo NOT lo invierte de nuevo. Al final, tenemos una simple conversión a booleano. -There's a little more verbose way to do the same thing -- a built-in `Boolean` function: +Hay una manera un poco mas prolija de realizar lo mismo -- una función integrada `Boolean`: ```js run -alert( Boolean("non-empty string") ); // true -alert( Boolean(null) ); // false +alert(Boolean("cadena de texto no vacía")); // true +alert(Boolean(null)); // false ``` -The precedence of NOT `!` is the highest of all logical operators, so it always executes first, before `&&` or `||`. +La precedencia de NOT `!` es la mayor de todos los operadores lógicos, así que siempre se ejecuta primero, antes que `&&` o `||`. + pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy