Skip to content

Commit 792e657

Browse files
committed
1-5-1
1 parent 6f5cefa commit 792e657

File tree

1 file changed

+49
-49
lines changed
  • 1-js/05-data-types/01-primitives-methods

1 file changed

+49
-49
lines changed
Lines changed: 49 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
1-
# Methods of primitives
1+
# Métodos de primitivos
22

3-
JavaScript allows us to work with primitives (strings, numbers, etc.) as if they were objects.
3+
JavaScript nos permite trabajar con datos primitivos (strings, numbers, etc.) como si fueran objetos.
44

5-
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).
5+
También proveen, como aquellos, 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 más evidente).
66

7-
Let's look at the key distinctions between primitives and objects.
7+
Veamos las diferencias clave entre primitivos y objetos.
88

9-
A primitive
9+
Un primitivo
1010

11-
- Is a value of a primitive type.
12-
- There are 6 primitive types: `string`, `number`, `boolean`, `symbol`, `null` and `undefined`.
11+
- Es un valor de tipo primitivo.
12+
- Hay 6 tipos primitivos: `string`, `number`, `boolean`, `symbol`, `null` y `undefined`.
1313

14-
An object
14+
Un objeto
1515

16-
- Is capable of storing multiple values as properties.
17-
- Can be created with `{}`, for instance: `{name: "John", age: 30}`. There are other kinds of objects in JavaScript; functions, for example, are objects.
16+
- Es capaz de almacenar múltiples valores como propiedades.
17+
- Puede ser creado con `{}`, por ejemplo: `{name: "John", age: 30}`. Hay otras clases de objetos en JavaScript; por ejemplo, las funciones (`function`) son objetos .
1818

19-
One of the best things about objects is that we can store a function as one of its properties.
19+
Una de las mejores cosas de los objetos es que podemos almacenar una función como una de sus propiedades.
2020

2121
```js run
2222
let john = {
@@ -29,102 +29,102 @@ let john = {
2929
john.sayHi(); // Hi buddy!
3030
```
3131

32-
So here we've made an object `john` with the method `sayHi`.
32+
Aquí hemos hecho un función `john` con el método `sayHi` (saludar).
3333

34-
Many built-in objects already exist, such as those that work with dates, errors, HTML elements, etc. They have different properties and methods.
34+
Ya existen muchos objetos incorporados, como aquellos que trabajan con fechas, errores, elementos HTML, etc. Ellos tienen diferentes propiedades y métodos.
3535

36-
But, these features come with a cost!
36+
¡Pero estas características vienen con un costo!
3737

38-
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.
38+
Los objetos son más "pesados" que los primitivos. Requieren recursos adicionales para soportar su maquinaria interna. Pero como las propiedades y los métodos son tan útiles en programación, los motores JavaScript tratan de optimizarlos para reducir su carga adiional.
3939

40-
## A primitive as an object
40+
## Un primitivo como objeto
4141

42-
Here's the paradox faced by the creator of JavaScript:
42+
Aquí la paradoja que enfrentó el creador de JavaScript:
4343

44-
- 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.
45-
- Primitives must be as fast and lightweight as possible.
44+
- Hay muchas cosas que uno quisiera hacer con primitivos como string o number. Sería grandioso acceder a métodos.
45+
- Los Primitivos deben ser tan rápidos y livianos como sea posible.
4646

47-
The solution looks a little bit awkward, but here it is:
47+
La solución se ve algo enrevesada, pero aquí está:
4848

49-
1. Primitives are still primitive. A single value, as desired.
50-
2. The language allows access to methods and properties of strings, numbers, booleans and symbols.
51-
3. When this happens, a special "object wrapper" that provides the extra functionality is created, and then is destroyed.
49+
1. Los primitivos son aún primitivos. Con un valor único, como es deseable.
50+
2. El lenguaje permite acceder a métodos y propiedades de strings, numbers, booleans y symbols.
51+
3. Cuando esto ocurre, un "object wrapper" (objeto envoltura) especial que provee la funcionalidad extra es creado y luego destruido.
5252

53-
The "object wrappers" are different for each primitive type and are called: `String`, `Number`, `Boolean` and `Symbol`. Thus, they provide different sets of methods.
53+
Los "object wrappers" son diferentes para cada tipo primitivo y son llamados: `String`, `Number`, `Boolean` y `Symbol`. Así proveen diferentes sets de métodos.
5454

55-
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.
55+
Por ejemplo, hay 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.
5656

57-
Here's how it works:
57+
Aquí cómo funciona:
5858

5959
```js run
6060
let str = "Hello";
6161

6262
alert( str.toUpperCase() ); // HELLO
6363
```
6464

65-
Simple, right? Here's what actually happens in `str.toUpperCase()`:
65+
Simple, ¿no es así? Lo que realmente ocurre en `str.toUpperCase()`:
6666

67-
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()`.
68-
2. That method runs and returns a new string (shown by `alert`).
69-
3. The special object is destroyed, leaving the primitive `str` alone.
67+
1. El string `str` es un tipo primitivo. Entonces 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()`.
68+
2. El método se ejecuta y devuelve un nuevo string (el mostrado con `alert`).
69+
3. El objeto especial es destruido, dejando solo el primitivo `str`.
7070

71-
So primitives can provide methods, but they still remain lightweight.
71+
Así las primitivas pueden proveer métodos y aún permanecer livianas.
7272

73-
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.
73+
El motor JavaScript optimiza este proceso enormemente. Puede incluso saltear la creación del objeto extra por completo. Pero aún debe adherir a la especificación y comportarse como si creara uno.
7474

75-
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:
75+
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:
7676

7777
```js run
7878
let n = 1.23456;
7979

8080
alert( n.toFixed(2) ); // 1.23
8181
```
8282

83-
We'll see more specific methods in chapters <info:number> and <info:string>.
83+
Veremos más métodos específicos en los capítulos <info:number> y <info:string>.
8484

8585

86-
````warn header="Constructors `String/Number/Boolean` are for internal use only"
87-
Some languages like Java allow us to create "wrapper objects" for primitives explicitly using a syntax like `new Number(1)` or `new Boolean(false)`.
86+
````warn header="Constructors `String/Number/Boolean` son de uso interno solamente"
87+
Algunos lenguajes como JAva permiten crear "wrapper objects" para primitivas explícitamente usando una sintaxis como `new Number(1)` o `new Boolean(false)`.
8888

89-
In JavaScript, that's also possible for historical reasons, but highly **unrecommended**. Things will go crazy in several places.
89+
En JavaScript, eso también es posible por razones históricas, pero firmemente **no recomendado**. Las cosas enloquecerán en varios lugares.
9090

91-
For instance:
91+
Por ejemplo:
9292

9393
```js run
9494
alert( typeof 1 ); // "number"
9595

9696
alert( typeof new Number(1) ); // "object"!
9797
```
9898

99-
And because what follows, `zero`, is an object, the alert will show up:
99+
Los objetos son siempre verdaderos en un if, por ello el alert se mostrará:
100100

101101
```js run
102102
let zero = new Number(0);
103103

104-
if (zero) { // zero is true, because it's an object
105-
alert( "zero is truthy?!?" );
104+
if (zero) { // zero es true, porque es un objeto
105+
alert( "zero es verdadero?!?" );
106106
}
107107
```
108108

109-
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).
109+
Por otro lado, usar las mismas funciones `String/Number/Boolean` sin `new` es totalmente sano y útil. Ellos convierten un valor al tipo correspondiente: a un string, number, o boolean (primitivo).
110110

111-
For example, this is entirely valid:
111+
Por ejemplo, esto es perfectamente válido:
112112
```js
113-
let num = Number("123"); // convert a string to number
113+
let num = Number("123"); // convierte string a number
114114
```
115115
````
116116
117117
118118
````warn header="null/undefined have no methods"
119-
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".
119+
Las primitivas especiales `null` y `undefined` son excepciones. No tienen "wrapper objects" correspondientes y no proveen métodos. En ese sentido son "lo más primitivo".
120120
121-
An attempt to access a property of such value would give the error:
121+
El intento de acceder a una propiedad de tal valor daría error:
122122
123123
```js run
124124
alert(null.test); // error
125125
````
126126

127-
## Summary
127+
## Resumen
128128

129-
- Primitives except `null` and `undefined` provide many helpful methods. We will study those in the upcoming chapters.
130-
- Formally, these methods work via temporary objects, but JavaScript engines are well tuned to optimize that internally, so they are not expensive to call.
129+
- Las primitivas excepto `null` y `undefined` proveen muchos métodos útiles. Los estudiaremos en los próximos capítulos.
130+
- 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.

0 commit comments

Comments
 (0)