How to make a function with infinite number of parameters?

2

How do I make a JavaScript function that can receive an infinite amount of parameters?

When I refer to infinite , I am aware that there is a limit, but I want to do a function where the person can pass as many parameters as he wants: one, two, five, ten, and same thing for each parameter passed to it.

A simple example would look something like:

function multiplicar(n1, n2, n3, n4) {
  return n1*n2*n3*n4;
}

But instead of accepting 4 parameters, accept an amount of 2 as many as the person puts (given the limit supported by the language)

As a bonus question, if so, what would be the limit of parameters that a function can receive in JavaScript?

    
asked by anonymous 25.07.2018 / 14:32

1 answer

6

Use the 3 points before a parameter. It is for you to use n parameters.

Your name is Spread and can be seen more about documentation >.

  

n will be an array within the multiply function

function multiplicar(...n) {
  let valor = n.reduce(function (valorAcumulado , valorAtual) { 
    return valorAcumulado *= valorAtual;
  }, 1)
  console.log(valor);
}

multiplicar(2,3,4);

I recommend reading: What is the '...' operator used for Javascript?

    
25.07.2018 / 14:36