Search code examples
javascriptfunctionreturn

Why does Javascript function returns undefined after completion


That's the function:

function randomNum(n) {
  const numbers = [1,2,3,4,5,6,7,8,9,10]
  if(numbers.includes(n)) {
    console.log('ok')
  } else {
    console.log('Choose a value between 1 and 10')
  }
}
console.log(randomNum(5))

Sorry if it's a simple problem, but i can't figure it out, i'm kinda new to programing. The function is returning 'undefined' after 'ok' or 'Choose a value between 1 and 10'.


Solution

  • Instead of using console.log(<value>);, try using a return <value>; statement. At the moment, your code runs the function randomNum, prints the result to the console, then prints the return value from the function. Without an explicit return statement, this return value is undefined.

    I hope this helps!