Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a function in JavaScript:

function test() {
  console.log(arguments.length);
}

if I call it with test(1,3,5), it prints out 3 because there are 3 arguments. How do I call test from within another function and pass the other function's arguments?

function other() {
  test(arguments); // always prints 1
  test(); // always prints 0
}

I want to call other and have it call test with its arguments array.

share|improve this question

2 Answers 2

up vote 4 down vote accepted

Take a look at apply():

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

function other(){
    test.apply(null, arguments);
}
share|improve this answer
2  
I think you meant test.apply(this, arguments); –  Malvolio Nov 9 '13 at 2:11
    
"if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed." But yeah, it will work either way. this only needs to be used when you actually want to pass it. –  FabianCook Nov 9 '13 at 2:14
    
Works perfect, thanks! –  at. Nov 11 '13 at 1:30

Why don't you try passing the arguments like this?

function other() {
  var testing=new Array('hello','world');
  test(testing); 
}
function test(example) {
  console.log(example[0] + " " + example[1]);
}

Output: hello world

Here's a working JSFiddle:

share|improve this answer
    
I think the OP just wants to know how to pass dynamic parameters to other functions without hardcoding –  AlexCheuk Nov 9 '13 at 2:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.