Hack Forums
[Javascript] Global variables - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Javascript] Global variables (/showthread.php?tid=6253910)



Global variables - Z3R00NDAT - Oct 14, 2023

What are global variables? How are these variables declared?


RE: Global variables - Edge - Oct 14, 2023

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


RE: Global variables - Hackers - Oct 15, 2023

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.


RE: Global variables - Disease - Oct 16, 2023

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.