Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 24 additions & 16 deletions coding-exercise/accidental-global.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,32 @@
function foo() {
let x = (y = 0);
let x = (y = 0); // ⚠️ y becomes a global variable
x++;
y++;
return x;
}

console.log(foo(), typeof x, typeof y); // 1, undefined, number
console.log(foo(), typeof x, typeof y);
// Output: 1, "undefined", "number"

/**
* Here's the breakdown:
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.

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.

3. x++ increments the local variable x by 1, making it 1.

4. y++ increments the global variable y by 1, making it 1 as well.

5. The function returns the value of x, which is 1.

However, x is scoped within the function, so typeof x outside of the function will result in undefined.
y is a global variable, so typeof y outside of the function will result in number.
*/
* Explanation:
*
* 1. `x` is declared using `let`, so it is scoped to the `foo` function.
*
* 2. `y` is NOT declared using `let`, `var`, or `const`.
* This causes `y` to become a global variable.
*
* 3. The expression `x = (y = 0)` is evaluated right to left:
* - `y` is assigned `0` (global)
* - `x` is assigned the value of `y` (local)
*
* 4. `x++` increments the local variable `x` → 1
*
* 5. `y++` increments the global variable `y` → 1
*
* 6. The function returns `x`, which is `1`.
*
* Outside the function:
* - `typeof x === "undefined"` (x is function-scoped)
* - `typeof y === "number"` (y is global)
*/
Loading