-1

I'm trying to print the return value of a function but I just can't seem to do it. I keep getting undefined for the last line.

let count = 0;
   
   
   function product(num){
     let result = 1;
     strNum = num.toString()
     strNumArr = strNum.split("")
     
     if(strNum.length === 1){
       return count;
     }
     
     
     for(let i = 0; i< strNum.length; i++){
       result *= parseInt(strNumArr[i])  
     }
     count++;
     //console.log(count)
     product(result)
   }
  
 let bool = product(39);
 console.log(product(39));

I know I'm missing something basic, but I don't know what it is.

1
  • 2
    What is your function supposed to do? What is the purpose of the count variable? Commented Jan 9, 2021 at 22:02

2 Answers 2

2

If I understand what you are trying to achieve correctly, here is a working version of your code.

   function product(num){
     let result = 1;
     strNum = num.toString()
     strNumArr = strNum.split("")
     
     if(strNum.length === 1){
       return num;
     }
     
     
     for(let i = 0; i< strNum.length; i++){
       result *= parseInt(strNumArr[i])  
     }
     return result;
   }
  
 console.log(product(39)); // should return 27
 console.log(product(5)); // should return 5
 console.log(product(234)); // should return 24

You should return the result after you are done with the loop.

By the way the same can be achieved with a one liner. For example

function product(num) { 
    return Array.from(String(num).split('')).reduce((c,p) => p * c, 1)
}
Sign up to request clarification or add additional context in comments.

Comments

0

Replace product(result) to return product(result). This way if the function calls itself it returns the value generated in the nested function call.

let count = 0;
   
   
   function product(num){
     let result = 1;
     strNum = num.toString()
     strNumArr = strNum.split("")
     
     if(strNum.length === 1){
       return count;
     }
     
     
     for(let i = 0; i< strNum.length; i++){
       result *= parseInt(strNumArr[i])  
     }
     count++;
     //console.log(count)
     return product(result)
   }
  
 let bool = product(39);
 console.log(product(39));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.