Skip to main content

Randomness

Understanding Math.random and Math.floor

Updated 1 min readMarkdown
Part of seriesJavascript
Randomness

As my journey to being a Web Developer continues, I have carried on my Javascript learnings via Scrimba.

Today I learnt about Math.random and Math.floor and how they work.

Math.random

If prompted, Math.random will give you a random (this in itself can be argued) number between 0 and 1. So it might be 0.2525357 or 0.9234 etc.

So how would we get a random number between 1 and 10? Well could start with this. This gives us a random number from 0 to 9, and then we +1 so we include 10 and exclude the 0.

let random = (Math.random()*10)+1
console.log (random)

Math.floor

This works well but it still decimal places in the way. If we apply Math.floor, then this will effectively snip off the decimal places.

let random = Math.floor((Math.random()*10)+1)
console.log (random)

This will now give us a random number between 1 and 10.

About the author

  • Learning to Code whilst having several projects under my belt.

No comments yet. Be the first to comment.

Javascript

Part 1 of 1

My Javascript Learning Joruney