Skip to content

Commit 14f54cf

Browse files
committed
exec: explain-the-difference-between-global-scope-function-scope-and-block-scope
1 parent aca5590 commit 14f54cf

File tree

1 file changed

+6
-5
lines changed
  • questions/explain-the-difference-between-global-scope-function-scope-and-block-scope

1 file changed

+6
-5
lines changed

questions/explain-the-difference-between-global-scope-function-scope-and-block-scope/en-US.mdx

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ title: Explain the difference between global scope, function scope, and block sc
66

77
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.
88

9-
```js
9+
```js live
1010
var globalVar = "I'm global"; // Global scope
1111

1212
function myFunction() {
@@ -18,6 +18,7 @@ function myFunction() {
1818
// console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined
1919
}
2020
// console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined
21+
myFunction();
2122
```
2223

2324
---
@@ -28,7 +29,7 @@ function myFunction() {
2829

2930
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.
3031

31-
```js
32+
```js live
3233
var globalVar = "I'm global";
3334

3435
function checkGlobal() {
@@ -43,21 +44,21 @@ console.log(globalVar); // Output: "I'm global"
4344

4445
Variables declared within a function are only accessible within that function. This is true for variables declared using `var`, `let`, or `const`.
4546

46-
```js
47+
```js live
4748
function myFunction() {
4849
var functionVar = "I'm in a function";
4950
console.log(functionVar); // Accessible here
5051
}
5152

5253
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
5455
```
5556

5657
### Block scope
5758

5859
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.
5960

60-
```js
61+
```js live
6162
if (true) {
6263
let blockVar = "I'm in a block";
6364
console.log(blockVar); // Accessible here

0 commit comments

Comments
 (0)