2.4 KiB
title |
---|
Global Variables |
Global variables are declared outside of a function for accessibility throughout the program, while local variables are stored within a function using var
for use only within that function's scope. If you declare a variable without using var
, even if it's inside a function, it will still be seen as global:
var x = 5; //global
function someThing(y) {
var z = x + y;
console.log(z);
}
function someThing(y) {
x = 5; //still global!
var z = x + y;
console.log(z);
}
function someThing(y) {
var x = 5; //local
var z = x + y;
console.log(z);
}
A global variable is also an object of the current scope, such as the browser window:
var dog = “Fluffy”;
console.log(dog); //Fluffy;
var dog = “Fluffy”;
console.log(window.dog); //Fluffy
It’s a best practice to minimize global variables. Since the variable can be accessed anywhere in the program, they can cause strange behavior.
References:
Additional Info:
- JavaScript Best Practices: Avoid Globals
- What's the difference between a global var and a window.variable in javascript?
The scope of JavaScript variables are either global or local. Global variables are declared OUTSIDE the function and its value is accessible/changeable throughout the program.
You should ALWAYS use var to declare your variables (to make locally) else it will install GLOBALLY
Take care with the global variables because they are risky. Most of the time you should use closures to declare your variables. Example:
(function(){
var myVar = true;
})();