Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can someone explain why i'm getting 9 & 5 instead of 36880 & 375

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading