user20676816
user20676816

Reputation:

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'.

Upvotes: 1

Views: 85

Answers (2)

PiCO
PiCO

Reputation: 47

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!

Upvotes: 0

protob
protob

Reputation: 3583

Your function doesn't return anything, it only logs. To fix add return.

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

Upvotes: 0

Related Questions