Skip to content

Commit 964ed57

Browse files
committed
closure
1 parent 5b19579 commit 964ed57

39 files changed

+321
-417
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
The answer is: **Pete**.
2+
3+
A function gets outer variables as they are now, it uses the most recent values.
4+
5+
Old variable values are not saved anywhere. When a function wants a variable, it takes the current value from its own Lexical Environment or the outer one.
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
importance: 5
2+
3+
---
4+
5+
# Does a function pickup latest changes?
6+
7+
The function sayHi uses an external variable name. When the function runs, which value is it going to use?
8+
9+
```js
10+
let name = "John";
11+
12+
function sayHi() {
13+
alert("Hi, " + name);
14+
}
15+
16+
name = "Pete";
17+
18+
sayHi(); // what will it show: "John" or "Pete"?
19+
```
20+
21+
Such situations are common both in browser and server-side development. A function may be scheduled to execute later than it is created, for instance after a user action or a network request.
22+
23+
So, the question is: does it pick up the latest changes?
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

1-js/06-advanced-functions/03-closure/lexenv-nested-work.svg renamed to 1-js/06-advanced-functions/03-closure/2-closure-variable-access/lexenv-nested-work.svg

Lines changed: 1 addition & 1 deletion
Loading
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
The answer is: **Pete**.
2+
3+
The `work()` function in the code below gets `name` from the place of its origin through the outer lexical environment reference:
4+
5+
![](lexenv-nested-work.svg)
6+
7+
So, the result is `"Pete"` here.
8+
9+
But if there were no `let name` in `makeWorker()`, then the search would go outside and take the global variable as we can see from the chain above. In that case the result would be `"John"`.

0 commit comments

Comments
 (0)