closure task
This commit is contained in:
parent
6be43b16a9
commit
c2a9c2da58
4 changed files with 61 additions and 0 deletions
|
@ -0,0 +1,40 @@
|
|||
The result is: **error**.
|
||||
|
||||
Try running it:
|
||||
|
||||
```js run
|
||||
let x = 1;
|
||||
|
||||
function func() {
|
||||
*!*
|
||||
console.log(x); // ReferenceError: Cannot access 'x' before initialization
|
||||
*/!*
|
||||
let x = 2;
|
||||
}
|
||||
|
||||
func();
|
||||
```
|
||||
|
||||
In this example we can observe the peculiar difference between a "non-existing" and "unitialized" variable.
|
||||
|
||||
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.
|
||||
|
||||
In other words, a variable technically exists, but can't be used before `let`.
|
||||
|
||||
The code above demonstrates it.
|
||||
|
||||
```js
|
||||
function func() {
|
||||
*!*
|
||||
// the local variable x is known to the engine from the beginning of the function,
|
||||
// but "unitialized" (unusable) until let ("dead zone")
|
||||
// hence the error
|
||||
*/!*
|
||||
|
||||
console.log(x); // ReferenceError: Cannot access 'vx before initialization
|
||||
|
||||
let x = 2;
|
||||
}
|
||||
```
|
||||
|
||||
This zone of temporary unusability of a variable (from the beginning of the code block till `let`) is sometimes called the "dead zone".
|
21
1-js/06-advanced-functions/03-closure/7-let-scope/task.md
Normal file
21
1-js/06-advanced-functions/03-closure/7-let-scope/task.md
Normal file
|
@ -0,0 +1,21 @@
|
|||
importance: 4
|
||||
|
||||
---
|
||||
|
||||
# Is variable visible?
|
||||
|
||||
What will be the result of this code?
|
||||
|
||||
```js
|
||||
let x = 1;
|
||||
|
||||
function func() {
|
||||
console.log(x); // ?
|
||||
|
||||
let x = 2;
|
||||
}
|
||||
|
||||
func();
|
||||
```
|
||||
|
||||
P.S. There's a pitfall in this task. The solution is not obvious.
|
Loading…
Add table
Add a link
Reference in a new issue