How to make a function with quantity of parameters 'infinite'?

Asked

Viewed 161 times

3

How do I do a Javascript function that can receive a quantity infinite parameter?

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 do the same thing for each parameter passed to him.

A simple example would be something like:

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

Only instead of accepting 4 parameters, accept a quantity of 2 to as many as the person puts (given the limit supported by the language)

As a bonus question, if you know, what is the limit of parameters that a function can receive in Javascript?

1 answer

7


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

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

n will be an array within the function multiply

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 for in Javascript?

  • I get it, thank you. If I may ask this here, is there a way for me to refer to a specific parameter between the indefinite amount of parameters? From what I understand I would take the index of n?

  • @Máttheusspoo n will be an array. Can understand?

  • Yes, I understood that, I was actually confirming if my reasoning was correct (if I could use n[3] to refer to the fourth parameter passed in the function, for example) .

  • @Máttheusspoo yes, you can use it the way you referred!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.