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
Copy file name to clipboardExpand all lines: questions/explain-the-difference-between-global-scope-function-scope-and-block-scope/en-US.mdx
+6-5Lines changed: 6 additions & 5 deletions
Original file line number
Diff line number
Diff line change
@@ -6,7 +6,7 @@ title: Explain the difference between global scope, function scope, and block sc
6
6
7
7
Global scope means variables are accessible from anywhere in the code. Function scope means variables are accessible only within the function they are declared in. Block scope means variables are accessible only within the block (e.g., within `{}`) they are declared in.
8
8
9
-
```js
9
+
```js live
10
10
var globalVar ="I'm global"; // Global scope
11
11
12
12
functionmyFunction() {
@@ -18,6 +18,7 @@ function myFunction() {
18
18
// console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined
19
19
}
20
20
// console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined
21
+
myFunction();
21
22
```
22
23
23
24
---
@@ -28,7 +29,7 @@ function myFunction() {
28
29
29
30
Variables declared in the global scope are accessible from anywhere in the code. In a browser environment, these variables become properties of the `window` object.
Variables declared within a function are only accessible within that function. This is true for variables declared using `var`, `let`, or `const`.
45
46
46
-
```js
47
+
```js live
47
48
functionmyFunction() {
48
49
var functionVar ="I'm in a function";
49
50
console.log(functionVar); // Accessible here
50
51
}
51
52
52
53
myFunction(); // Output: "I'm in a function"
53
-
//console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined
54
+
console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined
54
55
```
55
56
56
57
### Block scope
57
58
58
59
Variables declared with `let` or `const` within a block (e.g., within `{}`) are only accessible within that block. This is not true for `var`, which is function-scoped.
0 commit comments