Skip to content

Commit c2a9c2d

Browse files
committed
closure task
1 parent 6be43b1 commit c2a9c2d

File tree

4 files changed

+61
-0
lines changed

4 files changed

+61
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
The result is: **error**.
2+
3+
Try running it:
4+
5+
```js run
6+
let x = 1;
7+
8+
function func() {
9+
*!*
10+
console.log(x); // ReferenceError: Cannot access 'x' before initialization
11+
*/!*
12+
let x = 2;
13+
}
14+
15+
func();
16+
```
17+
18+
In this example we can observe the peculiar difference between a "non-existing" and "unitialized" variable.
19+
20+
As you may have read in the article [](info:closure), a variable starts in the "uninitialized" state from the moment when the execution enters a code block (or a function). And it stays uninitalized until the corresponding `let` statement.
21+
22+
In other words, a variable technically exists, but can't be used before `let`.
23+
24+
The code above demonstrates it.
25+
26+
```js
27+
function func() {
28+
*!*
29+
// the local variable x is known to the engine from the beginning of the function,
30+
// but "unitialized" (unusable) until let ("dead zone")
31+
// hence the error
32+
*/!*
33+
34+
console.log(x); // ReferenceError: Cannot access 'vx before initialization
35+
36+
let x = 2;
37+
}
38+
```
39+
40+
This zone of temporary unusability of a variable (from the beginning of the code block till `let`) is sometimes called the "dead zone".
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
importance: 4
2+
3+
---
4+
5+
# Is variable visible?
6+
7+
What will be the result of this code?
8+
9+
```js
10+
let x = 1;
11+
12+
function func() {
13+
console.log(x); // ?
14+
15+
let x = 2;
16+
}
17+
18+
func();
19+
```
20+
21+
P.S. There's a pitfall in this task. The solution is not obvious.

0 commit comments

Comments
 (0)