From 8b1ce1675e71e189ab7c8cdf3a1eb4a08819e21a Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Thu, 21 May 2020 03:07:52 -0300 Subject: [PATCH 1/6] =?UTF-8?q?art+task+sol=20c/base=20EN=204=20a=C3=B1os?= =?UTF-8?q?=20mas=20nueva?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1-string-new-property/solution.md | 26 ++--- .../1-string-new-property/task.md | 6 +- .../01-primitives-methods/article.md | 100 +++++++++--------- 3 files changed, 63 insertions(+), 69 deletions(-) diff --git a/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md b/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md index a169f7769..0f22f5ef8 100644 --- a/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md +++ b/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md @@ -1,5 +1,5 @@ -Try running it: +Prueba ejecutándolo: ```js run let str = "Hello"; @@ -9,23 +9,17 @@ str.test = 5; // (*) alert(str.test); ``` -There may be two kinds of result: -1. `undefined` -2. An error. +Depende de si usas el modo estricto "use strict" o no, el resultado será: +1. `undefined` (sin strict mode) +2. Un error. (strict mode) -Why? Let's replay what's happening at line `(*)`: +¿Por qué? Repasemos lo que ocurre en la línea `(*)`: -1. When a property of `str` is accessed, a "wrapper object" is created. -2. The operation with the property is carried out on it. So, the object gets the `test` property. -3. The operation finishes and the "wrapper object" disappears. +1. Cuando se accede a una propiedad de `str`, un "wrapper object" es creado. +2. Con modo estricto, tratar de alterarlo produce error. +3. Sin modo estricto, la operación es llevada a cabo y el objeto obtiene la propiedad `test`, pero después de ello el "wrapper object" desaparece, entonces en la última linea `str` queda sin rastros de la propiedad. -So, on the last line, `str` has no trace of the property. A new wrapper object for every object operation on a string. +**Este ejemlplo claramente muestra que los tipos primitivos no son objetos.** -Some browsers though may decide to further limit the programmer and disallow to assign properties to primitives at all. That's why in practice we can also see errors at line `(*)`. It's a little bit farther from the specification though. - -**This example clearly shows that primitives are not objects.** - -They just can not store data. - -All property/method operations are performed with the help of temporary objects. +Ellos no pueden almacenar datos adicionales. diff --git a/1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md b/1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md index 50c781ea5..d7ede9a44 100644 --- a/1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md +++ b/1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md @@ -2,10 +2,10 @@ importance: 5 --- -# Can I add a string property? +# ¿Puedo agregar una propiedad a un string? -Consider the following code: +Considera el siguiente código: ```js let str = "Hello"; @@ -15,4 +15,4 @@ str.test = 5; alert(str.test); ``` -How do you think, will it work? What will be shown? +Qué piensas, ¿funcionará? ¿Que mostrará? diff --git a/1-js/05-data-types/01-primitives-methods/article.md b/1-js/05-data-types/01-primitives-methods/article.md index a2dcceb19..8ea4af61f 100644 --- a/1-js/05-data-types/01-primitives-methods/article.md +++ b/1-js/05-data-types/01-primitives-methods/article.md @@ -1,22 +1,22 @@ -# Methods of primitives +# Métodos en tipos primitivos -JavaScript allows us to work with primitives (strings, numbers, etc.) as if they were objects. +JavaScript nos permite trabajar con tipos primitivos (string, number, etc) como si fueran objetos. -They also provide methods to call as such. We will study those soon, but first we'll see how it works because, of course, primitives are not objects (and here we will make it even clearer). +Como los objetos, los tipos primitivos también brindan métodos para ser llamados. Los estudiaremos pronto, pero primero veamos cómo trabajan porque, por supuesto, los primitivos no son objetos. (y aquí lo haremos aún más evidente). -Let's look at the key distinctions between primitives and objects. +Veamos las diferencias clave entre primitivos y objetos. -A primitive +Un primitivo -- Is a value of a primitive type. -- There are 6 primitive types: `string`, `number`, `boolean`, `symbol`, `null` and `undefined`. +- Es un valor de tipo primitivo. +- Hay 7 tipos primitivos: `string`, `number`, `bigint`, `boolean`, `symbol`, `null` y `undefined`. -An object +Un objeto -- Is capable of storing multiple values as properties. -- Can be created with `{}`, for instance: `{name: "John", age: 30}`. There are other kinds of objects in JavaScript; functions, for example, are objects. +- Es capaz de almacenar múltiples valores como propiedades. +- Puede ser creado con `{}`. Ejemplo: `{name: "John", age: 30}`. Hay otras clases de objetos en JavaScript; las funciones, por ejemplo, son objetos. -One of the best things about objects is that we can store a function as one of its properties. +Una de las mejores cosas de los objetos es que podemos almacenar una función como una de sus propiedades. ```js run let john = { @@ -29,32 +29,32 @@ let john = { john.sayHi(); // Hi buddy! ``` -So here we've made an object `john` with the method `sayHi`. +Aquí hemos creado una función `john` con el método `sayHi` (saludar). -Many built-in objects already exist, such as those that work with dates, errors, HTML elements, etc. They have different properties and methods. +Ya existen muchos objetos integrados al lenguaje, como los que trabajan con fechas, errores, elementos HTML, etc. Ellos tienen diferentes propiedades y métodos. -But, these features come with a cost! +¡Pero estas características tienen un precio! -Objects are "heavier" than primitives. They require additional resources to support the internal machinery. But as properties and methods are very useful in programming, JavaScript engines try to optimize them to reduce the additional burden. +Los objetos son más "pesados" que los primitivos. Ellos requieren recursos adicionales para soportar su maquinaria interna. Pero como las propiedades y los métodos son tan útiles en la programación, los motores JavaScript tratan de optimizarlos para reducir su carga adiional. -## A primitive as an object +## Un primitivo como objeto -Here's the paradox faced by the creator of JavaScript: +Aquí el dilema que enfrentó el creador de JavaScript: -- There are many things one would want to do with a primitive like a string or a number. It would be great to access them as methods. -- Primitives must be as fast and lightweight as possible. +- Hay muchas cosas que uno querría hacer con los primitivos como string o number. Sería grandioso accederlas como métodos. +- Los Primitivos deben ser tan rápidos y livianos como sea posible -The solution looks a little bit awkward, but here it is: +La solución es algo enrevesada, pero aquí está: -1. Primitives are still primitive. A single value, as desired. -2. The language allows access to methods and properties of strings, numbers, booleans and symbols. -3. When this happens, a special "object wrapper" that provides the extra functionality is created, and then is destroyed. +1. Los primitivos son aún primitivos. Con un valor único, como es deseable. +2. El lenguaje permite el acceso a métodos y propiedades de strings, numbers, booleans y symbols. +3. Cuando esto ocurre, se crea una envoltura especial, un "object wrapper" que provee la funcionalidad extra y luego es destruido. -The "object wrappers" are different for each primitive type and are called: `String`, `Number`, `Boolean` and `Symbol`. Thus, they provide different sets of methods. +Los "object wrappers" son diferentes para cada primitivo y son llamados: `String`, `Number`, `Boolean` y `Symbol`. Así, proveen diferentes sets de métodos. -For instance, there exists a method [str.toUpperCase()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) that returns a capitalized string. +Por ejemplo, existe un método [str.toUpperCase()](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/toUpperCase) que devuelve un string en mayúsculas. -Here's how it works: +Aquí el funcionamiento: ```js run let str = "Hello"; @@ -62,17 +62,17 @@ let str = "Hello"; alert( str.toUpperCase() ); // HELLO ``` -Simple, right? Here's what actually happens in `str.toUpperCase()`: +Simple, ¿no es así? Lo que realmente ocurre en `str.toUpperCase()`: -1. The string `str` is a primitive. So in the moment of accessing its property, a special object is created that knows the value of the string, and has useful methods, like `toUpperCase()`. -2. That method runs and returns a new string (shown by `alert`). -3. The special object is destroyed, leaving the primitive `str` alone. +1. El string `str` es primitivo. Al momento de acceder a su propiedad, un objeto especial es creado, uno que conoce el valor del string y tiene métodos útiles como `toUpperCase()`. +2. Ese método se ejecuta y devuelve un nuevo string (mostrado con `alert`). +3. El objeto especial es destruido, dejando solo el primitivo `str`. -So primitives can provide methods, but they still remain lightweight. +Así los primitivos pueden proveer métodos y aún permanecer livianos. -The JavaScript engine highly optimizes this process. It may even skip the creation of the extra object at all. But it must still adhere to the specification and behave as if it creates one. +El motor JavaScript optimiza este proceso enormemente. Incluso puede saltear la creación del objeto extra por completo. Pero aún se debe adherir a la especificación y comportarse como si creara uno. -A number has methods of its own, for instance, [toFixed(n)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) rounds the number to the given precision: +Un number tiene sus propios métodos, por ejemplo [toFixed(n)](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Number/toFixed) redondea el número a la precisión dada: ```js run let n = 1.23456; @@ -80,15 +80,15 @@ let n = 1.23456; alert( n.toFixed(2) ); // 1.23 ``` -We'll see more specific methods in chapters and . +Veremos más métodos específicos en los capítulos and . -````warn header="Constructors `String/Number/Boolean` are for internal use only" -Some languages like Java allow us to create "wrapper objects" for primitives explicitly using a syntax like `new Number(1)` or `new Boolean(false)`. +````warn header="Constructors `String/Number/Boolean` son de uso interno solamente" +Algunos lenguajes como Java permiten crear "wrapper objects" para primitivos explícitamente usando una sintaxis como `new Number(1)` o `new Boolean(false)`. -In JavaScript, that's also possible for historical reasons, but highly **unrecommended**. Things will go crazy in several places. +En JavaScript, eso también es posible por razones históricas, pero firmemente **no recomendado**. Las cosas enloquecerían en varios lugares. -For instance: +Por ejemplo: ```js run alert( typeof 1 ); // "number" @@ -96,35 +96,35 @@ alert( typeof 1 ); // "number" alert( typeof new Number(1) ); // "object"! ``` -And because what follows, `zero`, is an object, the alert will show up: +Y porque en lo que sigue, 'zero' es un objeto, el alert mostrará: ```js run let zero = new Number(0); -if (zero) { // zero is true, because it's an object - alert( "zero is truthy?!?" ); +if (zero) { // zero es true, porque es un objeto + alert( "zero es verdadero?!?" ); } ``` -On the other hand, using the same functions `String/Number/Boolean` without `new` is a totally sane and useful thing. They convert a value to the corresponding type: to a string, a number, or a boolean (primitive). +Por otro lado, usar las mismas funciones `String/Number/Boolean` sin `new` es totalmente sano y útil. Ellas convierten un valor al tipo correspondiente: a un string, number, o boolean (primitivo). -For example, this is entirely valid: +Por ejemplo, esto es perfectamente válido:: ```js -let num = Number("123"); // convert a string to number +let num = Number("123"); // convierte string a number ``` ```` -````warn header="null/undefined have no methods" -The special primitives `null` and `undefined` are exceptions. They have no corresponding "wrapper objects" and provide no methods. In a sense, they are "the most primitive". +````warn header="null/undefined no poseen métodos" +Los primitivos especiales `null` y `undefined` son excepciones. No tienen "wrapper objects" correspondientes y no proveen métodos. En ese sentido son "lo más primitivo". -An attempt to access a property of such value would give the error: +El intento de acceder a una propiedad de tal valor daría error: ```js run alert(null.test); // error ```` -## Summary +## Resumen -- Primitives except `null` and `undefined` provide many helpful methods. We will study those in the upcoming chapters. -- Formally, these methods work via temporary objects, but JavaScript engines are well tuned to optimize that internally, so they are not expensive to call. +- Los primitivos excepto `null` y `undefined` proveen muchos métodos útiles. Los estudiaremos en los próximos capítulos. +- Formalmente, estos métodos trabajan a través de objetos temporales, pero los motores de JavaScript están bien afinados para optimizarlos internamente así que llamarlos no es costoso. From dac55128fa2659ef6d3e6bcaccfd2ea72e978fd0 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Mon, 1 Jun 2020 23:33:18 -0300 Subject: [PATCH 2/6] Update 1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md Co-authored-by: Ezequiel Castellanos <51804994+ezzep66@users.noreply.github.com> --- .../01-primitives-methods/1-string-new-property/solution.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md b/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md index 43d016663..f5687f463 100644 --- a/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md +++ b/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md @@ -11,7 +11,7 @@ alert(str.test); Depende de si usas el modo estricto "use strict" o no, el resultado será: 1. `undefined` (sin strict mode) -2. Un error. (strict mode) +2. Un error. (strict mode) ¿Por qué? Repasemos lo que ocurre en la línea `(*)`: @@ -22,4 +22,3 @@ Depende de si usas el modo estricto "use strict" o no, el resultado será: **Este ejemlplo claramente muestra que los tipos primitivos no son objetos.** Ellos no pueden almacenar datos adicionales. - From 2541e702b6bfac4f579cf110792823bc2153feb8 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Mon, 1 Jun 2020 23:35:43 -0300 Subject: [PATCH 3/6] Update 1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md Co-authored-by: Ezequiel Castellanos <51804994+ezzep66@users.noreply.github.com> --- .../01-primitives-methods/1-string-new-property/solution.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md b/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md index f5687f463..716951da5 100644 --- a/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md +++ b/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md @@ -15,7 +15,7 @@ Depende de si usas el modo estricto "use strict" o no, el resultado será: ¿Por qué? Repasemos lo que ocurre en la línea `(*)`: -1. Cuando se accede a una propiedad de `str`, un "wrapper object" es creado. +1. Cuando se accede a una propiedad de `str`, se crea un "wrapper object" (objeto envolvente ). 2. Con modo estricto, tratar de alterarlo produce error. 3. Sin modo estricto, la operación es llevada a cabo y el objeto obtiene la propiedad `test`, pero después de ello el "wrapper object" desaparece, entonces en la última linea `str` queda sin rastros de la propiedad. From 2c0eac14e3808e873a5958450e6a5be66493049b Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Mon, 1 Jun 2020 23:43:30 -0300 Subject: [PATCH 4/6] Update 1-js/05-data-types/01-primitives-methods/article.md Co-authored-by: Ezequiel Castellanos <51804994+ezzep66@users.noreply.github.com> --- 1-js/05-data-types/01-primitives-methods/article.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/01-primitives-methods/article.md b/1-js/05-data-types/01-primitives-methods/article.md index 04d5dfdd4..f7c4f518e 100644 --- a/1-js/05-data-types/01-primitives-methods/article.md +++ b/1-js/05-data-types/01-primitives-methods/article.md @@ -1,6 +1,6 @@ # Métodos en tipos primitivos -JavaScript nos permite trabajar con tipos primitivos (string, number, etc) como si fueran objetos. Los tipos primitivos también brindan métodos para ser llamados. Los estudiaremos pronto, pero primero veamos cómo trabajan porque, por supuesto, los primitivos no son objetos. (y aquí lo haremos aún más evidente). +JavaScript nos permite trabajar con tipos de datos primitivos (string, number, etc) como si fueran objetos. Los primitivos también brindan métodos para ser llamados. Los estudiaremos pronto, pero primero veamos cómo trabajan porque, por supuesto, los primitivos no son objetos. (y aquí lo haremos aún más evidente). Veamos las diferencias clave entre primitivos y objetos. From 0c0d3d24ac38653dc00c51d665b5b7bc5d656757 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Tue, 2 Jun 2020 00:01:23 -0300 Subject: [PATCH 5/6] Apply suggestions from code review maomeno... Co-authored-by: Ezequiel Castellanos <51804994+ezzep66@users.noreply.github.com> --- .../05-data-types/01-primitives-methods/article.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/1-js/05-data-types/01-primitives-methods/article.md b/1-js/05-data-types/01-primitives-methods/article.md index f7c4f518e..1910e9096 100644 --- a/1-js/05-data-types/01-primitives-methods/article.md +++ b/1-js/05-data-types/01-primitives-methods/article.md @@ -27,7 +27,7 @@ let john = { john.sayHi(); // Hi buddy! ``` -Aquí hemos creado una función `john` con el método `sayHi` (saludar). +Aquí hemos creado un objeto `john` con el método `sayHi`. Ya existen muchos objetos integrados al lenguaje, como los que trabajan con fechas, errores, elementos HTML, etc. Ellos tienen diferentes propiedades y métodos. @@ -46,7 +46,7 @@ La solución es algo enrevesada, pero aquí está: 1. Los primitivos son aún primitivos. Con un valor único, como es deseable. 2. El lenguaje permite el acceso a métodos y propiedades de strings, numbers, booleans y symbols. -3. Para que esto funciones, se crea una envoltura especial, un "object wrapper" que provee la funcionalidad extra y luego es destruido. +3. Para que esto funcione, se crea una envoltura especial, un "object wrapper" (objeto envoltorio) que provee la funcionalidad extra y luego es destruido. Los "object wrappers" son diferentes para cada primitivo y son llamados: `String`, `Number`, `Boolean` y `Symbol`. Así, proveen diferentes sets de métodos. @@ -78,10 +78,10 @@ let n = 1.23456; alert( n.toFixed(2) ); // 1.23 ``` -Veremos más métodos específicos en los capítulos and . +Veremos más métodos específicos en los capítulos y . -````warn header="Constructors `String/Number/Boolean` son de uso interno solamente" +````warn header="Los constructores `String/Number/Boolean` son de uso interno solamente" Algunos lenguajes como Java permiten crear "wrapper objects" para primitivos explícitamente usando una sintaxis como `new Number(1)` o `new Boolean(false)`. En JavaScript, eso también es posible por razones históricas, pero firmemente **desaconsejado**. Las cosas enloquecerían en varios lugares. @@ -97,10 +97,10 @@ alert( typeof new Number(0) ); // "object"! Los objetos siempre son true en un `if`, entonces el alert mostrará: ```js run -let zero = new Number(0); +let cero = new Number(0); -if (zero) { // zero es true, porque es un objeto - alert( "zero es verdadero?!?" ); +if (cero) { // cero es true, porque es un objeto + alert( "cero es verdadero?!?" ); } ``` From ee4c6255efdf238762320b5bf4fafeff7b2c0665 Mon Sep 17 00:00:00 2001 From: joaquinelio Date: Sat, 6 Jun 2020 03:57:45 -0300 Subject: [PATCH 6/6] Update 1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md Co-authored-by: Ezequiel Castellanos <51804994+ezzep66@users.noreply.github.com> --- .../01-primitives-methods/1-string-new-property/solution.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md b/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md index 716951da5..2addec0a2 100644 --- a/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md +++ b/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md @@ -17,7 +17,7 @@ Depende de si usas el modo estricto "use strict" o no, el resultado será: 1. Cuando se accede a una propiedad de `str`, se crea un "wrapper object" (objeto envolvente ). 2. Con modo estricto, tratar de alterarlo produce error. -3. Sin modo estricto, la operación es llevada a cabo y el objeto obtiene la propiedad `test`, pero después de ello el "wrapper object" desaparece, entonces en la última linea `str` queda sin rastros de la propiedad. +3. Sin modo estricto, la operación es llevada a cabo y el objeto obtiene la propiedad `test`, pero después de ello el "objeto envolvente" desaparece, entonces en la última linea `str` queda sin rastros de la propiedad. **Este ejemlplo claramente muestra que los tipos primitivos no son objetos.**