How to generate a random number from 2 numbers

Viewed 728

I've searched a lot for generating a random number but all I got is generating for a range between a or b.

I'm trying to get a number from a or b, i.e. either a or b, none from in between.

This returns the first value only var number = 1 || 9; \\9

3 Answers

So Math.random() randomly generates a number between 0.0 and 1.0. Math.random() < 0.5 has a 50% percent chance of either being true or false. This way you can select one of two numbers with equal probability.

let number = Math.random() < 0.5 ? 1 : 9;
console.log(number)

You can store your two numbers in an array and get a random index of that array. Here's an example:

var yourTwoNumbers = [2,5]
console.log(yourTwoNumbers[Math.floor(Math.random() * yourTwoNumbers.length)]);

The same asked here: How to decide between two numbers randomly using javascript?

There is already an answer with explanations.

The Math.random[MDN] function chooses a random value in the interval [0, 1). You can take advantage of this to choose a value randomly.

const value1 = 1
const value2 = 9;
const chosenValue = Math.random() < 0.5 ? value1 : value2;
console.log(chosenValue)

Related