Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ed85606

Browse files
update example scripts
1 parent f418ab3 commit ed85606

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

‎1-js/06-advanced-functions/04-var/article.md‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ alert(phrase); // Error, phrase is not defined
3535

3636
For instance:
3737

38-
```js
38+
```js run
3939
if (true) {
4040
var test = true; // use "var" instead of "let"
4141
}
@@ -61,7 +61,7 @@ alert(i); // 10, "i" is visible after loop, it's a global variable
6161

6262
If a code block is inside a function, then `var` becomes a function-level variable:
6363

64-
```js
64+
```js run
6565
function sayHi() {
6666
if (true) {
6767
var phrase = "Hello";
@@ -71,7 +71,7 @@ function sayHi() {
7171
}
7272

7373
sayHi();
74-
alert(phrase); // Error: phrase is not defined
74+
alert(phrase); // Error: phrase is not defined (Check the Developer Console)
7575
```
7676

7777
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,
8484

8585
So this code:
8686

87-
```js
87+
```js run
8888
function sayHi() {
8989
phrase = "Hello";
9090

@@ -94,11 +94,12 @@ function sayHi() {
9494
var phrase;
9595
*/!*
9696
}
97+
sayHi();
9798
```
9899

99100
...Is technically the same as this (moved `var phrase` above):
100101

101-
```js
102+
```js run
102103
function sayHi() {
103104
*!*
104105
var phrase;
@@ -108,11 +109,12 @@ function sayHi() {
108109

109110
alert(phrase);
110111
}
112+
sayHi();
111113
```
112114

113115
...Or even as this (remember, code blocks are ignored):
114116

115-
```js
117+
```js run
116118
function sayHi() {
117119
phrase = "Hello"; // (*)
118120

@@ -124,6 +126,7 @@ function sayHi() {
124126

125127
alert(phrase);
126128
}
129+
sayHi();
127130
```
128131

129132
People also call such behavior "hoisting" (raising), because all `var` are "hoisted" (raised) to the top of the function.

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /