Personally, I never omit it. If you leave off the the var
keyword that variable becomes a global one if the variable is declared inside a function. This is because variables have function level scope in JavaScript. In the example you have given Namespace
will be a global variable whether you use var
or not because it is not declared inside of a function. You can test this theory out by adding var
to the Namespace
variable in example 1 below.
Example 1:
//I am a global variable with or without the var keyword because
//I am declared outside of a function.
Namespace = (function () {
return {
name: 'Module',
dep: ['d', 'a']
};
})();
function test(){
Namespace = "I was changed because i have global scope";
}
//Run the test function to gain access to the global variable inside.
test();
//You will see that the value was changed by calling the test function
console.log(Namespace);
Now if you put your Namespace
variable inside a function as it is now it will still be a global variable without the var
keyword. In the example below I have moved your Namespace
variable inside of function added the var
keyword to it to make it a non global function. If you remove the var
keyword from the Namespace
variable inside of the function in example 2 you will see that it will then be a global variable and the last console.log(Namespace)
call in the script will print out the Namespace
value from the getNameSpace
function.
Example 2:
function getNameSpace(){
var Namespace = (function () {
return {
name: 'Module',
dep: ['d', 'a']
};
})();
}
function test(){
Namespace = "I have global scope even inside a function because I am missing the var keyword.";
}
test();
//print the value of the global variable Namespace
console.log(Namespace);
//call get nameSpace
getNameSpace();
//This will still print the value from the test function because the variable inside of
//get Namespace has local or function level scope because it has the var keyword.
console.log(Namespace);
Hopefully all this makes more sense now. If it doesn't let me know I will try and help. A good thing to remember is to always use the var keyword and if you don't want another part of a script to access the variable directly then put it inside of function(also known as a closure).