For my return, I’m getting 9 and 5 instead of 362880 and 375. Can someone explain what I missed?
function multiplyAll(num){ // declare a function name multyplyAll with a num parameter
for (let i = 0; i < num.length; i++){ // for loop to iterate base on the length of the parameter.
num *= num[i] // multiplies them all together.
}
return num // function outpout
}
console.log(multiplyAll(9, 4, 5, 6, 7, 2, 1, 8, 3)) // should log: 362880
console.log(multiplyAll(5, 5, 5, 3)) // should log: 375
>Solution :
When you are using num without rest parameters then only the first value will get assign to num. You are treating like num is an array but num is just of type number
There is no length property on num, Because num is of type number. It won’t run the for loop and return the first element i.e 9 and 5
You should use collect then in to an array using rest parameters
function multiplyAll(...num) {
// declare a function name multyplyAll with a num parameter
let res = 1;
for (let i = 0; i < num.length; i++) {
// for loop to iterate base on the length of the parameter.
res *= num[i]; // multiplies them all together.
}
return res; // function outpout
}
console.log(multiplyAll(9, 4, 5, 6, 7, 2, 1, 8, 3)); // should log: 362880
console.log(multiplyAll(5, 5, 5, 3)); // should log: 375
You can also use reduce here as:
function multiplyAll(...num) {
return num.reduce((acc, curr) => acc * curr, 1);
}
console.log(multiplyAll(9, 4, 5, 6, 7, 2, 1, 8, 3)); // should log: 362880
console.log(multiplyAll(5, 5, 5, 3)); // should log: 375