You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/2-first-steps/07-types/article.md
+7-3Lines changed: 7 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -15,6 +15,8 @@ n = 12.345;
15
15
16
16
A *number* type serves both for integer and floating point numbers.
17
17
18
+
There are many operations for numbers, e.g. multiplication `*`, division `/`, addition `+`, substraction `-` and so on.
19
+
18
20
Besides regular numbers there are so-called "special numeric values" which also belong to that type: `Infinity`, `-Infinity` and `NaN`.
19
21
20
22
-`Infinity` represents the mathematical [Infinity](https://en.wikipedia.org/wiki/Infinity). It is a value that's greater than any number.
@@ -33,13 +35,13 @@ Besides regular numbers there are so-called "special numeric values" which also
33
35
-`NaN` represents a computational error. It is a result of an incorrect or an undefined mathematical operation, for instance:
34
36
35
37
```js run
36
-
alert( "not a number" * 2 ); // NaN
38
+
alert( "not a number" / 2 ); // NaN
37
39
```
38
40
39
41
`NaN` is sticky. Any further operation on `NaN` would give `NaN`:
40
42
41
43
```js run
42
-
alert( "not a number" * 2 + 5 - 9 ); // NaN
44
+
alert( "not a number" / 2 + 5 ); // NaN
43
45
```
44
46
45
47
So, in a long mathematical expression if we have `NaN`in one place, it propagates to the whole result.
@@ -232,6 +234,8 @@ Here we have a variable `key` which contains the property name, probably evaluat
232
234
233
235
Most of time, the dot is used to access object properties, but when we need a complex property name or to pass the name as a variable, then -- we go square brackets.
234
236
237
+
Javascript supports object inheritance. There are many types that are based on objects:`Date`for dates, `Array`for ordered data, `Error`for error-reporting and so on. So the word "object" is applicable to a variety ofthings. The term *plain objects* is used to represent "basic" objects, the ones we create with`{ ... }`.
238
+
235
239
Objects in JavaScript are very powerful. Here we've just scratched the surface of the topic that is really huge. We'll be closely working with objects and learning more about them in further parts of the tutorial.
236
240
237
241
## Arrays
@@ -263,7 +267,7 @@ alert( fruits[2] ); // Plum
263
267
alert( fruits.length ); // 3
264
268
```
265
269
266
-
Please note that arrays do not form a separate language type. They are based on objects, but have many features of their own including methods to add, remove, extract elements from the array, to sort arrays and more. We'll cover them in the chapter <info:array>.
270
+
Please note that arrays do not form a separate language type. They are based on objects. But they greatly extend them withfeatures of their own, methods to add, remove, extract elements from the array, to sort arrays and more. We'll cover them in the chapter <info:array>.
Copy file name to clipboardExpand all lines: 1-js/2-first-steps/08-type-conversions/article.md
+72-42Lines changed: 72 additions & 42 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,4 +1,4 @@
1
-
# Type conversions
1
+
# Type Conversions
2
2
3
3
A variable in JavaScript can contain any data. A variable can at one moment be a string and later recieve a numeric value:
4
4
@@ -8,21 +8,11 @@ let message = "hello";
8
8
message =123456;
9
9
```
10
10
11
-
...But sometimes we need to convert a value from one type to another. For example, `alert` automatically converts any value to a string, to show it. Or, so to say, an `if(value)` test converts the `value` to boolean type to see if it's `true` or `false`.
11
+
...But some operations implicitly convert a value from one type to another. For example, `alert` automatically converts any value to a string, to show it. Or mathematical operations convert values to numbers. That is called *type coercion*.
12
12
13
13
There are also cases when we need to explicitly convert between types to ensure that we store the right data the right way or to use special features of a certain type.
14
14
15
-
There are many type conversions in JavaScript, fully listed in [the specification](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-type-conversion).
16
-
17
-
Three conversions that happen the most often:
18
-
19
-
1. String conversion.
20
-
2. Numeric conversion.
21
-
3. Boolean conversion.
22
-
23
-
Let's see how they work and when they happen.
24
-
25
-
## String conversion
15
+
## ToString
26
16
27
17
The string conversion happens when we need a string form of a value.
28
18
@@ -46,36 +36,19 @@ alert(typeof a); // string
46
36
*/!*
47
37
```
48
38
49
-
The string conversion is obvious. A `false` becomes `"false"`, `null` becomes `"null"` etc.
50
-
51
-
For objects it's a little bit trickier. By default, regular objects are converted like this:
52
-
53
-
```js run
54
-
alert( {} ); [object Object]
55
-
```
56
-
57
-
Although, some object subtypes have their own way of formatting, for instance, arrays turn into the comma-delimited list of items:
58
-
59
-
```js run
60
-
let arr = [1,2,3];
61
-
62
-
alert( arr ); // 1,2,3
63
-
alert( String(arr) ==='1,2,3' ); // true
64
-
```
65
-
66
-
Later we'll see how to create custom rules for string conversions for our objects.
39
+
The string conversion is mostly obvious. A `false` becomes `"false"`, `null` becomes `"null"` etc.
67
40
68
-
## Numeric conversion
41
+
## ToNumber
69
42
70
43
Numeric conversion happens in mathematical functions and expressions automatically.
71
44
72
-
For example, a mathematical operation like division '/' can be applied to non-numbers:
45
+
For example, when division '/' is applied to non-numbers:
73
46
74
47
```js run
75
-
alert( "6"/"2" ); // 3, strings become numbers
48
+
alert( "6"/"2" ); // 3, strings are converted to numbers
76
49
```
77
50
78
-
We can use a `Number(value)` function to convert any`value` to a number:
51
+
We can use a `Number(value)` function to explicitly convert a`value`:
79
52
80
53
```js run
81
54
let str ="123";
@@ -86,9 +59,9 @@ let n = Number(str); // becomes a number 123
86
59
alert(typeof n); // number
87
60
```
88
61
89
-
The conversion is usually applied when we have a numeric value coming from a text form field or another string-based source.
62
+
The explicit conversion is usually required when we read a value coming from a text form field or another string-based source, but we expect a number to be entered.
90
63
91
-
If the string is not a number, the result of such conversion is `NaN`, for instance:
64
+
If the string is not a valid number, the result of such conversion is `NaN`, for instance:
92
65
93
66
```js run
94
67
let age =Number("an arbitrary string instead of a number");
@@ -116,7 +89,22 @@ alert( Number(false) ); // 0
116
89
117
90
Please note that `null` and `undefined` behave differently here: `null` becomes a zero, while `undefined` becomes `NaN`.
Almost all mathematical operations convert values to numbers. With a notable exception of the addition `+`. If one of the added values is a string, then another one is also converted to a string.
94
+
95
+
Then it concatenates (joins) them:
96
+
97
+
```js run
98
+
alert( 1 + '2' ); // '12' (string to the right)
99
+
alert( '1' + 2 ); // '12' (string to the left)
100
+
101
+
alert( 1 + 2 ); // 3, numbers (for the contrast)
102
+
```
103
+
104
+
That only happens when one of arguments is a string, in other cases values are converted to numbers.
105
+
````
106
+
107
+
## ToBoolean
120
108
121
109
Boolean conversion is the simplest one.
122
110
@@ -125,7 +113,7 @@ It happens in logical operations (later we'll meet `if` tests and other kinds),
125
113
The conversion rule:
126
114
127
115
- Values that are intuitively "empty", like `0`, an empty string, `null`, `undefined` and `NaN` become `false`.
128
-
- Other values become `true`.
116
+
- Other values become `true`.
129
117
130
118
````warn header="Please note: the string with zero `\"0\"` is `true`"
131
119
Some languages (namely PHP) treat `"0"` as `false`. But in JavaScript a non-empty string is always `true`.
@@ -136,6 +124,49 @@ alert( Boolean(" ") ); // any non-empty string, even whitespaces are true
136
124
```
137
125
````
138
126
127
+
````warn header="Empty objects and arrays are truthy"
128
+
All objects become `true`:
129
+
130
+
```js run
131
+
alert( Boolean([]) ); // true
132
+
alert( Boolean({}) ); // true
133
+
```
134
+
````
135
+
136
+
137
+
## ToPrimitive
138
+
139
+
A string or numeric conversion of an object is a two-stage process. The object is first converted to a primitive value, and then ToString/ToNumber rules are applied to it.
140
+
141
+
The conversion is customizable on a per-object basis, so we'd better deal with it later when we know more about objects.
142
+
143
+
For now, let's just see two common rules that we often meet when showing objects.
144
+
145
+
- When a plain object is converted into a string, is becomes `[object Object]`:
146
+
147
+
```js run
148
+
alert( {} ); // [object Object]
149
+
alert( {name:"John"} ); // [object Object]
150
+
```
151
+
152
+
- An array becomes a comma-delimited list of items:
153
+
154
+
```js run
155
+
let arr = [1, 2, 3];
156
+
157
+
alert( arr ); // 1,2,3
158
+
alert( String(arr) ==='1,2,3' ); // true
159
+
```
160
+
161
+
We'll return to it in the chapter [todo].
162
+
163
+
```smart header="It was only about ToString/ToNumber"
164
+
For ToBoolean, there is no complexity neither customizability.
165
+
166
+
The rule is simple: all objects are truthy.
167
+
```
168
+
169
+
139
170
## Summary
140
171
141
172
There exist three most widely used type conversions: to string, to number and to boolean.
@@ -158,11 +189,10 @@ To boolean:
158
189
|`0`, `null`, `undefined`, `NaN`, `""`|`false`|
159
190
|any other value|`true`|
160
191
161
-
Objects provide advanced means to specify how they are converted to string and number, we'll see them later, when study objects in-depth.
162
-
163
192
Most of these rules are easy to understand and memorize. The notable exceptions where people usually make mistakes are:
164
193
165
194
-`undefined` is `NaN` as a number.
166
195
-`"0"` is true as a boolean.
167
196
168
-
In the next chapter we'll study operators. You will find enough tasks for type conversion there.
197
+
Objects can define their own methods of converting to a string or a number, we'll see them later. But they can't redefine the conversion to boolean.
Copy file name to clipboardExpand all lines: 1-js/2-first-steps/10-comparison/article.md
+14-2Lines changed: 14 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -69,7 +69,7 @@ For instance, the case matters. A capital letter `"A"` is not equal to the lower
69
69
70
70
## Comparison of different types
71
71
72
-
When compared values belong to different types, they get autoconverted to numbers.
72
+
When compared values belong to different types, they are coerced to numbers.
73
73
74
74
For example:
75
75
@@ -187,14 +187,26 @@ We've got such result, because:
187
187
- Comparisons `(1)` and `(2)` return `false` because `undefined` gets converted to `NaN`. And `NaN` is a special numeric value which returns `false` for all comparisons.
188
188
- The equality check `(3)` returns `false`, because `undefined` only equals `null` and no other value.
189
189
190
-
### How to live a good life
190
+
### Evade problems
191
191
192
192
Why did we observe these examples? Should we remember these pecularities all the time? Well, not really. Actually, these tricky things will gradually become familiar over the time, but there's a solid way to evade any problems with them.
193
193
194
194
Just treat any comparison with `undefined/null` except the strict equality `===` with an exceptional care.
195
195
196
196
Don't use comparisons `>= > < <=` with a variable which may be `null/undefined`, unless you are really sure what you're doing. If a variable can have such values, then check it separately.
197
197
198
+
## Comparison with objects
199
+
200
+
For equality checks two objects are always treated as non-equal.
201
+
202
+
```js run
203
+
alert( {} == {} ); // false
204
+
alert( [] == [] ); // false
205
+
```
206
+
207
+
Note that Javascript does not try to compare the objects by content. The rule is simple: different objects are not equal.
208
+
209
+
For other comparisons like `< >` operators, or when an object is compared with a primitive, objects are first converted to primitives, and then the comparison runs as usual.
Copy file name to clipboardExpand all lines: 1-js/2-first-steps/19-function-create-advanced/article.md
+2-68Lines changed: 2 additions & 68 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -156,78 +156,12 @@ A function can be perceived as an *action*.
156
156
We can copy it between variables and run when we want. We can even add properties to it if we wish.
157
157
```
158
158
159
-
## Function Expression as a method
160
-
161
-
Now let's step back and reconsider. We have two ways of declaring a function. Do we really need both? What's so good about Function Expressions that makes it useful?
162
-
163
-
Actually, yes, we do. For example, we can assign functions to object properties using function expressions.
164
-
165
-
As we remember from the chapter <info:types>, objects are data structures meant to store collections of data. Most often, we create objects to represent entities of the real world, like users, goodies and so on:
166
-
167
-
```js
168
-
let user = {
169
-
name:"John",
170
-
age:30
171
-
};
172
-
```
173
-
174
-
In the real world, a user can `act`: to select something from the shopping cart, to login, to logout etc. For the start, let's teach him to say hello:
175
-
176
-
```js run
177
-
let user = {
178
-
name:"John",
179
-
age:30
180
-
};
181
-
182
-
*!*
183
-
user.sayHi=function() {
184
-
alert("Hello!");
185
-
};
186
-
*/!*
187
-
188
-
user.sayHi(); // Hello!
189
-
```
190
-
191
-
You see? We've just used a Function Expression to create the function and assign it to the property `user.sayHi` of the object.
192
-
193
-
Then we can call it any time. The user now can speak!
194
-
195
-
That is how a so-called "object-oriented code" is written. We make objects which reflect entities of the real world: like a user, or a document, or a button that is clickable etc.
196
-
197
-
An object stores its data in regular properties (like `name`, `age` etc) and has functions to express itself. Function properties are usually called *methods*. So, one can say that in the code above "`sayHi` is a method of the object `user`".
198
-
199
-
Of course we could use a Function Declaration for the same purpose:
200
-
201
-
```js run
202
-
let user = {
203
-
// ...
204
-
};
205
-
206
-
*!*
207
-
functionsayHi() {
208
-
alert("Hello!");
209
-
};
210
-
211
-
user.sayHi= sayHi;
212
-
*/!*
213
-
214
-
user.sayHi(); // Hello!
215
-
```
216
-
217
-
That would also work, but is longer. Also we get an "extra" function `sayHi` outside of the `user` object. Here we don't want it.
218
-
219
-
```smart header="Object-oriented programming"
220
-
When we write our code using objects to represent entities, that's called an [object-oriented programming](https://en.wikipedia.org/wiki/Object-oriented_programming), in short: "OOP".
221
-
222
-
As of now, we already know how to create an object with `{...}` and how to store data and add a method to it. But we will study it in detail later when we get enough familarity with basic functions of the language.
223
-
```
224
-
225
159
226
160
## Function Expression vs Function Declaration
227
161
228
162
Let's formulate the key differences between Function Declarations and Expressions.
229
163
230
-
Here's the syntax distinction between these two.
164
+
First, the syntax: how to see what is what in the code.
231
165
232
166
-*Function Declaration:* a function, declared as a separate statement, in the main code flow.
233
167
@@ -247,7 +181,7 @@ Here's the syntax distinction between these two.
247
181
}
248
182
```
249
183
250
-
Another difference is when they are actualy created by the JavaScript engine.
184
+
The more subtle difference is when they are actualy created by the JavaScript engine.
251
185
252
186
**Function Expressions are created when the execution reaches them and are usable since then.**
0 commit comments