Unassigned functions to javascript functions by default

In the following function:

foo = function(a){ if (!a) a = "Some value"; // something done with a return a; } 

If "a" is not declared, I want to assign a default value for use in the rest of the function, although "a" is the name of the parameter and is not declared as "var a", is this a private variable for this to function? It doesn't seem to look like a global var after the function is executed, is this a standard (i.e. sequential) possible use?

+4
source share
3 answers

This is a private variable within the scope. it is "invisible" to the global scale.
As for your code, it is better to write like this:

 foo = function(a){ if (typeof a == "undefined") a = "Some value"; // something done with a return a; } 

Because !a may be true for 0 , an empty string, '' or just null .

+3
source

Yes, in this context, a has a region inside the function. You can even use it to override global variables for a local scope. For example, you can do function ($){....}(JQuery); so you know that $ will always be a variable for the jQuery structure.

0
source

Parameters always have a private function area.

 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' 
0
source

All Articles