bhylu.com

Advertisements

JS Math Random

Math.random returns a value from zero up to, but not including, one. Scale and floor it to choose an array index.

Where to run this

This example uses the JavaScript console playground. Select Run to execute it; the example does not run on this lesson page.

A practical example

JavaScript

const tools = ["Brush", "Tape", "Ruler"];
const index = Math.floor(Math.random() * tools.length);
console.log(tools[index]);

What happens

One tool is selected; the result changes between runs.