4

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?

3
  • 1
    Any argument provided in the function signature is scoped to the function only. The function you have written as an example is correct. Commented Aug 13, 2012 at 20:57
  • 1
    A common short hand for this is, return a || "Some value" instead of if(!a) a = "some value"; return a; Commented Aug 13, 2012 at 20:58
  • 2
    better use if(typeof a == "undefined") Commented Aug 13, 2012 at 20:58

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Good point. a = a || "some value" has the same failings as if(!a).
a will always be either an object or undefined, but yes point taken
0

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.

Comments

0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.