0

I have one doubt here that I need to pass n nos of values as argument and calculating the total sum of it using Javascript. I am explaining some sample code below.

function add(a,b,c) {
  return a+b+c;
}



var data =add(5,6,7);

console.log(data)

Here I am passing only 3 arguments to the function but I need to pass n numbers of argument to the function like inside function its known how many values have passed as argument and final I need the total sum and return it.

subhra_edqart
  • 183
  • 1
  • 11
  • 5
    Modern JS lets you define explicitly a variadic parameter by using rest syntax. So it would look like: `function add(...nums) { /*your code*/ }` The `nums` will be an array of whatever was passed. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters –  Jun 21 '20 at 07:37
  • I'd suggest you to either create a class and call it's object, so with each argument you'll be creating a new instance of the class, OR, try passing arguments as an array/vector!! – Shashank Shukla Jun 21 '20 at 07:38
  • @slappy: Yes you are right. – subhra_edqart Jun 21 '20 at 07:39
  • `add = (...arg) => [...arg].reduce((a, b) => a + b, 0)` – Dhaval Marthak Jun 21 '20 at 07:40

2 Answers2

2

You can either reduce over it to sum all if you want to write it in a functional way like

function add(...numbers) {
  return numbers.reduce((acc,no) => return acc + no),0);
}

or by using arguments keyword knowing it's only available if the function is normal function, not an arrow function. here's a ref https://stackoverflow.com/a/38567145/1888435

also, arguments aren't an array it's an array-like and if you checked typeof arguments it will give you object.

Reem
  • 150
  • 2
  • 15
0

As @slappy said you can get parameters as array

function add(...numbers){
  // Values reach as array
  console.log(numbers)
  // Here you should use array inner functions
  return numbers.reduce((sum,value) => sum+value, 0)
}

let data = add(5,6,7);
console.log(data)
HYAR7E
  • 194
  • 2
  • 10