sirKitty
sirKitty

Reputation: 143

Using only one parameter of a function in javascript

I'm writing an app in Javascript, and while I'm comfortable with the language, I was wondering about unused parameters.

Say I have a function as follows:

function test(data, complete){
    if (data){
        return complete(null, 'yes');
    }
    else{
        return complete('error', null);
    }
}

I call that function with a callback, but am only interested in checking for an error - if the data exists, I can move forward with my program. Is it okay if I just pass the error parameter into the function?

test(data, function(err){
    if(err){
        //Uh Oh
    }
    else{
        //Keep going
    }
});

Or is it best if I pass both the error and the result (even though the result variable remains unused)?

test(data, function(err, result){
    if(err){
        //Uh Oh
    }
    else{
        //Keep going
    }
});

Upvotes: 0

Views: 513

Answers (2)

SLaks
SLaks

Reputation: 888293

It doesn't matter.

Function arguments are only used to create local variables.
You can pass any number of parameters to any function, no matter how its declared.

Upvotes: 2

Quentin
Quentin

Reputation: 944568

Is it okay if I just pass the error parameter into the function?

Yes. Arguments that don't receive an explicit value will receive undefined instead (but will still exist and be locally scoped so will still mask variables with the same name from a wider scope).

As an aside, any extra arguments will still be accessible through the array-like arguments object.

Upvotes: 4

Related Questions