Skip to content

Commit 6a9f66e

Browse files
committed
up
1 parent 6baabac commit 6a9f66e

File tree

3 files changed

+148
-70
lines changed

3 files changed

+148
-70
lines changed
Lines changed: 105 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,109 @@
11

22
# Let, const and var revisited
33

4-
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
53+
}
54+
55+
alert(`Goodbye ${user}!`); // Goodbye *!*Pete*/!*!
56+
```
57+
58+
Now there is no declaration inside `if`, there's no local `user`, hence the outer (the only declared) variable is used and modified.
59+
60+
The same applies to other `{…}` blocks, including `for`, `while`, `switch` and other constructs.
61+
62+
[smart header="`let` in `for` is also local"]
63+
In `for(let i=…)` the variable declared inside `for` is local to the loop body.
64+
65+
For instance, `i` in the example below is visible only inside the loop:
66+
67+
```js
68+
//+ run
69+
'use strict';
70+
71+
for(let i = 0; i < 3; i++) {
72+
// ...i becomes: 0, 1, 2
73+
alert(i);
74+
}
75+
76+
// i no longer exists here
77+
alert(i); // Error: i is not defined!
78+
```
79+
[/smart]
80+
81+
### Let is visible only after the declaration
82+
83+
The variable can only be used after it is declared:
84+
85+
```js
86+
//+ run
87+
'use strict';
88+
89+
alert(message); // Error, the variable does not exist yet!
90+
91+
let message = "hello";
92+
```
93+
94+
In the code above we must put `alert` after `let message` for it to work.
95+
96+
That seems to be obvious. But a little later we'll see that `var` behaves differently here.
97+
98+
## Const
99+
100+
A variable declared with `const` is exactly the same as `let` except that it cannot be modified.
101+
102+
The visibility rules are same.
103+
104+
## Var
105+
106+
107+
108+
5109

1-js/2-first-steps/18-function-basics/article.md

Lines changed: 43 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,9 @@ If we ever need to change the message or the way it is shown -- it's enough to m
4848

4949
## Local variables
5050

51-
A function may declare *local* variables with `var`, `let` or `const`.
51+
A variable declared inside a function is only visible inside that function.
5252

53-
These variables are only seen from inside the function:
53+
For example:
5454

5555
```js
5656
//+ run
@@ -67,121 +67,95 @@ showMessage(); // Hello, I'm JavaScript!
6767
alert( message ); // <-- Error! The variable is local to the function
6868
```
6969

70+
## Outer variables
7071

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:
7773

7874
```js
79-
//+ no-beautify
80-
function count() {
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';
8577

86-
*!*
87-
alert( i ); // i=3, последнее значение i, при нём цикл перестал работать
88-
alert( j ); // j=4, последнее значение j, которое вычислил цикл
89-
*/!*
78+
function showMessage() {
79+
var message = 'Hello, my name is ' + *!*userName*/!*;
80+
alert(message);
9081
}
91-
```
92-
93-
**Неважно, где именно в функции и сколько раз объявляется переменная. Любое объявление срабатывает один раз и распространяется на всю функцию.**
94-
95-
Объявления переменных в примере выше можно передвинуть вверх, это ни на что не повлияет:
96-
97-
```js
98-
function count() {
99-
*!*
100-
var i, j; // передвинули объявления var в начало
101-
*/!*
102-
for (i = 0; i < 3; i++) {
103-
j = i * 2;
104-
}
10582

106-
alert( i ); // i=3
107-
alert( j ); // j=4
108-
}
83+
showMessage(); // Hello, my name is John
10984
```
11085

111-
## Внешние переменные
86+
The function can not only read but also modify an outer variable.
11287

113-
Функция может обратиться ко внешней переменной, например:
88+
For instance:
11489

11590
```js
116-
//+ run no-beautify
117-
var *!*userName*/!* = 'Вася';
91+
//+ run
92+
var *!*userName*/!* = 'John';
11893

11994
function showMessage() {
120-
var message = 'Привет, я ' + *!*userName*/!*;
95+
userName = "Bob"; // (1) changed the outer variable
96+
97+
var message = 'Hello, my name is ' + *!*userName*/!*;
12198
alert(message);
12299
}
123100

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+
*/!*
125108
```
126109

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:
128111

129112
```js
130113
//+ run
131-
var userName = 'Вася';
114+
var *!*userName*/!* = 'John';
132115

133116
function showMessage() {
134-
userName = 'Петя'; // (1) присвоение во внешнюю переменную
117+
*!*
118+
var userName = "Bob"; // declare a local variable
119+
*/!*
135120

136-
var message = 'Привет, я ' + userName;
137-
alert( message );
121+
var message = 'Hello, my name is ' + *!*userName*/!*;
122+
alert(message);
138123
}
139124

125+
// the function will create and use it's own userName
140126
showMessage();
141127

142128
*!*
143-
alert( userName ); // Петя, значение внешней переменной изменено функцией
129+
alert( userName ); // John, the outer variable is not modified
144130
*/!*
145131
```
146132

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*.**
154134

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.
155136

156-
[warn header="Внимание: неявное объявление глобальных переменных!"]
157-
158-
В старом стандарте JavaScript существовала возможность неявного объявления переменных присвоением значения.
159-
160-
Например:
137+
[warn header="Attention: implicit global declaration!"]
138+
In the old JavaScript it was possible to omit variable declaration:
161139

162140
```js
163141
//+ run
164142
function showMessage() {
165-
message = 'Привет'; // без var!
143+
message = 'Hello'; // pure assignment, no declaration
166144
}
167145

168146
showMessage();
169147

170-
alert( message ); // Привет
148+
alert( message ); // Hello
171149
```
172150

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`.
178152

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.
180154

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.
182156
[/warn]
183157

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.
185159

186160
## Параметры
187161

figures.sketch

32 KB
Binary file not shown.

0 commit comments

Comments
 (0)