What are global variables? How are these variables declared?
|
Javascript
Global variables |
|
This is explained here: https://www.w3schools.com/js/js_scope.asp
If you learn better by watching videos: https://www.youtube.com/watch?v=TkFN6e9ZDMw
Oct 15, 2023 06:03 AM
(This post was last modified: Oct 15, 2023 06:03 AM by Hackers.)
Here's an example of a global variable
Code const globalvar = 2;A global variable in JS is just a variable that is declared outside of a functional scope, so it's available to everything else inside the same scope. My foo function is inside the same scope that globalvar is defined in, so we can access it, but newvar is defined inside the function so it can't be accessed outside of the function.
As a general practice you want to avoid global variables. Having variables that are globally accessible and mutable can open the door to unintended side effects. The example in the OP here is a constant, at least, which isn't the worse thing in the world. But even then, best to only define global constants when you find yourself with no other alternative.
<Disease />
|
|
|


![[Image: z4PvoJm.jpg]](https://i.ibb.co/HVJyss0/z4PvoJm.jpg)

