0

I am using rest parameter to calculate the sum in javascript but as per my code its throwing the following error.

Error::

error: unknown: Rest element must be last element (4:19)

I am explaining my code below.

function add(...num, cb) {
  let result= num.reduce((a,i) => {
    return a+i;
  })
  cb(result);
}

add(2,3,4,(item) => {
  console.log(item);
})

Here I need to use rest param using add the all value and return result using callback. But its throwing error.

subhra_edqart
  • 183
  • 1
  • 11
  • Did you search for the error? [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/a/261593/3082296) – adiga Jun 27 '20 at 07:50

1 Answers1

1

The error says it all. Rest params must me the last argument to add function.

The following snippet will work:-

function add(cb,...num) {
  let result= num.reduce((a,i) => {
    return a+i;
  })
  cb(result);
}

add((item) => {
  console.log(item);
},2,3,4)
Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39