Simplify passing same arguments two two different functions

Tags:



I’m calling two functions to which I pass the identical arguments.

foo1('p1','p2','p3','p4','p5');

//...

foo2('p1','p2','p3','p4','p5');

Can I do something like the following, to declare the arguments once and then pass it to both functions?

var params = 'p1','p2','p3','p4','p5'; // what's the syntax here?

foo1(params);
foo2(params);

Answer

Yes, you can: Put them in an array and use ... (in modern environments) or apply (in older environments):

In modern environments:

const params = ['p1','p2','p3','p4','p5'];
// −−−−−−−−−−−−^−−−−−−−−−−−−−−−−−−−−−−−−^

foo1(...params);
// −−^^^
foo2(...params);
// −−^^^

In older environments:

var params = ['p1','p2','p3','p4','p5'];
// −−−−−−−−−−^−−−−−−−−−−−−−−−−−−−−−−−−^

foo1.apply(null, params);
// −^^^^^^^^^^^^
foo2.apply(null, params);
// −^^^^^^^^^^^^


Source: stackoverflow