Math.random()

I'm starting a new vibe here with LoFi. I want to share smaller, more bit-sized pieces of information. Little nuggets that'll hopefully help you with your creative coding.

Creative coding tends to mean that you'll use some different skills to UI development, but also potentially pieces of JavaScript that you havent used before. The champ of these JavaScript APIs is Math. And within Math, random() is king!

Math.random() only does one the, return a random number between 0-1. It's as simple as this.

// assigns a random number to num
// eg: 0.6547161150703487
const num = Math.random();

That might not sound like a lot, but you can do one or two more things to get any random number you want! Need a random number between 0-10, just multiply by 10.

// assigns a random number to num
// eg: 8.558616898572417
const num = Math.random() * 10;

You might notice that this is a float, or a number with a decimal in normal language. Want those decimals to go away? Add a Math.floor().

// assigns a random number to num
// eg: 3
const num = Math.floor(Math.random() * 10);

It's important to note here that this will only ever return the numbers 0 - 9. This is because we're flooring, rather than rounding. This comes in really handy when trying to pick a random item from an array.

const arr = ["Paul","John","George","Ringo"];

// assigns a random number to num
const num = Math.floor(Math.random() * arr.length);

// assigns a random item to musician
// eg: 'George'
const musician = arr[num];

We can already get a number between 0-10, but what if we wanted a number between 5-10? First, we would need to get a number between 0-5, then simply add 5.

// assigns a random number to num
// eg: 'George'
const num = (Math.random() * 5) + 5;

This isnt very intuitive at first. We do two things, get a random number of the max - min, then after we add the min again. Putting that all into a function, we get.

const rand = (max = 1, min = 0) => {
  return (Math.random() * (max-min)) + min;
}

// assigns a random number to num
// eg: 6.255813315992315
const num = rand(10,5);

Why max first? Most often you'll just need a number between 0-max, so this way we can only set max if we like.