I’m a beginner and I’m wondering how to create a function that multiplies an indeterminate number in Javascript

Asked

Viewed 41 times

-1

I’m a beginner in the world of programming and am doing my first projects in Javascript. I ran into this simple problem that I’m having trouble solving. I need a function that performs an operation at an undetermined amount of values. It does not necessarily have to be a multiplication, I would like to know for any operation (sum, subtraction, multiplication and division) how to create a function that calculates an indeterminate number of values that I pass. Always check the pre-determined amount of values. For example:

function mult (a,b) {
   console.log (a * b)
   
}

mult (2,3)

In the above case I can only pass two values. If you pass 3, it will discard the third element.

I would like to do an undetermined amount of values, either by passing the mult () 3 values or 10 values the function multiplies all. How can I do this?

1 answer

-1

This is very simple.

Every JS function has a local variable called arguments, which stores function parameters or arguments in Object form

In this example the function will do what you want

function mult (){ 
   let params = arguments;
   let result = 1;
   for(let i in params){
       result = result * params[i]; 
    }
   console.log(result);
   return result;
}
        
mult (2,3)
  • 1

    Thank you very much. I did not know the variable Arguments and this new knowledge was extremely useful. I was able to use this method for multiplication and for summation. But it’s going wrong for division and subtractions. I’m breaking my head here.

Browser other questions tagged

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