You should understand the difference and then choose for yourself.
Basically, you have these two patterns:
x as global variable:
var x = 1;
var f = function() {
console.log('x in f:', x);
x = 2;
}
console.log('x before f:', x);
f();
console.log('x after f:', x);
and x as argument:
var x = 1;
var f = function(x) {
console.log('x in f:', x);
x = 2;
}
console.log('x before f:', x);
f(x);
console.log('x after f:', x);
There two main differences:
if f
uses a global variable, it is going to modify the global variable, whereas if it works with an argument, it does not affect any variables visible outside, i.e. the first code writes x after f: 2
, whereas the second writes x after f: 1
if f
uses a global variable, then it becomes less convenient to pass it different values. With an argument, you don't even need a global variable, you can call f(1); f(2); f(3456);
. With global vaiables, you would accomplish the same with var x=1; f(); x=2; f(); x=3456; f();
.
Instead of going more into details, I'll give you a link: Why are global variables evil?
Anyway, there are cases when global variables are good! I would make a global variable for a value which is constant and used by multiple functions (var GRAVITY = 9.81;
or var BASE_URL = "https://stackoverflow.com/";
)