javascript unassigned default function parameters-Collection of common programming errors
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?
-
It’s a private variable within the function scope. it’s ‘invisible’ in the global scope.
as for your code you better write like thisfoo = function(a){ if (typeof(a)=="undefined") a = "Some value"; // something done with a return a; }
because
!a
can be true for0
, anempty string ''
or justnull
. -
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 dofunction ($){....}(JQuery);
so you know that$
will always be a variable for the JQuery framework. -
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'
Originally posted 2013-11-09 19:44:09.