mjmitche
mjmitche

Reputation: 2067

JavaScript "arguments" -passing a function with other parameters

Function multiply below is passed a callback function "addOne". Function multiply returns [3,5,7].

Since the callback function addOne is one of the arguments of function multiply, and since the arguments of function multiply are all multiplied by 2, why doesnt the callback function itself (i.e. addOne) get multiplied by 2? In other words, instead of function multiply returning [3,5,7], I would have expected it to return [3,5,7, NAN] since the function is not a number?

Does JavaScript interpreter just somehow know not to multiply it by 2?

function addOne(a) {
return a + 1;
}

function multiply(a,b,c, callback) {
    var i, ar = [];
    for (i = 0; i < 3; i++) {
        ar[i] = callback(arguments[i] * 2);
    }
    return ar;
}



myarr = multiply(1,2,3, addOne);
myarr;

Upvotes: 1

Views: 369

Answers (3)

alex
alex

Reputation: 490143

Because your loop's condition is <3 (hehe) which means it won't subscript the callback (the last element).

You should consider making the callback the first argument always, and splitting the arguments like so...

var argumentsArray = Array.prototype.slice.call(arguments),
    callback = argumentsArray.shift();

jsFiddle.

Then, callback has your callback which you can call with call(), apply() or plain (), and argumentsArray has the remainder of your arguments as a proper array.

Upvotes: 4

Yasser
Yasser

Reputation: 1808

Because you are running the the loop for the first 3 args only. i < 3 runs for i=0, i=1,i=2

Upvotes: 0

JohnP
JohnP

Reputation: 50009

This line for (i = 0; i < 3; i++) { is protecting you.

You stop before it hits the callback argument

Upvotes: 0

Related Questions