Home > Enterprise >  Why is my function returning undefined? Javascript
Why is my function returning undefined? Javascript

Time:09-22

I'm trying to create a function that returns the digital root of a number. I thought I had it figured out, but my function keeps returning undefined. Can someone tell me what's wrong?

Here's my code:

function digital_root(n) {

    if (n < 10){
        console.log(n)  //this works
        return n        //this returns undefined
    }
    
    var turnToArray = n.toString().split('')
    var joinArray = turnToArray.join(' ')
    result = eval(joinArray)
    digital_root(result)        

}


console.log(digital_root(120)) //should return 3

CodePudding user response:

If n >= 10 you don't return anything, i.e. change the last line of the function digital_root(n) to return digital_root(result).

CodePudding user response:

You need to return a value from the outer most recursive function.

Here is updated code.

function digital_root(n) {

if (n < 10){
    console.log(n)  //this works
    return n        //this returns undefined
}

var turnToArray = n.toString().split('')
var joinArray = turnToArray.join(' ')
result = eval(joinArray)
 return digital_root(result)        

}

CodePudding user response:

because you are looking to the wrong return

actualy your code is like this one

function digital_root(n)
  {
  if (n < 10)
    {
    console.log(n)  // this works
    return n        // this returns the same n to the parent recursive call
    }
    
  var turnToArray = n.toString().split('')
  var joinArray   = turnToArray.join(' ')
  result = eval(joinArray)
  digital_root(result)  // get the value 3

  return  // implicit return with the undefined value       
  }

your code should changed to

function digital_root(n) 
  {
  if (n < 10)
    {
    console.log(n)   
    return n       
    }
  let turnToArray = n.toString().split('')
  let joinArray = turnToArray.join(' ')
  result = eval(joinArray)
   
  return digital_root(result)     
  }

console.log(digital_root(120)) //  return 3

so simply:

function digital_root(n) 
  {
  if (n < 10) return n 
  return digital_root([...n.toString()].reduce((v,x)=>(v  =  x,v),0))
  }
  • Related