•
A global variable is a variable that can be accessed and used from any scope within a program. The most basic, most common and least complex method of creating a global variable is by declaring the variable in the global scope, outside of any function, statement, loop etc. Below we have two figures (a) and (b). We will use these two figures to demonstrate the concept of global variables and show you how to create a global variable using the most basic method and most common method of creating a global variable.
\r\n\r\n
•
The dashed lines represent a scope region. Variables declared inside a scope region are visible at any sub-region within that region. For example, if the global scope region is our focus, any variable declared at global scope region, outside any sub-region, that variable is visible at any sub-region of the global scope.
\r\n\r\n
•
Here, we declare a global variable called globalVar and assign it a value of 5. Since globalV
Code
//Global Scope\r\nlet globalVar = 5;\r\n\r\nif(true){\r\n//Region B\r\n}\r\nwhile(true){\r\n//Region C\r\n}
Example: Accessing the global variable at region B.
\r\n
\r\n
•
Here, we print the global variable in scope region B. The output is 5, and therefore, the global variable is accessible from region B.
\r\n
Code
//Global Scope Region\r\nlet globalVar = 5;\r\n\r\nif(true){\r\n//Region B\r\nconsole.log(globalVar)\r\n}\r\nwhile(true){\r\n//Region C\r\n}\r\n\r\n\r\nOutput\r\n5
Example: Accessing the global variable at region C.\r\nHere, we print the global variable in scope region B. The output is 5, repeated till infinity since we are using a forever true while loop, and therefore, the global variable is accessible from region C. \r\n
Code
//Global scope\r\nlet globalVar = 5\r\n\r\nif(true){\r\n //Region B\r\n console.log(globalVar)\r\n}\r\nwhile(true){\r\n //Region C\r\n}\r\n\r\n\r\n\r\nOutput\r\n5\r\n
Method B: How to declare a global variable in JavaScript using the var keyword. \r\nThe var keyword is used for declaring a global variable in JavaScript. A variable declaration using the var keyword follows the following syntax: \r\nvar globalVar = value;\r\n\r\nThe var keyword allows you to declare a global variable from any scope region. This makes the var keyword particularly useful in cases where you can only alter code in a limited scope region such as a, if - else statements, switch statements and loop statements etc. Note that when it comes to object definitions, class definitions, function definitions and library definitions, the var keyword creates a global variable within the scope of the class, object, function or library being defined. \r\n
**Note that variables declared in region B are not visible outside region B and variables declared inside region C are not visible outside region C.
let globalVar = 5\r\n\r\nif(true){\r\n //Region B\r\n}\r\nwhile(true){\r\n //Region C\r\n console.log(globalVar)\r\n}\r\n\r\n\r\nOutput\r\n5\r\n5\r\n5\r\n5\r\n…\r\n