chore(i8n,curriculum): processed translations (#41534)

Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
This commit is contained in:
camperbot
2021-03-20 00:31:24 -06:00
committed by GitHub
parent 0d3158d4f4
commit 4cd40f23d1
22 changed files with 284 additions and 261 deletions

View File

@ -1,6 +1,6 @@
---
id: 5cddbfd622f1a59093ec611d
title: Create a Module Script
title: Crea un módulo para scripts
challengeType: 6
forumTopicId: 301198
dashedName: create-a-module-script
@ -8,27 +8,27 @@ dashedName: create-a-module-script
# --description--
JavaScript started with a small role to play on an otherwise mostly HTML web. Today, its huge, and some websites are built almost entirely with JavaScript. In order to make JavaScript more modular, clean, and maintainable; ES6 introduced a way to easily share code among JavaScript files. This involves exporting parts of a file for use in one or more other files, and importing the parts you need, where you need them. In order to take advantage of this functionality, you need to create a script in your HTML document with a type of `module`. Heres an example:
En sus inicios, JavaScript comenzó desempeñando un pequeño rol, cuando la web estaba mayormente hecha en HTML. Hoy Javascript se ha vuelto gigante y algunos sitios web están casi completamente construidos con JavaScript. Con la finalidad de hacer JavaScript más modular, limpio y mantenible, ES6 introdujo una manera de compartir código fácilmente entre archivos JavaScript. Esto implica exportar partes de un archivo para usar en uno o más archivos, e importar las partes que necesitas donde las necesites. Para aprovechar esta funcionalidad, necesitas crear un script en tu documento HTML con un `type` de `module`. A continuación, te presentamos un ejemplo:
```html
<script type="module" src="filename.js"></script>
```
A script that uses this `module` type can now use the `import` and `export` features you will learn about in the upcoming challenges.
Un script que utilice este `module` ahora podrá utilizar las caraterísticas `import` y `export`, sobre las que aprenderás en los próximos desafíos.
# --instructions--
Add a script to the HTML document of type `module` and give it the source file of `index.js`
Agrega un script de tipo `module` al documento HTML y asígnale el archivo fuente `index.js`
# --hints--
You should create a `script` tag.
Debes crear una etiqueta `script`.
```js
assert(code.match(/<\s*script[^>]*>\s*<\/\s*script\s*>/g));
```
Your `script` tag should be of type `module`.
Tu etiqueta `input` debe tener un atributo `type` con un valor de `date`.
```js
assert(
@ -38,7 +38,7 @@ assert(
);
```
Your `script` tag should have a `src` of `index.js`.
Tu etiqueta `script` debe tener un `src` con el valor `index.js`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b8c367417b2b2512b58
title: Create an Export Fallback with export default
title: Crear un fallback de exportación con export default
challengeType: 1
forumTopicId: 301199
dashedName: create-an-export-fallback-with-export-default
@ -8,33 +8,33 @@ dashedName: create-an-export-fallback-with-export-default
# --description--
In the `export` lesson, you learned about the syntax referred to as a <dfn>named export</dfn>. This allowed you to make multiple functions and variables available for use in other files.
En la lección `export`, aprendiste sobre la sintaxis conocida como <dfn>named export</dfn>. Esto te permitió hacer disponibles múltiples funciones y variables para usar en otros archivos.
There is another `export` syntax you need to know, known as <dfn>export default</dfn>. Usually you will use this syntax if only one value is being exported from a file. It is also used to create a fallback value for a file or module.
Aquí hay otra sintaxis `export` que necesitas saber, conocida como <dfn>export default</dfn>. Usualmente utilizarás esta sintaxis, si es sólo un valor el que está siendo exportado desde un archivo. También es utilizado para crear valores fallback para un archivo o módulo.
Below are examples using `export default`:
A continuación hay ejemplos usando `export default`:
```js
// named function
export default function add(x, y) {
return x + y;
}
// anonymous function
export default function(x, y) {
return x + y;
}
```
Since `export default` is used to declare a fallback value for a module or file, you can only have one value be a default export in each module or file. Additionally, you cannot use `export default` with `var`, `let`, or `const`
La primera es una función nombrada, y la segunda es una función anónima.
Ya que `export default` es usado para declarar un valor fallback para un módulo o archivo, sólo puedes tener un valor que sea exportación por defecto en cada módulo o archivo. Además, no puedes usar `export default` con `var`, `let`, o `const`
# --instructions--
The following function should be the fallback value for the module. Please add the necessary code to do so.
La siguiente función debe ser el valor fallback para el módulo. Por favor, añade el código necesario para hacerlo.
# --hints--
Your code should use `export` fallback.
Tu código debe utilizar un `export` fallback.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b8a367417b2b2512b4e
title: Create Strings using Template Literals
title: Crea strings usando plantillas literales
challengeType: 1
forumTopicId: 301200
dashedName: create-strings-using-template-literals
@ -8,11 +8,11 @@ dashedName: create-strings-using-template-literals
# --description--
A new feature of ES6 is the <dfn>template literal</dfn>. This is a special type of string that makes creating complex strings easier.
Una nueva característica de ES6 es la <dfn>plantilla literal</dfn>. Este es un tipo especial de strings que facilita la creación de strings complejos.
Template literals allow you to create multi-line strings and to use string interpolation features to create strings.
Las plantillas literales te permiten crear strings multilínea y usar características de interpolación, para crear strings.
Consider the code below:
Fíjese en el código debajo:
```js
const person = {
@ -20,23 +20,21 @@ const person = {
age: 56
};
// Template literal with multi-line and string interpolation
const greeting = `Hello, my name is ${person.name}!
I am ${person.age} years old.`;
console.log(greeting); // prints
// Hello, my name is Zodiac Hasbro!
// I am 56 years old.
console.log(greeting);
```
A lot of things happened there. Firstly, the example uses backticks (`` ` ``), not quotes (`'` or `"`), to wrap the string. Secondly, notice that the string is multi-line, both in the code and the output. This saves inserting `\n` within strings. The `${variable}` syntax used above is a placeholder. Basically, you won't have to use concatenation with the `+` operator anymore. To add variables to strings, you just drop the variable in a template string and wrap it with `${` and `}`. Similarly, you can include other expressions in your string literal, for example `${a + b}`. This new way of creating strings gives you more flexibility to create robust strings.
La consola mostrará las cadenas `Hello, my name is Zodiac Hasbro!` y `I am 56 years old.`.
Muchas cosas han ocurrido allí. En primer lugar, el ejemplo utiliza backticks (`` ` ``), no comillas (`'` o `"`), para envolver la cadena. En segundo lugar, observe que la cadena es multi-línea tanto en el código como cuando se imprime en pantalla. Esto guarda la inserción `\n` dentro de las cadenas. La sintaxis `${variable}` utilizada anteriormente es un marcador de posición. Básicamente, ya no tendrás que utilizar concatenación con el operador `+`. Para añadir variables a las cadenas, basta con colocar la variable en una plantilla de cadena y envolverla con `${` y `}`. Del mismo modo, puedes incluir otras expresiones en tu literal de cadena, por ejemplo `${a + b}`. Esta nueva forma de crear cadenas te da mayor flexibilidad para crear cadenas robustas.
# --instructions--
Use template literal syntax with backticks to create an array of list element (`li`) strings. Each list element's text should be one of the array elements from the `failure` property on the `result` object and have a `class` attribute with the value `text-warning`. The `makeList` function should return the array of list item strings.
Usa la sintaxis de plantilla literal con comillas invertidas para crear un arreglo de cadenas de elemento lista (`li`). El texto de cada elemento de lista debe ser uno de los elementos del arreglo de la propiedad `failure` en el objeto `result` y tener un atributo `class` con el valor `text-warning`. La función `makeList` debe devolver el arreglo de cadenas de elemento lista.
Use an iterator method (any kind of loop) to get the desired output (shown below).
Utiliza un método de iteración (cualquier tipo de bucle) para obtener el resultado deseado (mostrado a continuación).
```js
[
@ -48,7 +46,7 @@ Use an iterator method (any kind of loop) to get the desired output (shown below
# --hints--
`failuresList` should be an array containing `result failure` messages.
`failuresList` debe ser un arreglo que contenga los mensajes de `result failure`.
```js
assert(
@ -56,7 +54,7 @@ assert(
);
```
`failuresList` should be equal to the specified output.
`failuresList` debe ser igual que el resultado especificado.
```js
assert(
@ -68,13 +66,13 @@ assert(
);
```
Template strings and expression interpolation should be used.
Las cadenas de plantillas y la interpolación de expresiones deben ser usadas.
```js
(getUserInput) => assert(getUserInput('index').match(/(`.*\${.*}.*`)/));
```
An iterator should be used.
Debe utilizarse un iterador.
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 587d7b87367417b2b2512b41
title: Declare a Read-Only Variable with the const Keyword
title: Declara una variable de sólo lectura con la palabra clave const
challengeType: 1
forumTopicId: 301201
dashedName: declare-a-read-only-variable-with-the-const-keyword
@ -8,44 +8,46 @@ dashedName: declare-a-read-only-variable-with-the-const-keyword
# --description--
The keyword `let` is not the only new way to declare variables. In ES6, you can also declare variables using the `const` keyword.
La palabra clave `let` no es la única manera nueva de declarar variables. En ES6, tú puedes declarar variables usando la palabra clave `const`.
`const` has all the awesome features that `let` has, with the added bonus that variables declared using `const` are read-only. They are a constant value, which means that once a variable is assigned with `const`, it cannot be reassigned.
`const` tiene todas las características increíbles que tiene `let`, con el bono añadido de que las variables declaradas usando `const` son de solo lectura. Son un valor constante, lo que significa que una vez que una variable es asignada con `const`, no se puede reasignar.
```js
const FAV_PET = "Cats";
FAV_PET = "Dogs"; // returns error
FAV_PET = "Dogs";
```
As you can see, trying to reassign a variable declared with `const` will throw an error. You should always name variables you don't want to reassign using the `const` keyword. This helps when you accidentally attempt to reassign a variable that is meant to stay constant. A common practice when naming constants is to use all uppercase letters, with words separated by an underscore.
La consola mostrará un error debido a la reasignación del valor de `FAV_PET`.
**Note:** It is common for developers to use uppercase variable identifiers for immutable values and lowercase or camelCase for mutable values (objects and arrays). In a later challenge you will see an example of a lowercase variable identifier being used for an array.
Como puedes ver, intentar reasignar una variable declarada con `const` arrojará un error. Siempre debes nombrar variables que no quieras reasignar usando la palabra clave `const`. Esto ayuda cuando intentas reasignar accidentalmente una variable que está destinada a permanecer constante. Una práctica común al nombrar constantes es utilizar todas las letras en mayúsculas, con palabras separadas por un guion bajo.
**Nota:** Es común que los desarrolladores usen identificadores de variables en mayúsculas para valores inmutables y minúsculas o camelCase para valores mutables (objetos y arreglos). En un desafío posterior verás un ejemplo de un identificador de variable en minúsculas que se usa para un arreglo.
# --instructions--
Change the code so that all variables are declared using `let` or `const`. Use `let` when you want the variable to change, and `const` when you want the variable to remain constant. Also, rename variables declared with `const` to conform to common practices, meaning constants should be in all caps.
Cambia el código para que todas las variables sean declaradas usando `let` o `const`. Usa `let` cuando quieras que la variable cambie y `const` cuando quieras que la variable permanezca constante. Además, renombra las variables declaradas con `const` para adaptarse a las prácticas comunes, lo que significa que las constantes deben estar todas en mayúsculas.
# --hints--
`var` should not exist in your code.
`var` no debe existir en tu código.
```js
(getUserInput) => assert(!getUserInput('index').match(/var/g));
```
`SENTENCE` should be a constant variable declared with `const`.
`SENTENCE` debe ser una variable constante declarada con `const`.
```js
(getUserInput) => assert(getUserInput('index').match(/(const SENTENCE)/g));
```
`i` should be declared with `let`.
`i` debe ser declarada con `let`.
```js
(getUserInput) => assert(getUserInput('index').match(/(let i)/g));
```
`console.log` should be changed to print the `SENTENCE` variable.
`console.log` debe cambiarse para imprimir la variable `SENTENCE`.
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 587d7b87367417b2b2512b3f
title: Explore Differences Between the var and let Keywords
title: Explora las diferencias entre las palabras claves var y let
challengeType: 1
forumTopicId: 301202
dashedName: explore-differences-between-the-var-and-let-keywords
@ -8,49 +8,52 @@ dashedName: explore-differences-between-the-var-and-let-keywords
# --description--
One of the biggest problems with declaring variables with the `var` keyword is that you can overwrite variable declarations without an error.
Uno de los grandes problemas con la declaración de variables, usando la palabra clave `var`, es que tu puedes sobrescribir declaraciones de variables sin un error.
```js
var camper = 'James';
var camper = 'David';
console.log(camper);
// logs 'David'
```
As you can see in the code above, the `camper` variable is originally declared as `James` and then overridden to be `David`. In a small application, you might not run into this type of problem, but when your code becomes larger, you might accidentally overwrite a variable that you did not intend to overwrite. Because this behavior does not throw an error, searching and fixing bugs becomes more difficult.
A new keyword called `let` was introduced in ES6 to solve this potential issue with the `var` keyword. If you were to replace `var` with `let` in the variable declarations of the code above, the result would be an error.
Aquí la consola mostrará la cadena de caracteres `David`.
Como puedes ver en el código anterior, la variable `camper` es originalmente declarada como `James` luego de anularse pasa a ser `David`. En una aplicación pequeña, puede que no te topes con este tipo de problema, pero cuando tu código se vuelve mas grande, puede que accidentalmente sobrescribas una variable que no pretendías sobrescribir. Debido a que este comportamiento no arroja un error, buscar y corregir errores se vuelve mas difícil.
Una nueva palabra clave llamada `let` que fue introducida en ES6 para resolver este posible problema con la palabra clave `var`. Si reemplazas `var` por `let` en las declaraciones de variables del código anterior, el resultado será un error.
```js
let camper = 'James';
let camper = 'David'; // throws an error
let camper = 'David';
```
This error can be seen in the console of your browser. So unlike `var`, when using `let`, a variable with the same name can only be declared once. Note the `"use strict"`. This enables Strict Mode, which catches common coding mistakes and "unsafe" actions. For instance:
Este error se puede ver en la consola de tu navegador. Así que a diferencia de `var`, al usar `let`, una variable con el mismo nombre solo puede declararse una vez. Toma en cuenta el `"use strict"` (uso estricto). Esto habilita el modo estricto, el cual captura errores comunes de programación y acciones "inseguras". Por ejemplo:
```js
"use strict";
x = 3.14; // throws an error because x is not declared
x = 3.14;
```
Esto mostrará el error `x is not defined`.
# --instructions--
Update the code so it only uses the `let` keyword.
Actualiza el código para que solo utilice la palabra clave `let`.
# --hints--
`var` should not exist in the code.
`var` no debe existir en el código.
```js
(getUserInput) => assert(!getUserInput('index').match(/var/g));
```
`catName` should be `Oliver`.
`catName` debe ser la cadena `Oliver`.
```js
assert(catName === 'Oliver');
```
`quote` should be `"Oliver says Meow!"`
`quote` debe ser la cadena `Oliver says Meow!`
```js
assert(quote === 'Oliver says Meow!');

View File

@ -1,6 +1,6 @@
---
id: 587d7b87367417b2b2512b42
title: Mutate an Array Declared with const
title: Muta un arreglo declarado con const
challengeType: 1
forumTopicId: 301206
dashedName: mutate-an-array-declared-with-const
@ -8,40 +8,42 @@ dashedName: mutate-an-array-declared-with-const
# --description--
The `const` declaration has many use cases in modern JavaScript.
La declaración `const` tiene muchos casos de uso, en el actual JavaScript.
Some developers prefer to assign all their variables using `const` by default, unless they know they will need to reassign the value. Only in that case, they use `let`.
Algunos desarrolladores, prefieren asignar todas sus variables utilizando `const` por defecto, salvo que sepan que necesitarán reasignar el valor. Sólo en ese caso, utilizan `let`.
However, it is important to understand that objects (including arrays and functions) assigned to a variable using `const` are still mutable. Using the `const` declaration only prevents reassignment of the variable identifier.
Sin embargo, es importante comprender que los objetos (incluyendo arreglos y funciones), asignados a una variable usando `const` siguen siendo mutables. Usar la declaración `const` sólo previene la reasignación del identificador de una variable.
```js
const s = [5, 6, 7];
s = [1, 2, 3]; // throws error, trying to assign a const
s[2] = 45; // works just as it would with an array declared with var or let
console.log(s); // returns [5, 6, 45]
s = [1, 2, 3];
s[2] = 45;
console.log(s);
```
As you can see, you can mutate the object `[5, 6, 7]` itself and the variable `s` will still point to the altered array `[5, 6, 45]`. Like all arrays, the array elements in `s` are mutable, but because `const` was used, you cannot use the variable identifier `s` to point to a different array using the assignment operator.
`s = [1, 2, 3]` resultará en un error. El `console.log` mostrará el valor `[5, 6, 45]`.
Como puedes ver, puedes mutar el objeto `[5, 6, 7]` en sí mismo y la variable `s` seguirá apuntado al arreglo alterado `[5, 6, 45]`. Como en todos los arreglos, los elementos del arreglo en `s` son mutables, pero debido a que se utilizó `const`, no puedes utilizar el identificador de la variable `s` para apuntar a un arreglo diferente usando el operador de asignación.
# --instructions--
An array is declared as `const s = [5, 7, 2]`. Change the array to `[2, 5, 7]` using various element assignments.
Un arreglo es declarado como `const s = [5, 7, 2]`. Cambia el arreglo a `[2, 5, 7]` utilizando varias asignaciones de elementos.
# --hints--
You should not replace `const` keyword.
No debes reemplazar la palabra clave `const`.
```js
(getUserInput) => assert(getUserInput('index').match(/const/g));
```
`s` should be a constant variable (by using `const`).
`s` debe ser una variable constante (utilizando `const`).
```js
(getUserInput) => assert(getUserInput('index').match(/const\s+s/g));
```
You should not change the original array declaration.
No debes cambiar la declaración original del arreglo.
```js
(getUserInput) =>
@ -52,7 +54,7 @@ You should not change the original array declaration.
);
```
`s` should be equal to `[2, 5, 7]`.
`s` debe ser igual a `[2, 5, 7]`.
```js
assert.deepEqual(s, [2, 5, 7]);

View File

@ -1,6 +1,6 @@
---
id: 598f48a36c8c40764b4e52b3
title: Prevent Object Mutation
title: Prevenir la mutación del objeto
challengeType: 1
forumTopicId: 301207
dashedName: prevent-object-mutation
@ -8,9 +8,9 @@ dashedName: prevent-object-mutation
# --description--
As seen in the previous challenge, `const` declaration alone doesn't really protect your data from mutation. To ensure your data doesn't change, JavaScript provides a function `Object.freeze` to prevent data mutation.
Como se vio en el desafío anterior, la declaración `const` por sí sola no protege la información de la mutación. Para asegurar que tu información no cambie, JavaScript provee una funcn `Object.freeze` para prevenir la mutación de datos.
Once the object is frozen, you can no longer add, update, or delete properties from it. Any attempt at changing the object will be rejected without an error.
Una vez que el objeto está congelado, ya no puedes agregar, actualizar o borrar propiedades alojadas en él. Cualquier intento de cambiar el objeto será rechazado sin ningún error.
```js
let obj = {
@ -18,32 +18,33 @@ let obj = {
review:"Awesome"
};
Object.freeze(obj);
obj.review = "bad"; // will be ignored. Mutation not allowed
obj.newProp = "Test"; // will be ignored. Mutation not allowed
obj.review = "bad";
obj.newProp = "Test";
console.log(obj);
// { name: "FreeCodeCamp", review:"Awesome"}
```
Las asignaciones `obj.review` y `obj.newProp` provocarán errores y la consola mostrará el valor `{ name: "FreeCodeCamp", review: "Awesome" }`.
# --instructions--
In this challenge you are going to use `Object.freeze` to prevent mathematical constants from changing. You need to freeze the `MATH_CONSTANTS` object so that no one is able to alter the value of `PI`, add, or delete properties.
En este desafío vas a utilizar `Object.freeze` para prevenir el cambio de constantes matemáticas. Necesitas congelar el objeto `MATH_CONSTANTS` para que nadie pueda alterar el valor de `PI`, añadir o borrar propiedades.
# --hints--
You should not replace `const` keyword.
No debes reemplazar la palabra clave `const`.
```js
(getUserInput) => assert(getUserInput('index').match(/const/g));
```
`MATH_CONSTANTS` should be a constant variable (by using `const`).
`MATH_CONSTANTS` debe ser una variable constante (utilizando `const`).
```js
(getUserInput) =>
assert(getUserInput('index').match(/const\s+MATH_CONSTANTS/g));
```
You should not change original `MATH_CONSTANTS`.
No debes modificar la declaración original de `MATH_CONSTANTS`.
```js
(getUserInput) =>
@ -54,7 +55,7 @@ You should not change original `MATH_CONSTANTS`.
);
```
`PI` should equal `3.14`.
`PI` debe ser igual a `3.14`.
```js
assert(PI === 3.14);

View File

@ -1,6 +1,6 @@
---
id: 587d7b88367417b2b2512b46
title: Set Default Parameters for Your Functions
title: Establece parámetros por defecto para tus funciones
challengeType: 1
forumTopicId: 301209
dashedName: set-default-parameters-for-your-functions
@ -8,38 +8,40 @@ dashedName: set-default-parameters-for-your-functions
# --description--
In order to help us create more flexible functions, ES6 introduces <dfn>default parameters</dfn> for functions.
Para ayudarnos a crear funciones más flexibles, ES6 introduce <dfn>parametros por defecto</dfn> para funciones.
Check out this code:
Echa un vistazo, al siguente código:
```js
const greeting = (name = "Anonymous") => "Hello " + name;
console.log(greeting("John")); // Hello John
console.log(greeting()); // Hello Anonymous
console.log(greeting("John"));
console.log(greeting());
```
The default parameter kicks in when the argument is not specified (it is undefined). As you can see in the example above, the parameter `name` will receive its default value `"Anonymous"` when you do not provide a value for the parameter. You can add default values for as many parameters as you want.
La consola mostrará las cadenas `Hello John` y `Hello Anonymous`.
El parámetro por defecto entra en juego cuando el argumento no es especificado (es indefinido). Como puedes ver en el ejemplo anterior, el parámetro `name` recibirá su valor por defecto `Anonymous` cuando no proveas un valor para el parámetro. Puede agregar valores por defecto para tantos parámetros como desees.
# --instructions--
Modify the function `increment` by adding default parameters so that it will add 1 to `number` if `value` is not specified.
Modifica la funcn `increment` agregando parámetros por defecto para que sume 1 a `number` si `value` no se especifica.
# --hints--
The result of `increment(5, 2)` should be `7`.
El resultado de `increment(5, 2)` debe ser `7`.
```js
assert(increment(5, 2) === 7);
```
The result of `increment(5)` should be `6`.
El resultado de `increment(5)` debe ser `6`.
```js
assert(increment(5) === 6);
```
A default parameter value of `1` should be used for `value`.
Un valor de parámetro por defecto de `1` debe utilizarse para `value`.
```js
assert(code.match(/value\s*=\s*1/g));

View File

@ -1,6 +1,6 @@
---
id: 587d7b87367417b2b2512b43
title: Use Arrow Functions to Write Concise Anonymous Functions
title: Usa funciones flecha para escribir funciones anónimas de manera breve
challengeType: 1
forumTopicId: 301211
dashedName: use-arrow-functions-to-write-concise-anonymous-functions
@ -8,9 +8,9 @@ dashedName: use-arrow-functions-to-write-concise-anonymous-functions
# --description--
In JavaScript, we often don't need to name our functions, especially when passing a function as an argument to another function. Instead, we create inline functions. We don't need to name these functions because we do not reuse them anywhere else.
En JavaScript, usualmente no necesitas nombrar tus funciones, especialmente cuando se pasa una función como argumento a otra función. En su lugar, creamos funciones inline (en línea). No necesitamos nombrar estas funciones porque no las reutilizamos en otro lugar.
To achieve this, we often use the following syntax:
Para lograr esto, por lo general se usa la siguiente sintaxis:
```js
const myFunc = function() {
@ -19,7 +19,7 @@ const myFunc = function() {
}
```
ES6 provides us with the syntactic sugar to not have to write anonymous functions this way. Instead, you can use **arrow function syntax**:
ES6 nos proporciona el azúcar sintáctico, para no tener que escribir funciones anónimas de este modo. En su lugar, puedes usar la **sintaxis de función flecha**:
```js
const myFunc = () => {
@ -28,45 +28,45 @@ const myFunc = () => {
}
```
When there is no function body, and only a return value, arrow function syntax allows you to omit the keyword `return` as well as the brackets surrounding the code. This helps simplify smaller functions into one-line statements:
Cuando la función no posee cuerpo y sólo tiene un valor de retorno, la sintaxis de "función de flecha", te permite omitir la palabra clave `return`, así como los corchetes que rodean el código. Esto ayuda a simplificar las funciones más pequeñas en sentencias de una sola línea:
```js
const myFunc = () => "value";
```
This code will still return the string `value` by default.
Este código todavía retorna el string `value` por defecto.
# --instructions--
Rewrite the function assigned to the variable `magic` which returns a `new Date()` to use arrow function syntax. Also, make sure nothing is defined using the keyword `var`.
Reescribe la funcn asignada a la variable `magic`, la cual devuelve una `new Date()`, utilizando la sintaxis de función flecha. Además, asegúrate de que nada esté definido usando la palabra clave `var`.
# --hints--
User should replace `var` keyword.
Debes reemplazar la palabra clave `var`.
```js
(getUserInput) => assert(!getUserInput('index').match(/var/g));
```
`magic` should be a constant variable (by using `const`).
`magic` debe ser una variable constante (utilizando `const`).
```js
(getUserInput) => assert(getUserInput('index').match(/const\s+magic/g));
```
`magic` should be a `function`.
`magic` debe ser una función (`function`).
```js
assert(typeof magic === 'function');
```
`magic()` should return correct date.
`magic()` debe devolver la fecha correcta.
```js
assert(magic().setHours(0, 0, 0, 0) === new Date().setHours(0, 0, 0, 0));
```
`function` keyword should not be used.
La palabra clave `function` no debe ser usada.
```js
(getUserInput) => assert(!getUserInput('index').match(/function/g));

View File

@ -1,6 +1,6 @@
---
id: 587d7b8b367417b2b2512b53
title: Use class Syntax to Define a Constructor Function
title: Usa sintaxis de clases para definir una función constructora
challengeType: 1
forumTopicId: 301212
dashedName: use-class-syntax-to-define-a-constructor-function
@ -8,11 +8,11 @@ dashedName: use-class-syntax-to-define-a-constructor-function
# --description--
ES6 provides a new syntax to create objects, using the <dfn>class</dfn> keyword.
ES6 proporciona una nueva sintaxis para crear objetos, usando la palabra clave <dfn>class</dfn>.
It should be noted that the `class` syntax is just syntax, and not a full-fledged class-based implementation of an object-oriented paradigm, unlike in languages such as Java, Python, Ruby, etc.
Debemos notar que la sintaxis `class` es sólo sintaxis, y no una implementación completa basada en clases de un paradigma orientado a objetos, a diferencia de lenguajes como Java, Python, Ruby, etc.
In ES5, we usually define a constructor function and use the `new` keyword to instantiate an object.
En ES5, normalmente definimos una función `constructor` y usamos la palabra clave `new` para instanciar un objeto.
```js
var SpaceShuttle = function(targetPlanet){
@ -21,7 +21,7 @@ var SpaceShuttle = function(targetPlanet){
var zeus = new SpaceShuttle('Jupiter');
```
The `class` syntax simply replaces the constructor function creation:
La sintaxis `class` simplemente reemplaza la creación de la función `constructor`:
```js
class SpaceShuttle {
@ -32,21 +32,21 @@ class SpaceShuttle {
const zeus = new SpaceShuttle('Jupiter');
```
It should be noted that the `class` keyword declares a new function, to which a constructor is added. This constructor is invoked when `new` is called to create a new object.
**Notes:**
Debe tenerse en cuenta que la palabra clave `class` declara una nueva función, a la cual se añade un constructor. Este constructor se invoca cuando `new` es llamado para crear un nuevo objeto.
- UpperCamelCase should be used by convention for ES6 class names, as in `SpaceShuttle` used above.
- The constructor method is a special method for creating and initializing an object created with a class. You will learn more about it in the Object Oriented Programming section of the JavaScript Algorithms And Data Structures Certification.
**Nota:** UpperCamelCase debe ser utilizado por convención para nombres de clase en ES6, como `SpaceShuttle` fue usado arriba.
El método `constructor` es un método especial para crear e inicializar un objeto creado con una clase. Aprenderás más sobre ello en la sección de Programación Orientada a Objetos de la Certificación en Algoritmos de JavaScript y Estructuras de Datos.
# --instructions--
Use the `class` keyword and write a constructor to create the `Vegetable` class.
Usa la palabra clave `class` y escribe un `constructor` para crear la clase `Vegetable`.
The `Vegetable` class allows you to create a vegetable object with a property `name` that gets passed to the constructor.
La clase `Vegetable` te permite crear un objeto vegetal con una propiedad `name` que es pasada al `constructor`.
# --hints--
`Vegetable` should be a `class` with a defined `constructor` method.
`Vegetable` debe ser una clase (`class`) con un método `constructor` definido.
```js
assert(
@ -54,13 +54,13 @@ assert(
);
```
`class` keyword should be used.
La palabra clave `class` debe ser utilizada.
```js
assert(code.match(/class/g));
```
`Vegetable` should be able to be instantiated.
`Vegetable` debe ser capaz de ser instanciada.
```js
assert(() => {
@ -69,7 +69,7 @@ assert(() => {
});
```
`carrot.name` should return `carrot`.
`carrot.name` debe devolver `carrot`.
```js
assert(carrot.name == 'carrot');

View File

@ -1,6 +1,6 @@
---
id: 587d7b8c367417b2b2512b54
title: Use getters and setters to Control Access to an Object
title: Utiliza getters (accesores) y setters (mutadores) para controlar el acceso a un objeto
challengeType: 1
forumTopicId: 301220
dashedName: use-getters-and-setters-to-control-access-to-an-object
@ -8,13 +8,13 @@ dashedName: use-getters-and-setters-to-control-access-to-an-object
# --description--
You can obtain values from an object and set the value of a property within an object.
Puedes obtener valores de un objeto y establecer el valor de una propiedad dentro de un objeto.
These are classically called <dfn>getters</dfn> and <dfn>setters</dfn>.
Estas operaciones clásicamente se llaman <dfn>getters</dfn> y <dfn>setters</dfn>.
Getter functions are meant to simply return (get) the value of an object's private variable to the user without the user directly accessing the private variable.
Las funciones getter están destinadas a simplemente devolver (get) el valor de la variable privada de un objeto al usuario sin que el usuario acceda directamente a la variable privada.
Setter functions are meant to modify (set) the value of an object's private variable based on the value passed into the setter function. This change could involve calculations, or even overwriting the previous value completely.
Las funciones setter están destinadas a modificar (set) el valor de la variable privada de un objeto basado en el valor pasado a la función setter. Este cambio podría implicar cálculos, o incluso sobrescribir completamente el valor anterior.
```js
class Book {
@ -31,30 +31,34 @@ class Book {
}
}
const novel = new Book('anonymous');
console.log(novel.writer); // anonymous
console.log(novel.writer);
novel.writer = 'newAuthor';
console.log(novel.writer); // newAuthor
console.log(novel.writer);
```
Notice the syntax used to invoke the getter and setter. They do not even look like functions. Getters and setters are important because they hide internal implementation details. **Note:** It is convention to precede the name of a private variable with an underscore (`_`). However, the practice itself does not make a variable private.
La consola mostrará las cadenas `anonymous` y `newAuthor`.
Ten en cuenta la sintaxis usada para invocar el getter y el setter. Ni siquiera se ven como funciones. Los getter y los setter son importantes porque ocultan los detalles internos de la implementación.
**Nota:** Es convención preceder el nombre de una variable privada con un guión bajo (`_`). Sin embargo, la práctica en sí misma no hace una variable privada.
# --instructions--
Use the `class` keyword to create a Thermostat class. The constructor accepts a Fahrenheit temperature.
Utiliza la palabra clave `class` para crear una clase `Thermostat`. El `constructor` acepta una temperatura Fahrenheit.
In the class, create a `getter` to obtain the temperature in Celsius and a `setter` to set the temperature in Celsius.
En la clase, crea un `getter` para obtener la temperatura en Celsius y un `setter` para ajustar la temperatura en Celsius.
Remember that `C = 5/9 * (F - 32)` and `F = C * 9.0 / 5 + 32`, where `F` is the value of temperature in Fahrenheit, and `C` is the value of the same temperature in Celsius.
Recuerda que `C = 5/9 * (F - 32)` y `F = C * 9.0 / 5 + 32` donde `F` es el valor de la temperatura en Fahrenheit y `C` es el valor de la misma temperatura en Celsius.
**Note:** When you implement this, you will track the temperature inside the class in one scale, either Fahrenheit or Celsius.
**Nota:** Cuando implementes esto, rastrearás la temperatura dentro de la clase en una escala, ya sea Fahrenheit o Celsius.
This is the power of a getter and a setter. You are creating an API for another user, who can get the correct result regardless of which one you track.
Este es el poder de un getter y un setter. Estás creando una API para otro usuario, que puede obtener el resultado correcto independientemente de cuál estés rastreando.
In other words, you are abstracting implementation details from the user.
En otras palabras, estás abstrayendo los detalles de la implementación del usuario.
# --hints--
`Thermostat` should be a `class` with a defined `constructor` method.
`Thermostat` debe ser una `class` con un método `constructor` definido.
```js
assert(
@ -63,13 +67,13 @@ assert(
);
```
`class` keyword should be used.
La palabra clave `class` debe ser utilizada.
```js
assert(code.match(/class/g));
```
`Thermostat` should be able to be instantiated.
`Thermostat` debe ser capaz de ser instanciado.
```js
assert(
@ -80,7 +84,7 @@ assert(
);
```
When instantiated with a Fahrenheit value, `Thermostat` should set the correct temperature.
Cuando se crea una instancia con un valor de Fahrenheit, `Thermostat` debe establecer la temperatura (`temperature`) correcta.
```js
assert(
@ -91,7 +95,7 @@ assert(
);
```
A `getter` should be defined.
Un `getter` debe ser definido.
```js
assert(
@ -105,7 +109,7 @@ assert(
);
```
A `setter` should be defined.
Un `setter` debe ser definido.
```js
assert(
@ -119,7 +123,7 @@ assert(
);
```
Calling the `setter` with a Celsius value should set the temperature.
Llamar al `setter` con un valor Celsius debe establecer `temperature`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b88367417b2b2512b44
title: Write Arrow Functions with Parameters
title: Escribe funciones flecha con parámetros
challengeType: 1
forumTopicId: 301223
dashedName: write-arrow-functions-with-parameters
@ -8,48 +8,49 @@ dashedName: write-arrow-functions-with-parameters
# --description--
Just like a regular function, you can pass arguments into an arrow function.
Al igual que una función regular, puedes pasar argumentos a una función flecha.
```js
// doubles input value and returns it
const doubler = (item) => item * 2;
doubler(4); // returns 8
doubler(4);
```
If an arrow function has a single parameter, the parentheses enclosing the parameter may be omitted.
`doubler(4)` devolvería el valor `8`.
Si una función flecha tiene un solo parámetro, los paréntesis que encierran el parámetro pueden ser omitidos.
```js
// the same function, without the parameter parentheses
const doubler = item => item * 2;
```
It is possible to pass more than one argument into an arrow function.
Es posible pasar más de un argumento a una función flecha.
```js
// multiplies the first input value by the second and returns it
const multiplier = (item, multi) => item * multi;
multiplier(4, 2); // returns 8
multiplier(4, 2);
```
`multiplier(4, 2)` devolverá el valor `8`.
# --instructions--
Rewrite the `myConcat` function which appends contents of `arr2` to `arr1` so that the function uses arrow function syntax.
Reescribe la función `myConcat` que añade el contenido de `arr2` a `arr1` para que la funcn use la sintaxis de función flecha.
# --hints--
You should replace the `var` keyword.
Debes reemplazar la palabra clave `var`.
```js
(getUserInput) => assert(!getUserInput('index').match(/var/g));
```
`myConcat` should be a constant variable (by using `const`).
`myConcat` debe ser una variable constante (utilizando `const`).
```js
(getUserInput) => assert(getUserInput('index').match(/const\s+myConcat/g));
```
`myConcat` should be an arrow function with two parameters
`myConcat` debe ser una función de flecha con dos parámetros
```js
assert(
@ -58,13 +59,13 @@ assert(
);
```
`myConcat()` should return `[1, 2, 3, 4, 5]`.
`myConcat()` debe devolver `[1, 2, 3, 4, 5]`.
```js
assert.deepEqual(myConcat([1, 2], [3, 4, 5]), [1, 2, 3, 4, 5]);
```
`function` keyword should not be used.
La palabra clave `function` no debe ser usada.
```js
(getUserInput) => assert(!getUserInput('index').match(/function/g));

View File

@ -1,6 +1,6 @@
---
id: 587d7b8b367417b2b2512b50
title: Write Concise Declarative Functions with ES6
title: Escribe funciones declarativas concisas con ES6
challengeType: 1
forumTopicId: 301224
dashedName: write-concise-declarative-functions-with-es6
@ -8,7 +8,7 @@ dashedName: write-concise-declarative-functions-with-es6
# --description--
When defining functions within objects in ES5, we have to use the keyword `function` as follows:
Al definir funciones dentro de objetos en ES5, tenemos que utilizar la palabra clave `function` de la siguiente manera:
```js
const person = {
@ -19,7 +19,7 @@ const person = {
};
```
With ES6, You can remove the `function` keyword and colon altogether when defining functions in objects. Here's an example of this syntax:
Con ES6, puedes eliminar la palabra clave `function` y los dos puntos al definir funciones en objetos. Aquí hay un ejemplo de esta sintaxis:
```js
const person = {
@ -32,17 +32,17 @@ const person = {
# --instructions--
Refactor the function `setGear` inside the object `bicycle` to use the shorthand syntax described above.
Refactoriza la funcn `setGear` dentro del objeto `bicycle` para que utilice la sintaxis abreviada descrita arriba.
# --hints--
Traditional function expression should not be used.
La expresión tradicional "function" no debe ser utilizada.
```js
(getUserInput) => assert(!__helpers.removeJSComments(code).match(/function/));
```
`setGear` should be a declarative function.
`setGear` debe ser una función declarativa.
```js
assert(
@ -50,7 +50,7 @@ assert(
);
```
`bicycle.setGear(48)` should change the `gear` value to 48.
`bicycle.setGear(48)` debe cambiar el valor de `gear` a 48.
```js
assert(new bicycle.setGear(48).gear === 48);

View File

@ -1,6 +1,6 @@
---
id: 587d7b8a367417b2b2512b4f
title: Write Concise Object Literal Declarations Using Object Property Shorthand
title: Escribe declaraciones concisas de objecto literales usando la abreviatura de propiedad de objeto
challengeType: 1
forumTopicId: 301225
dashedName: write-concise-object-literal-declarations-using-object-property-shorthand
@ -8,9 +8,9 @@ dashedName: write-concise-object-literal-declarations-using-object-property-shor
# --description--
ES6 adds some nice support for easily defining object literals.
ES6 añade un buen soporte para definir fácilmente objetos literales.
Consider the following code:
Considera el siguiente código:
```js
const getMousePosition = (x, y) => ({
@ -19,7 +19,7 @@ const getMousePosition = (x, y) => ({
});
```
`getMousePosition` is a simple function that returns an object containing two properties. ES6 provides the syntactic sugar to eliminate the redundancy of having to write `x: x`. You can simply write `x` once, and it will be converted to`x: x` (or something equivalent) under the hood. Here is the same function from above rewritten to use this new syntax:
`getMousePosition` es una función simple que devuelve un objeto que contiene dos propiedades. ES6 proporciona el azúcar sintáctico para eliminar la redundancia de tener que escribir `x: x`. Puedes simplemente escribir `x` una vez, y se convertirá en `x: x` (o algo equivalente) de la nada. Aquí está la misma función de arriba reescrita para usar esta nueva sintaxis:
```js
const getMousePosition = (x, y) => ({ x, y });
@ -27,11 +27,11 @@ const getMousePosition = (x, y) => ({ x, y });
# --instructions--
Use object property shorthand with object literals to create and return an object with `name`, `age` and `gender` properties.
Utiliza la abreviatura de propiedad de objeto con objetos literales para crear y devolver un objeto con las propiedades `name`, `age` y `gender`.
# --hints--
`createPerson("Zodiac Hasbro", 56, "male")` should return `{name: "Zodiac Hasbro", age: 56, gender: "male"}`.
`createPerson("Zodiac Hasbro", 56, "male")` debe devolver `{name: "Zodiac Hasbro", age: 56, gender: "male"}`.
```js
assert.deepEqual(
@ -40,7 +40,7 @@ assert.deepEqual(
);
```
Your code should not use `key:value`.
Tu código no debe usar `key:value`.
```js
(getUserInput) => assert(!getUserInput('index').match(/:/g));