RyanP13
RyanP13

Reputation: 7753

JavaScript - referencing arguments from within a function

Recently i found myself attaching function arguments to a variable inside the function scope so that i was not referencing the argument every time it was used.

Is there any benefit to this practice?

For example:

function populateResultCount(count){
    var count = count;
    return $('.resultCounter').text(count);     
};

Could easily be re-written like so:

function populateResultCount(count){
    return $('.resultCounter').text(count);     
};

And would still function correctly.

Upvotes: 0

Views: 80

Answers (5)

Flambino
Flambino

Reputation: 18783

All the other answers are correct: There's no reason to "re-assign" a passed argument inside the function.

The only thing I can think of, where you'd mess with reassigning arguments, is if you have optional arguments/default values

function xyz(optionalArgument) {
    optionalArgument = optionalArgument || "no argument given";
    ...
}

But in that case, it'd be better to write it as

function xyz( /* optionalArgument */ ) {
    var optionalArgument = arguments[0] || "no argument given";
    ...
}

Note that the || trick will give you the right-hand side's value, if the left-hand side is a falsy value. I.e. if you're ok with the optional argument being something that's falsy (like explicitly passing null, 0, etc), you'd have to do something like var arg = typeof arguments[x] === 'undefined' ? defaultValue : arguments[x];

Upvotes: 1

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

function Test (count) {
    this.increment = function() {
        count++;
    }

    this.getCount = function() {
        return count;
    }
}

var test = new Test(10);


<button onclick="test.increment(); alert(test.getCount());">Increment</button>

You can do something like that even with the argument. So I think they are same.

Upvotes: 1

darioo
darioo

Reputation: 47213

If you're not using the argument that's passed in, there is no difference. In your first example, you can potentially confuse future maintainers because of var count = count, i.e., you're declaring a variable that has the same name as the argument, and that isn't a best practise.

So, if you can, use your second form. Its intent is clearer and there is no room for confusion.

Upvotes: 1

65Fbef05
65Fbef05

Reputation: 4522

I can see no benefit to this unless you are manipulating the data somehow. Your variable without the additional assingment can still not be accessed outside of the function.

Upvotes: 1

RichieHindle
RichieHindle

Reputation: 281835

There's no functional difference between the two. Go with the simpler version.

Upvotes: 3

Related Questions