Skip to content

Commit 0924269

Browse files
committed
Updated scope.js
1 parent f0fa04b commit 0924269

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

scope.js

+34-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
Scope of Variable
1+
Scope of Variable
22

33
Scope is a concept that refers to where values and functions can be accessed.
44

@@ -20,4 +20,36 @@ function myFunction() {
2020

2121
}
2222

23-
// Code here can't use pizzaName
23+
// Code here can't use pizzaName
24+
25+
26+
-- Global Variables
27+
JavaScript variables that are declared outside of blocks or functions can exist in the global scope, which means they are accessible throughout a program. Variables declared outside of smaller block or function scopes are accessible inside those smaller scopes.
28+
29+
Note: It is best practice to keep global variables to a minimum.
30+
31+
// Variable declared globally
32+
const color = 'blue';
33+
34+
function printColor() {
35+
console.log(color);
36+
}
37+
38+
printColor(); // Prints: blue
39+
40+
41+
-- Block Scoped Variables
42+
const and let are block scoped variables, meaning they are only accessible in their block or nested blocks. In the given code block, trying to print the statusMessage using the console.log() method will result in a ReferenceError. It is accessible only inside that if block.
43+
44+
const isLoggedIn = true;
45+
46+
if (isLoggedIn == true) {
47+
const statusMessage = 'User is logged in.';
48+
}
49+
50+
console.log(statusMessage);
51+
52+
// Uncaught ReferenceError: statusMessage is not defined
53+
54+
--Note: We should not use global scope unless required as it is a bad practice.
55+
Scope should be limited till the variable is used. Also it makes the code looks clean and increases readability for other Developers.

0 commit comments

Comments
 (0)