Spread syntax is a way of calling a JavaScript object with any number of arguments. So, you can make function like this:
const avg = (first = 0, ...others) {
let sum = first;
for (const value of others) { sum += value; }
return sum / (1 + others.lenght);
}
This can be called with any number of arguments. One thing to note is that if the argument is an array, the result will be NaN
. But, you can call it by using the ...
operator in front of the array. This will work:
let myArr = [1, 3, 5];
avg(...myArr);