4

My issue is best illustrated with a small code example available on JsFiddle:

function a() {
    alert("a: " + arguments.length);
    b(arguments);
}

function b() {
    alert("b: " + arguments.length);
}

a(33,445,67);

I have a function a called with a variable number of arguments, and I would like to call b with these arguments. Unfortunately, when I run the code above, it displays respectively 3 and 1, rather than 3 and 3.

How can I call b with all the arguments received in a?

1
  • You already call b with all the arguments, but like adeneo said, you call it with the argument-Object [33,445,67], this means your argument-Object in b looks like this [[33,445,67]]. Commented Mar 27, 2014 at 10:00

1 Answer 1

6

arguments is an array-like object corresponding to the arguments passed to a function, so when b() is called there is only one argument, the array.
You can use apply(), which accepts the arguments as an array instead

function a() {
    alert("a: " + arguments.length);
    b.apply(undefined, arguments);
}

function b() {
    alert("b: " + arguments.length);
}

a(33,445,67);

FIDDLE

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

8 Comments

Actually b.apply(null, arguments); or a relevant first argument will return the desired result.
@Arbel - Why would null be more relevant than this when both functions are in the same parent scope ?
@adeneo: "Why would null be more relevant than this when both functions are in the same parent scope ?" Scope and this have almost nothing to do with one another, in JavaScript. this is (until ES6's arrow functions) set primarily by how a function is called, not where it's defined.
@T.J.Crowder - That's true, but in this case the functions are both defined in the same scope, and a() is called from that scope, so this would have the correct value, but as it's not used anyway it doesn't really matter.
@adeneo: Right. But again, I would really stay away from combining "scope" and "this" when talking about JavaScript, as they really are unrelated, and the fact they're unrelated but people tend to think they're related is one of the biggest problems people have with JS.
|

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.