Reputation: 273
In the following function:
foo = function(a){
if (!a) a = "Some value";
// something done with a
return a;
}
When "a" is not declared I want to assign a default value for use in the rest of the function, although "a" is a parameter name and not declared as "var a", is it a private variable of this function? It does not seem to appear as a global var after execution of the function, is this a standard (i.e. consistent) possible use?
Upvotes: 4
Views: 2757
Reputation: 7320
It's a private variable within the function scope. it's 'invisible' to the global scope.
As for your code you better write like this
foo = function(a){
if (typeof a == "undefined") a = "Some value";
// something done with a
return a;
}
Because !a
can be true for 0
, an empty string ''
or just null
.
Upvotes: 4
Reputation: 15962
Parameters always have private function scope.
var a = 'Hi';
foo = function(a) {
if (!a) a = "Some value";
// something done with a
return a;
};
console.log(a); // Logs 'Hi'
console.log('Bye'); // Logs 'Bye'
Upvotes: 0
Reputation: 115488
Yes, in this context a
has a scope inside the function. You can even use it to override global variables for a local scope. So for example, you could do function ($){....}(JQuery);
so you know that $
will always be a variable for the JQuery framework.
Upvotes: 0