Search code examples
javascriptfunctiontuplesreturnarguments

Passing return value as function arguments (tuple)


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.


Solution

  • Use the spread syntax:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

    function foo(initial_state, indexer = 0) {
      return [initial_state, indexer + 1];
    }
    
    console.log(foo(...foo(0, 0)));