Generate Random Numbers in Javscript

Steps to generate random numbers in Javscript.

Generate Random Numbers in Javscript

Posted in Code on February 3, 2016  – 1 min read

While working on a prototype of a web app, I needed to generate random boolean (true-or-false) values.

At first, I tried this:

var x = Math.random()>0.5;

Get this into a 2D array:

var array = [];
var 2DArray = [];

for(var i=0; i<10; i++) {
    array.push(Math.random()>0.5);
}

for(var i=0; i<10; i++) {
    2Darray.push(array);
        array[i] = Math.random()>0.5;
}

The above ended up in 10 identical subarrays in the 2D array. Not what I wanted.

So I dug in Google and found this, which is

var x = !!Math.floor(Math.random() * 2)

Voilà!