DEV Community

Cover image for JavaScript Fundamentals: Math Object
Astrodevil
Astrodevil

Posted on • Edited on • Originally published at mranand.com

JavaScript Fundamentals: Math Object

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();
Enter fullscreen mode Exit fullscreen mode

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();
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Math.floor

Math.floor takes arguments.

const two = Math.floor(2.2598223);
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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.

If You ❤️ My Content! Connect Me on Twitter or Supports Me By Buying Me A Coffee☕

Top comments (0)