Sahan Chinthaka
Sahan Chinthaka

Reputation: 116

How I make a function with unlimited parameters in js?

function add(args_list){
   var total;
   return totatl; // Output should be Total of args list
}
add(25,25,10); // 60

How I make this function with unlimited parameters

Upvotes: 3

Views: 1398

Answers (1)

Lyubomir
Lyubomir

Reputation: 20037

This is called Rest parameters

function add(...theArgs) {
  const sum = theArgs.reduce((acc, arg) => acc + arg, 0);
  console.log('Sum is', sum);
  
}
    
add();  // 0
add(5); // 1
add(5, 6, 7); // 3

Note: theArgs is an array, but you pass parameters to the function as you normally would, not as an array.

Upvotes: 6

Related Questions