Skip to content

Commit acf0488

Browse files
authored
Merge pull request #347 from 2400030303/docs/formatting-fix
docs: improve formatting and explanation for accidental global example
2 parents f3f5341 + 853841b commit acf0488

1 file changed

Lines changed: 24 additions & 16 deletions

File tree

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,32 @@
11
function foo() {
2-
let x = (y = 0);
2+
let x = (y = 0); // ⚠️ y becomes a global variable
33
x++;
44
y++;
55
return x;
66
}
77

8-
console.log(foo(), typeof x, typeof y); // 1, undefined, number
8+
console.log(foo(), typeof x, typeof y);
9+
// Output: 1, "undefined", "number"
910

1011
/**
11-
* Here's the breakdown:
12-
1. Inside the foo function, x is declared using let, which means it's scoped to the function. However, y is not declared with let or var, so it becomes a global variable.
13-
14-
2. When x = y = 0; is executed, it's interpreted as x = (y = 0);, which initializes y as a global variable with the value of 0, and x as a local variable within the function with the value of 0.
15-
16-
3. x++ increments the local variable x by 1, making it 1.
17-
18-
4. y++ increments the global variable y by 1, making it 1 as well.
19-
20-
5. The function returns the value of x, which is 1.
21-
22-
However, x is scoped within the function, so typeof x outside of the function will result in undefined.
23-
y is a global variable, so typeof y outside of the function will result in number.
24-
*/
12+
* Explanation:
13+
*
14+
* 1. `x` is declared using `let`, so it is scoped to the `foo` function.
15+
*
16+
* 2. `y` is NOT declared using `let`, `var`, or `const`.
17+
* This causes `y` to become a global variable.
18+
*
19+
* 3. The expression `x = (y = 0)` is evaluated right to left:
20+
* - `y` is assigned `0` (global)
21+
* - `x` is assigned the value of `y` (local)
22+
*
23+
* 4. `x++` increments the local variable `x` → 1
24+
*
25+
* 5. `y++` increments the global variable `y` → 1
26+
*
27+
* 6. The function returns `x`, which is `1`.
28+
*
29+
* Outside the function:
30+
* - `typeof x === "undefined"` (x is function-scoped)
31+
* - `typeof y === "number"` (y is global)
32+
*/

0 commit comments

Comments
 (0)