In reference to setting global and local variables, I’ve read about memory leaks and how to avoid them. I am still a little confused.
Let’s just say that these examples occur deep within pages, where there are other global and local variables being used.
If I don’t plan to reuse a variable, should I or should I not use var?
If I use var once within a function, do I need to use it again when I manipulate or modify the variable?
// EMAMPLE ONE
$("#AddBrandSave").click(function() {
// DO THIS?
Brand = $("#Brand").val();
// OR DO THIS?
var Brand = $("#Brand").val();
});
// EMAMPLE TWO
$("#AddBrandSave").click(function() {
// DO THIS?
Brand = $("#Brand").val();
Brand = Brand.substring(7);
Brand = Brand.someMathFunction();
// OR DO THIS?
var Brand = $("#Brand").val();
Brand = Brand.substring(7);
Brand = Brand.someMathFunction;
// OR DO THIS?
var Brand = $("#Brand").val();
var Brand = Brand.substring(7);
var Brand = Brand.someMathFunction();
});
Understanding var
Javascript has exactly two levels of scope, global and function. When you use the
var, the declaration of that variable is hoisted to the top of the scope it is in. For instance:is interpreted as
If you had not included
varinside a function, “Brand” will be declared in the global scope, sois interpreted as:
This is why it is suggested that you declare any variables you intend to use in a function with
varat the top of that function, because that is what technically happens anyway so it makes it easier to understand.Using
varmultiple times for the same variable could cause issues because it makes the interpreter work a little harder to check if that variable already exists – I don’t know if it causes memory leaks, but why risk it?