JavaScript math object


The JavaScript Math object allows you to perform mathematical tasks on numbers.


                      Math.PI;            // returns 3.141592653589793
                  

Math.round()

Math.round(x) returns the value of x rounded to its nearest integer:


                      Math.round(4.7);    // returns 5
                      Math.round(4.4);    // returns 4
                

Math.pow()

Math.pow(x, y) returns the value of x to the power of y:


                    Math.pow(8, 2);      // returns 64
                

Math.sqrt()

Math.sqrt(x) returns the square root of x:


                    Math.sqrt(64);      // returns 8
                

Math.abs()

Math.abs(x) returns the absolute (positive) value of x:


                    Math.abs(-4.7);     // returns 4.7
                

Math.ceil()

Math.ceil(x) returns the value of x rounded up to its nearest integer:


                    Math.ceil(4.4);     // returns 5
                

Math.floor()

Math.floor(x) returns the value of x rounded down to its nearest integer:


                      Math.floor(4.7);    // returns 4
                

Math.min() and Math.max()

Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:


                      Math.min(0, 150, 30, 20, -8, -200);  // returns -200
                

                    Math.max(0, 150, 30, 20, -8, -200);  // returns 150
                

Math.random()

Math.random() returns a random number between 0 (inclusive), and 1 (exclusive):


                      Math.random();     // returns a random number
                  

Exercises - test your knowledge

Exercise 1

Use the correct Math method to create a random number.


                      var r = 
                

                        var r = Math.random();
                    

Exercise 2

Use the correct Math method to return the largest number of 10 and 20.


                      var x =
                 

                        var x = Math.max(10, 20);
                    

Exercise 3

Use the correct Math method to round a 5.3 to the nearest integer.


                    var y = 
                

                      var y = Math.round(5.3);
                    

Exercise 4

Use the correct Math method to get the square root of 9.


                 var s =
                

                        var x = Math.sqrt(9);
                    

Rate this lesson

Previous lesson Next lesson

Spread the word:
Do you need help? Use our support forum

About the author

User avatar
Michal Szymanski
Co-Founder at MDBootstrap & BrandFlow. Entrepreneur, web developer, UI/UX designer, marketing analyst. Dancer and nerd in one.