skip to Main Content

I’m trying to use the return value of my function as arguments for my function, however the fact that it’s a tuple is being problematic. This is further compounded by the fact that it will not always be a tuple.

function foo(initial_state, indexer = 0) {
// does something

return [initial_state, indexer + 1];
}

I want to be able to sometimes use the function as simply

foo(initial_state);

but also I want to call the function with the return, as such..

foo(foo());

Instead of the desired behavior, the tuple is put into initial_state, whereas I would want it deconstructed to match the arguments in the function.

I can obviously do a temporary variable like

let some_state, some_index = foo();
foo(some_state, some_index);

But that seems very ugly. There has to be a better way.

2

Answers


  1. Use the rest parameters:

    function foo(initial_state, indexer = 0) {
      return [initial_state, indexer + 1];
    }
    
    console.log(foo(...foo(0, 0)));
    Login or Signup to reply.
  2. You can’t create temporary variable like that as well actually no. That way, only some_index will be assigned to foo()s return value. some_state will be undefined.

    But you can just spread the array to another function.

    foo(...foo(state, indexer))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search