-2

I am trying to write a code that makes a new random number every time it runs. I have a function here, there is no syntax errors but why does my code not run? And when it does all it does is spit out undefined?

function GetRandomInteger(a, b){

    if (a > b){
        small = b;
        large = a;
    }
    else{
        small = a;
        large = b;
    }

}

var randomInt = GetRandomInteger(1,5);

console.log(randomInt);
iconstar
  • 15
  • 1

2 Answers2

0

this should look like this

function GetRandomInteger(a, b){
    let res = {};
    if (a > b){
        res.small = b;
        res.large = a;
    }
    else{
        res.small = a;
        res.large = b;
    }

    return res;
}

var randomInt = GetRandomInteger(1,5);

console.log(randomInt);

but this will still not work as "advertised". You want the random number you will not get this like that. You have to use Math.random. Write math random in browser there are so many answers and I don't want to replicate them, also I think that probably there is an answer in Stackoverflow already.

Jacck Mark
  • 127
  • 1
  • 10
  • just in case if you want more examples than these that Martin gave, here someone had exactly the same problem https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript – Jacck Mark Jul 19 '21 at 09:59
0

As per my comment, your function does not currently return any value, which is why the output of your function is undefined.

Also, to make a random number you are better using Math.random() which is a built-in function to accomplish this. An example would be:

function GetRandomInteger(a, b) {
  return Math.round(Math.random() * (b - a) + a);
}

var randomInt = GetRandomInteger(1, 5);

console.log(randomInt );
console.log(GetRandomInteger(1, 5));
console.log(GetRandomInteger(1, 5));

This uses Math.random() to make a random number between 0 and 1. It then multiplies this by the range between a and b, and then adds the minimum value a. Finally, it uses Math.round() to round the result to a whole number.

In the case of the example snippet above, this returns a number between 1 and 5 (inclusive).

If the case is that a can be larger than b sometimes, the following modification will permit this to work still:

function GetRandomInteger(a, b) {
  if (a <= b) {
    return Math.round(Math.random() * (b - a) + a);
  } else {
    return Math.round(Math.random() * (a - b) + b);
  }
}

var randomInt = GetRandomInteger(1, 5);

console.log(randomInt );
console.log(GetRandomInteger(1, 5));
console.log(GetRandomInteger(1, 5));
console.log(GetRandomInteger(5, 1));
console.log(GetRandomInteger(5, 1));
Martin
  • 16,093
  • 1
  • 29
  • 48