Today is the 4th day of my #100DaysOfCode journey with JavaScript.
I write about my learnings in an explained way through my blogs and socials. If you want to join me on the learning journey, make sure to follow my blogs and social and share yours too. Let’s learn together!🫱🏼🫲🏼
This Article is a part of the JavaScript Fundamentals series.
Today, I learned about Math.random
, Math.floor
Functions and to call a function within our function.
Math.random
In JavaScript, there are many math utilities on the Math
object. To get a random number we can call the Math.random
function.
const myRandomNumber = Math.random();
The above line will return some number between 0
and 1
(not including 1
). Math.random
can also be used to generate random numbers between the range.
Example: Inside getRandom
, get a random number from the Math.random()
function. Then, return that number!👇🏼
function getRandom() {
return Math.random();
}
A random number between 0
and 100
could be created by simply multiplying the output:
// randomNumber will be between 0 and 100
const randomNumber = Math.random() * 100;
We could multiply and then add to get a random number between 15
and 100
:
// randomNumber will be between 15 and 100
const randomNumber = (Math.random() * 85) + 15;
Math.floor
Math.floor
takes arguments.
const two = Math.floor(2.2598223);
Math.floor
function will take 2.2598223
and return 2
. A number will be rounded to the nearest integer using this function. For instance, if the input was 2.9999
, the method would round it to 2
.
Example: Take the argument x
and use Math.floor
to turn it into an integer without the values after the decimal place. Once you have this floored value, return it!
function getFloor(x) {
return Math.floor(x);
}
Conclusion
Ending with an extra bit of information about JavaScript functions…
The JavaScript Math object allows us to perform mathematical tasks on numbers. There are various math object properties.
Today I learned about Math.random, Math.floor Functions in JavaScript.