0

I'm going to make a function that makes a random number that isn't equal to a specified number.

var number = 5;
var randnum2 = getrandnum(number);

function getrandnum(oldrandnum) {
  var results = Math.round(Math.random() * 7);
  if (results == oldrandnum) {
    getrandnum(oldrandnum);
  } else {
    return results;
  }
};

console.log(randnum2);

Explanation:

getrandnum is my function and it generates a random number that doesn't equal 5.

My problem is that the results will be NaN some times.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
alireza
  • 25
  • 5
  • 3
    Replace `getrandnum(oldrandnum);` with `return getrandnum(oldrandnum);`. – Karan Apr 28 '22 at 11:02
  • 1
    As you have not use `return` so it will not return any value till the end of the function and hence you will return `undefined`. Which you might be processing further and getting that NaN value. – Karan Apr 28 '22 at 11:06
  • oh thank you so much this my first question in stack overflow that i get the answer – alireza Apr 28 '22 at 11:08

1 Answers1

1

You should do return getrandnum(oldrandnum); instead of getrandnum(oldrandnum);

geertjanknapen
  • 1,159
  • 8
  • 23