#### Apr 7, 2010

# Go random with JavaScript

One day, you must need code to get a random number, or values, in your program. Suppose you code for a game such as backgammon requires a roll of some dice on each move. Since there are 6 numbers on each die, you could calculate each roll by finding a random number from 1 to 6 for each die.Today you will learn going random with JavaScript.

### idea

In the dreamnight animation we needed*random positions*and

*random colors*for bubbles.

### Math.random()

The random() method returns a random number between 0 and 1.### Generating random number less than M

```
var randomnumber = Math.floor(Math.random()*(M + 1));
```

This will generate no between 0 and M### Generating random number between higher and lower

```
parseInt(rand_no = Math.floor((higher - (lower - 1)) * Math.random()) + lower);
```

### Generating random colors

` 'rgb('+Math.floor(Math.random()*255)+','+`

` Math.floor(Math.random()*255)+','+ `

` Math.floor(Math.random()*255)+')'; `

```
```

OR if you need it in hex - ```
Math.round(0xffffff * Math.random()).toString(16)
```

I hope now you are able to solve your

*problem you googled*.

Enjoy!!

Labels: Javascript

If anything helps, feel free to buy me a beer.

By : Motyar+ @motyar