Skip to content

Commit 4ca7ee7

Browse files
committed
add Primitives methods
1 parent 825e398 commit 4ca7ee7

File tree

2 files changed

+165
-0
lines changed

2 files changed

+165
-0
lines changed

README.md

+24
Original file line numberDiff line numberDiff line change
@@ -75,3 +75,27 @@ We concentrate on the language itself here, with the minimum of environment-spec
7575
4.5 [Object to primitive conversion](pages/4.5-Object-to-primitive-conversion.md)
7676

7777
4.6 [Constructor, operator "new"](pages/4.6-Constructor-new.md)
78+
79+
### Data types
80+
81+
5.1 [Methods of primitives](pages/5.1-Primitives-methods.md)
82+
83+
5.2 Numbers
84+
85+
5.3 Strings
86+
87+
5.4 Arrays
88+
89+
5.5 Array methods
90+
91+
5.6 Iterables
92+
93+
5.7 Map, Set, WeakMap and WeakSet
94+
95+
5.8 Object.keys, values, entries
96+
97+
5.9 Destructuring assignment
98+
99+
5.10 Date and time
100+
101+
5.11 JSON methods, toJSON

pages/5.1-Primitives-methods.md

+141
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
# Constructor, operator "new"
2+
3+
JavaScript allows us to work with primitives (strings, numbers etc) as if they were objects.
4+
5+
They also provide methods to call and 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 more clear).
6+
7+
Let’s look at the key distinction between primitives and objects.
8+
9+
A primitive
10+
11+
***An object***
12+
13+
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, e.g. functions are objects.
14+
15+
One of the best things about objects is that we can store a function as one of its properties:
16+
17+
```
18+
let john = {
19+
name: "John",
20+
sayHi: function() {
21+
alert("Hi buddy!");
22+
}
23+
};
24+
25+
john.sayHi(); // Hi buddy!
26+
```
27+
28+
So here we’ve made an object `john` with the method `sayHi`.
29+
30+
Many built-in objects already exist, such as those that work with dates, errors, HTML elements etc. They have different properties and methods.
31+
32+
But, these features come with a cost!
33+
34+
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.
35+
36+
## A primitive as an object
37+
38+
Here’s the paradox faced by the creator of JavaScript:
39+
40+
* 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.
41+
42+
* Primitives must be as fast and lightweight as possible.
43+
44+
The solution looks a little bit awkward, but here it is:
45+
46+
1. Primitives are still primitive. A single value, as desired.
47+
48+
2. The language allows access to methods and properties of strings, numbers, booleans and symbols.
49+
50+
3. When this happens, a special “object wrapper” is created that provides the extra functionality, and then is destroyed.
51+
52+
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+
54+
For instance, there exists a method str.toUpperCase() that returns a capitalized string.
55+
56+
Here’s how it works:
57+
58+
```
59+
let str = "Hello";
60+
61+
alert( str.toUpperCase() ); // HELLO
62+
```
63+
64+
Simple, right? Here’s what actually happens in `str.toUpperCase()`:
65+
66+
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()`.
67+
68+
2. That method runs and returns a new string (shown by `alert`).
69+
70+
3. The special object is destroyed, leaving the primitive `str` alone.
71+
72+
So primitives can provide methods, but they still remain lightweight.
73+
74+
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.
75+
76+
A number has methods of its own, for instance, toFixed(n) rounds the number to the given precision:
77+
78+
```
79+
let n = 1.23456;
80+
81+
alert( n.toFixed(2) ); // 1.23
82+
```
83+
84+
We’ll see more specific methods in chapters Numbers and Strings.
85+
86+
87+
***
88+
89+
#### Constructors `String/Number/Boolean` are for internal use only
90+
91+
Some languages like Java allow us to create “wrapper objects” for primitives explicitly using a syntax like `new Number(1)` or `new Boolean(false)`.
92+
93+
In JavaScript, that’s also possible for historical reasons, but highly ***unrecommended***. Things will go crazy in several places.
94+
95+
For instance:
96+
97+
```
98+
alert( typeof 1 ); // "number"
99+
100+
alert( typeof new Number(1) ); // "object"!
101+
```
102+
103+
And because what follows, `zero`, is an object, the alert will show up:
104+
105+
```
106+
let zero = new Number(0);
107+
108+
if (zero) { // zero is true, because it's an object
109+
alert( "zero is truthy?!?" );
110+
}
111+
```
112+
113+
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).
114+
115+
For example, this is entirely valid:
116+
117+
```
118+
let num = Number("123"); // convert a string to number
119+
```
120+
121+
***
122+
123+
***
124+
125+
#### null/undefined have no methods
126+
127+
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”.
128+
129+
An attempt to access a property of such value would give the error:
130+
131+
```
132+
alert(null.test); // error
133+
```
134+
135+
***
136+
137+
## Summary
138+
139+
* Primitives except `null` and `undefined` provide many helpful methods. We will study those in the upcoming chapters.
140+
141+
* Formally, these methods work via temporary objects, but JavaScript engines are well tuned to optimize that internally, so they are not expensive to call.

0 commit comments

Comments
 (0)