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
Now as we know most language syntax constructs, let's recall `let`, `var` and `const` and make sure we understand the difference.
4
+
Now as we know most language syntax constructs, let's discuss the subtle features and differences between variable definitions: `let`, `var` and `const`.
5
+
6
+
## Let
7
+
8
+
We'll start with `let`, because in the modern code this declaration appears far more often than any other.
9
+
10
+
### Let is local to the block
11
+
12
+
A variable declared with `let` is local to the containing `{…}`.
13
+
14
+
In other words, the variable is only visible inside the block `{…}` where it was declared.
15
+
16
+
For instance, let's consider the following code:
17
+
18
+
```js
19
+
//+ run
20
+
'use strict';
21
+
22
+
let user ="John";
23
+
24
+
alert(`Hello ${user}!`); // Hello John!
25
+
26
+
if (true) {
27
+
*!*
28
+
let user ="Pete";
29
+
*/!*
30
+
alert(`…working with ${user}`); // …working with Pete
31
+
}
32
+
33
+
alert(`Goodbye ${user}!`); // Goodbye John!
34
+
```
35
+
36
+
Here the if-block declares and uses it's own variable named `"user"`. The code inside that `if` will see and use the local variable ("Pete"). And after the `if` finished, the if-local `user` is no longer seen ("John" again).
37
+
38
+
Let's see what happens if we remove the `let` inside `if`:
39
+
40
+
```js
41
+
//+ run
42
+
'use strict';
43
+
44
+
let user ="John";
45
+
46
+
alert(`Hello ${user}!`); // Hello John!
47
+
48
+
if (true) {
49
+
*!*
50
+
user ="Pete";
51
+
*/!*
52
+
alert(`…working with ${user}`); // …working with Pete
alert( message ); // <-- Error! The variable is local to the function
68
68
```
69
69
70
+
## Outer variables
70
71
71
-
72
-
**Блоки `if/else`, `switch`, `for`, `while`, `do..while` не влияют на область видимости переменных.**
73
-
74
-
При объявлении переменной в таких блоках, она всё равно будет видна во всей функции.
75
-
76
-
Например:
72
+
A function can access an outer variable as well, for example:
77
73
78
74
```js
79
-
//+ no-beautify
80
-
functioncount() {
81
-
// переменные i,j не будут уничтожены по окончании цикла
82
-
for (*!*var*/!* i =0; i <3; i++) {
83
-
*!*var*/!* j = i *2;
84
-
}
75
+
//+ run no-beautify
76
+
var*!*userName*/!*='John';
85
77
86
-
*!*
87
-
alert( i ); // i=3, последнее значение i, при нём цикл перестал работать
88
-
alert( j ); // j=4, последнее значение j, которое вычислил цикл
89
-
*/!*
78
+
functionshowMessage() {
79
+
var message ='Hello, my name is '+*!*userName*/!*;
80
+
alert(message);
90
81
}
91
-
```
92
-
93
-
**Неважно, где именно в функции и сколько раз объявляется переменная. Любое объявление срабатывает один раз и распространяется на всю функцию.**
94
-
95
-
Объявления переменных в примере выше можно передвинуть вверх, это ни на что не повлияет:
96
-
97
-
```js
98
-
functioncount() {
99
-
*!*
100
-
var i, j; // передвинули объявления var в начало
101
-
*/!*
102
-
for (i =0; i <3; i++) {
103
-
j = i *2;
104
-
}
105
82
106
-
alert( i ); // i=3
107
-
alert( j ); // j=4
108
-
}
83
+
showMessage(); // Hello, my name is John
109
84
```
110
85
111
-
## Внешние переменные
86
+
The function can not only read but also modify an outer variable.
112
87
113
-
Функция может обратиться ко внешней переменной, например:
88
+
For instance:
114
89
115
90
```js
116
-
//+ run no-beautify
117
-
var*!*userName*/!*='Вася';
91
+
//+ run
92
+
var*!*userName*/!*='John';
118
93
119
94
functionshowMessage() {
120
-
var message ='Привет, я '+*!*userName*/!*;
95
+
userName ="Bob"; // (1) changed the outer variable
96
+
97
+
var message ='Hello, my name is '+*!*userName*/!*;
121
98
alert(message);
122
99
}
123
100
124
-
showMessage(); // Привет, я Вася
101
+
alert( userName ); // John before the function call
102
+
103
+
showMessage();
104
+
105
+
*!*
106
+
alert( userName ); // Bob, the value was modified by the function
107
+
*/!*
125
108
```
126
109
127
-
Доступ возможен не только на чтение, но и на запись. При этом, так как переменная внешняя, то изменения будут видны и снаружи функции:
110
+
Of course if we had `var userName = ...` in the line (1) then the function would have a local variable `userName` and use it instead of the outer one:
128
111
129
112
```js
130
113
//+ run
131
-
var userName ='Вася';
114
+
var*!*userName*/!*='John';
132
115
133
116
functionshowMessage() {
134
-
userName ='Петя'; // (1) присвоение во внешнюю переменную
117
+
*!*
118
+
var userName ="Bob"; // declare a local variable
119
+
*/!*
135
120
136
-
var message ='Привет, я '+ userName;
137
-
alert(message);
121
+
var message ='Hello, my name is '+*!*userName*/!*;
122
+
alert(message);
138
123
}
139
124
125
+
// the function will create and use it's own userName
140
126
showMessage();
141
127
142
128
*!*
143
-
alert( userName ); //Петя, значение внешней переменной изменено функцией
129
+
alert( userName ); //John, the outer variable is not modified
144
130
*/!*
145
131
```
146
132
147
-
Конечно, если бы внутри функции, в строке `(1)`, была бы объявлена своя локальная переменная `var userName`, то все обращения использовали бы её, и внешняя переменная осталась бы неизменной.
148
-
149
-
**Переменные, объявленные на уровне всего скрипта, называют *"глобальными переменными"*.**
150
-
151
-
В примере выше переменная `userName` -- глобальная.
152
-
153
-
Делайте глобальными только те переменные, которые действительно имеют общее значение для вашего проекта, а нужные для решения конкретной задачи -- пусть будут локальными в соответствующей функции.
133
+
**Variables declared on the most outer level, not in any function, are called *global*.**
154
134
135
+
Please only declare global the variables which have a project-wide importance. Variables needed by specific tasks should reside in the corresponding functions. So to say, global variables are rare in modern projects.
В старом стандарте JavaScript существовала возможность неявного объявления переменных присвоением значения.
159
-
160
-
Например:
137
+
[warn header="Attention: implicit global declaration!"]
138
+
In the old JavaScript it was possible to omit variable declaration:
161
139
162
140
```js
163
141
//+ run
164
142
functionshowMessage() {
165
-
message ='Привет'; //без var!
143
+
message ='Hello'; //pure assignment, no declaration
166
144
}
167
145
168
146
showMessage();
169
147
170
-
alert( message ); //Привет
148
+
alert( message ); //Hello
171
149
```
172
150
173
-
В коде выше переменная `message` нигде не объявлена, а сразу присваивается. Скорее всего, программист просто забыл поставить `var`.
174
-
175
-
При `use strict` такой код привёл бы к ошибке, но без него переменная будет создана автоматически, причём в примере выше она создаётся не в функции, а на уровне всего скрипта.
176
-
177
-
Избегайте этого.
151
+
In the code above `message` was not declared. Most probably, the programmer simply forgot to write `var`.
178
152
179
-
Здесь опасность даже не в автоматическом создании переменной, а в том, что глобальные переменные должны использоваться тогда, когда действительно нужны "общескриптовые" параметры.
153
+
With `"use strict"` there will be an error. But without it, the variable will be created automatically. And not in the function, but globally, in the whole script.
180
154
181
-
Забыли `var` в одном месте, потом в другом -- в результате одна функция неожиданно поменяла глобальную переменную, которую использует другая. И поди разберись, кто и когда её поменял, не самая приятная ошибка для отладки.
155
+
Modern editors and tools for code quality checking like [jshint](http://jshint.com/) allow to see and fix "missed declarations" early while coding.
182
156
[/warn]
183
157
184
-
В будущем, когда мы лучше познакомимся с основами JavaScript, в главе [](/closures), мы более детально рассмотрим внутренние механизмы работы переменных и функций.
158
+
In the future, after we deal with the basics and data structures, in the chapter [](/closures) we will go deeper in the internals of functions and variables.
0 commit comments