From 853841b5d87b3201fabf8808637c711035fc1fdd Mon Sep 17 00:00:00 2001 From: 2400030303 <2400030303@kluniversity.in> Date: Mon, 9 Feb 2026 12:21:50 +0530 Subject: [PATCH] docs: improve formatting and explanation for accidental global example --- coding-exercise/accidental-global.js | 40 +++++++++++++++++----------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/coding-exercise/accidental-global.js b/coding-exercise/accidental-global.js index ff761b09..bad88621 100644 --- a/coding-exercise/accidental-global.js +++ b/coding-exercise/accidental-global.js @@ -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) + */ \ No newline at end of file