Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Javascript 

Global variables

What are global variables? How are these variables declared?
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
Here's an example of a global variable

Code
const globalvar = 2;

function foo(){
let newvar = globalvar + 5;
// newvar = 7
console.log(globalvar, ' this is a global ' );
console.log(newvar, 'this is a local var');
}

console.log(globalvar); // this returns 2
console.log(newvar); // this doesn't work because newvar is not global

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 />


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C] by bhaktefhabo87Oct 11, 2021 07:28 AM 2 180 Oct 11, 2021 07:28 AM
Last Post: Cool_Pro_Grammer
[Python] by simmerMay 28, 2021 05:33 AM 5 200 May 28, 2021 05:33 AM
Last Post: simmer
[C] by SмℯґƒMay 1, 2020 09:00 PM 2 150 May 1, 2020 09:00 PM
Last Post: 0xDEAD10CC