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
> **What's happening?** > The `city` parameter on **Line 3** shadows the `city` variable on **Line 1**. Any changes made to `city` inside the function (Line 4) stay inside the function's "bubble."
26
31
@@ -32,19 +37,23 @@ While shadowing is a common pattern, JavaScript has strict rules about how diffe
32
37
33
38
You cannot shadow a `let` or `const` variable using `var` within the same block or a nested block. This is because `var` is function-scoped and tries to "hoist" itself to the top, which conflicts with the block-scoped `let`.
*The `var` at line 4 is trying to **'cross the boundary'** of the `let` declaration, which results in a SyntaxError.*
40
47
41
48
### 2. Valid Shadowing (Function Boundaries)
42
49
43
50
Shadowing becomes valid again if there is a **function boundary** separating the declarations. Since functions create a completely new execution context, the conflict is resolved.
44
51
52
+
<!--
45
53
<JSEditortitle="Valid: Shadowing via Function Boundary">
<JSEditortitle="Visualizing Function Scope"url="scopes">
27
30
{firstExample}
28
31
</JSEditor>
32
+
-->
29
33
30
34
### Re-declaration & Updates
31
35
32
36
One of the "quirks" of `var` is that it allows you to re-declare the same variable name without an error. In large codebases, this often leads to accidental bugs.
33
37
38
+
<!--
34
39
<JSEditortitle="The 'Silent' Re-declaration">
35
40
{secondExample}
36
41
</JSEditor>
42
+
-->
37
43
38
44
:::tip Technical Insight
39
45
A repeated `var` declaration in the same scope is effectively a **do-nothing operation**. The JS engine sees the first one and ignores subsequent declarations of the same name.
@@ -63,9 +69,11 @@ age = 25; // 3. Assignment happens here
63
69
64
70
Functions are the "VIPs" of hoisting. They are moved to the top **before** variable declarations.
65
71
72
+
<!--
66
73
<JSEditortitle="Challenge: Function vs. Var Hoisting">
67
74
{fourthExample}
68
75
</JSEditor>
76
+
-->
69
77
70
78
## 3. The Modern Way: `let` & `const`
71
79
@@ -82,9 +90,11 @@ While `var` is function-scoped, `let` and `const` are **block-scoped** `{ }`. Th
82
90
83
91
Test your understanding of the execution context with these common interview scenarios.
84
92
93
+
<!--
85
94
<JSEditortitle="Puzzle: The Hoisting Order">
86
95
{fifthExample}
87
96
</JSEditor>
97
+
-->
88
98
89
99
:::info Deep Dive
90
100
For a deeper understanding of these mechanics, I highly recommend checking out:
0 commit comments