1

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;

3 Answers 3

4

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.

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

4 Comments

I know generally what "call" does, but can you explain how it is working exactly in the example code you wrote. Thank you.
@mjmitche The arguments variable is an object, not an array, although it exposes some array like properties. To be able to call shift() on it, we need it as a real array. To do that, we can call the Array's slice() on the arguments array, using call() to pass the object as this. When using slice() with no arguments, it returns a copy of the object as an array (or a copy of an array if used on a standard array).
thanks, so if you need arguments as an array to call shift() on it, and if slice() returns a copy of the object (i.e. arguments) as an array, I dont understand why you need to use "call() to pass the object as this." Slice turns it into an array, and shift works on the array. Why cant it be that simple. If you have time to clarify, please do. Thanks again.
@mjmitche Because when you do slice() normally, the array is this. call() lets you call a function and set the this variable with its first argument.
0

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

You stop before it hits the callback argument

Comments

0

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

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.