How to get one digit random number in javascript?

Math.random() returns a float between 0 and 1, so just multiply it by 10 and turn it into an integer:

Math.floor(Math.random() * 10)

Or something a little shorter:

~~(Math.random() * 10)

DISCLAIMER:

JavaScript's math.rand() is not cryptographically secure, meaning that this should NOT be used for password, PIN-code and/or gambling related random number generation. If this is your use case, please use the web crypto API instead! (w3c)


If the digit 0 is not included (1-9):

function randInt() {
    return Math.floor((Math.random()*9)+1);
}

If the digit 0 is included (0-9):

function randIntWithZero() {
     return Math.floor((Math.random()*10));
}

var randomnumber=Math.floor(Math.random()*10)

where 10 dictates that the random number will fall between 0-9.