Math

Contact Us or call 1-877-932-8228
Math

Math

The Math object is a built-in static object. The Math object's properties and methods can be accessed directly (e.g, Math.PI) and are used for performing complex math operations. Here are two commonly used properties of the Math object.

Common Math Properties
Property Description
Math.PI Pi (Π)
Math.PI;
//3.141592653589793
Math.SQRT2 Square root of 2.
Math.SQRT2;
//1.4142135623730951

Below are some of the common Math methods that you can use to perform mathematical operations:

Common Math Methods
Method Description
Math.abs(number) Absolute value of number.
Math.abs(-12);
//Returns 12
Math.ceil(number) number rounded up.
Math.ceil(5.4);
//Returns 6
Math.floor(number) number rounded down.
Math.floor(5.6);
//Returns 5
Math.max(numbers) Highest Number in numbers.
Math.max(2, 5, 9, 3);
//Returns 9
Math.min(numbers) Lowest Number in numbers.
Math.min(2, 5, 9, 3);
//Returns 2
Math.pow(number, power) number to the power of power.
Math.pow(2, 5);
//Returns 32
Math.round(number) Rounded number.
Math.round(2.5);
//Returns 3
Math.random() Random number between 0 and 1.
Math.random();
//Returns random
//number from 0 to 1

You can see these examples in a browser by opening BuiltInObjects/Demos/MathPropertiesAndMethods.html. In the next activity, we'll use the Math.round() and Math.random() methods in a simple example.

Method for Generating Random Integers

You can easily generate random numbers in JavaScript using the Math.random() method.

var low = 1;
var high = 10;
var rndDec = Math.random();

var rndInt = Math.floor(rndDec * (high - low + 1) + low);
Next