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
Copy file name to clipboardExpand all lines: 1-js/06-advanced-functions/04-var/article.md
+9-6Lines changed: 9 additions & 6 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -35,7 +35,7 @@ alert(phrase); // Error, phrase is not defined
35
35
36
36
For instance:
37
37
38
-
```js
38
+
```js run
39
39
if (true) {
40
40
var test =true; // use "var" instead of "let"
41
41
}
@@ -61,7 +61,7 @@ alert(i); // 10, "i" is visible after loop, it's a global variable
61
61
62
62
If a code block is inside a function, then `var` becomes a function-level variable:
63
63
64
-
```js
64
+
```js run
65
65
functionsayHi() {
66
66
if (true) {
67
67
var phrase ="Hello";
@@ -71,7 +71,7 @@ function sayHi() {
71
71
}
72
72
73
73
sayHi();
74
-
alert(phrase); // Error: phrase is not defined
74
+
alert(phrase); // Error: phrase is not defined (Check the Developer Console)
75
75
```
76
76
77
77
As we can see, `var` pierces through `if`, `for` or other code blocks. That's because a long time ago in JavaScript blocks had no Lexical Environments. And `var` is a remnant of that.
@@ -84,7 +84,7 @@ In other words, `var` variables are defined from the beginning of the function,
84
84
85
85
So this code:
86
86
87
-
```js
87
+
```js run
88
88
functionsayHi() {
89
89
phrase ="Hello";
90
90
@@ -94,11 +94,12 @@ function sayHi() {
94
94
var phrase;
95
95
*/!*
96
96
}
97
+
sayHi();
97
98
```
98
99
99
100
...Is technically the same as this (moved `var phrase` above):
100
101
101
-
```js
102
+
```js run
102
103
functionsayHi() {
103
104
*!*
104
105
var phrase;
@@ -108,11 +109,12 @@ function sayHi() {
108
109
109
110
alert(phrase);
110
111
}
112
+
sayHi();
111
113
```
112
114
113
115
...Or even as this (remember, code blocks are ignored):
114
116
115
-
```js
117
+
```js run
116
118
functionsayHi() {
117
119
phrase ="Hello"; // (*)
118
120
@@ -124,6 +126,7 @@ function sayHi() {
124
126
125
127
alert(phrase);
126
128
}
129
+
sayHi();
127
130
```
128
131
129
132
People also call such behavior "hoisting" (raising), because all `var` are "hoisted" (raised) to the top of the function.
0 commit comments