Reputation: 13
Uses rest parameter and for...of loop for an array...
function average(...nums) {
let total = 0;
for(const num of nums) {
total += num;
}
let avr = total / arguments.length;
return avr;
}
console.log(average(2, 6));
console.log(average(2, 3, 3, 5, 7, 10));
console.log(average(7, 1432, 12, 13, 100));
// returns NaN - required to return 0.
console.log(average());
Problem: for no arguments - console.log(average());
- Returns NaN where the correct answer must be 0.
Any good shorthand solution here?
Upvotes: 1
Views: 134
Reputation: 822
It's not very elegant but...
const average = (...arr) => arr.reduce( ( acc, current ) => acc + current, 0 ) / (arr.length || 1) ;
console.log(average(2, 6));
console.log(average(2, 3, 3, 5, 7, 10));
console.log(average(7, 1432, 12, 13, 100));
console.log(average());
Upvotes: 0
Reputation: 76
You could just check arguments.length at the start of the function. Something like:
function average(...nums) {
//check if no args are passed & return 0
if(arguments.length === 0) return 0;
//else
let total = 0;
for(const num of nums) {
total += num;
}
let avr = total / arguments.length;
return avr;
}
Upvotes: 3
Reputation: 151
Modify the function as -
function average(...nums) {
if(nums.length === 0){
return 0;
}
let total = 0;
for(const num of nums) {
total += num;
}
let avr = total / arguments.length;
return avr;
}
Upvotes: 4