- Javascript Math Tutorial: How to do Math in Javascript
- Mathematical Operations
- Javascript Arithmetic Operators
- Math Constants
- Mathematical Notation in Javascript
- Rounding and Static Methods
- Abs
- Floor
- Ceil
- Round
- Max
- Min
- More Static Methods
- Pow
- Sign
- Trunc
- Sqrt
- Cbrt
- Random
- Logs
- Operations for Geometry
- ParseFloat and ParseInt
- Conclusion
- More Tips and Tricks for Javascript
- JavaScript Math Object
- Example
- The Math Object
- Math Properties (Constants)
- Example
- Math Methods
- Number to Integer
- Math.round()
- Examples
- Math.ceil()
- Example
- Math.floor()
- Example
- Math.trunc()
- Example
- Math.sign()
- Example
- Math.pow()
- Example
- Math.sqrt()
- Example
- Math.abs()
- Example
- Math.sin()
- Example
- Math.cos()
- Example
- Math.min() and Math.max()
- Example
- Example
- Math.random()
- Example
- The Math.log() Method
- Examples
- The Math.log2() Method
- The Math.log10() Method
- JavaScript Math Methods
- Complete Math Reference
Javascript Math Tutorial: How to do Math in Javascript
In all programming languages, performing mathematical operations is done routinely. Adding, subtracting, and many other operations are all required in any application. In Javascript, we can do this through simple operations, and by leveraging the Javascript Math object.
Note: to do mathematical operations, we need to be comparing numbers. A number that is in quotation marks will not work in mathematical operations.
Mathematical Operations
Let’s take a look at a simple mathematical operation how we can use maths in variables which we covered here. Basic maths operations work just the same as if we were to write them on paper:
Above, we have defined a variable i . We then define another variable, j , which is equal to i plus 10. Therefore, when we refer to j in our code, it will return 11.
There are a bunch of other mathematical operations we can do. Let’s take a look at them all.
Javascript Arithmetic Operators
Operator | What it does | Code example |
+ | Adds two numbers together | 10 + 5 returns 15 |
— | Subtract one number from another | 10 — 5 returns 5 |
+ | Divide one number by another | 10 / 5 returns 2 |
* | Multiply two numbers together | 10 * 5 returns 50 |
% | Get the remainder of a calculation | 12 % 5 returns 2 (12 divided by 5 leaves a remainder of 2) |
** | Raises one number to the power of another | 2 ** 3 returns 8 (2 to the power of 3 is 8) |
let x = 12; let y = 15; let add = x + y; let remainder = x % y; let raiseToPower = x ** y; let divide = x / y; console.log("Addition: " + add); console.log("Remainder: " + remainder); console.log("To the Power: " + raiseToPower); console.log("Divide: " + divide);
Math Constants
Apart from being able to do basic maths with operators in Javascript, we also have the Math object in Javascript. This object lets us access mathematical constants and do some more complicated maths.
Let’s start by looking at Mathematical constants Below is an example of how we can access PI.
let pi = Math.PI; // returns 3.141.
In Javascript, we use a dot to note the specific child of the Math object. These are all predefined, so they exist as part of basic Javascript. The above code will return the value PI — but most common mathematical constants are available in Javascript. These irrational numbers are all listed below, and can be used in the same way as a normal number:
Mathematical Constant | What it does | Value |
Math.PI | Returns PI | 3.141 . |
Math.E | Returns Euler’s number | 2.718 . |
Math.E | Returns Euler’s number | 2.718 . |
Math.LN2 | Returns ln(2) | 0.693 . |
Math.LOG10E | Returns log10(e) | 0.434 . |
Math.LOG2E | Returns log2(e) | 1.442 . |
Math.LN10 | Returns ln(10) | 2.302 . |
Math.SQRT2 | Returns the square root of 2 | 1.414 . |
Math.SQRT1_2 | Returns the square root of 1/2 | 0.707 . |
Mathematical Notation in Javascript
If you are used to working in a mathematics environment, you will be used to scientific or mathematic notation. We can use mathematical notation in Javascript. A mathematic notation for 3124 could be written as 3.124e3.
let myMathNotation = 3.124e3 console.log(myMathNotation);
We use e to refer to the exponent. The above is the same as writing 3.124 x 10 3 .
Rounding and Static Methods
We can use the Math object to do some more complicated mathematics, using functions that are built into it. These functions take a number as a value, and then adjust it accordingly. Let’s look at a few examples.
Abs
Math.abs takes a number and returns its absolute value. All that means, is it makes it positive if it was negative, and keeps it positive if it already was. It is the equivalent of the mathematic concept of magnitude.
let absoluteNumber = Math.abs(-2); // Returns 2.
Floor
Math.floor takes a number and rounds it down. This will only work with decimals.
let roundItDown = Math.floor(2.8371); // Returns 2.
Ceil
Math.ceil takes a number and rounds it up. This will only work with decimals.
let roundItDown = Math.ceil(2.8371); // Returns 3.
Round
Math.round takes a number and rounds it. This will only work with decimals.
let roundItDown = Math.ceil(1.453); // Returns 1.
Max
Math.max takes a set of numbers separated by commas, and picks the biggest one.
let biggestNumber = Math.max(2, 3, 6); // Returns 6.
Min
Math.min takes a set of numbers separated by commas, and picks the smallest one.
let smallestNumber = Math.min(2, 3, 6); // Returns 2.
More Static Methods
These useful operations let us manipulate or perform mathematical operations on numbers.
Pow
Math.pow takes a number, and raises it to a certain power. It is similar to the ** arithmetic operator we looked at earlier.
let toThePower = Math.pow(2, 3); // Returns 8, i.e. 2 to the power of 3.
Sign
Math.sign takes a number, and returns it sign. Not to be confused with sin
let getSign = Math.sign(-14); // Returns -1 let getAnotherSign = Math.sign(14); // Returns 0
Trunc
Math.trunc takes a number, and returns only the integer part of it.
let truncIt = Math.trunc(14.2431); // Returns 14
Sqrt
Math.sqrt takes a number, and returns its square root.
let sqrtIt = Math.sqrt(4); // Returns 2
Cbrt
Math.sqrt takes a number, and returns its cube root.
let cbrtIt = Math.sqrt(8); // Returns 2
Random
Math.random returns a random number between 0 and 1.
let randomNumber = Math.random(); // As an example, may return 0.4845737088624795
Logs
There are a number of ways to do logs in Javascript, all of which are shown below:
let naturalLog = Math.log(10); // The natural log of 10 let log10 = Math.log10(10); // The base 10 log of 10 let log2 = Math.log2(10); // The base 2 log of 10 let log2 = Math.log1p(10); // The natural log of 1 + 10
Operations for Geometry
There are a whole host of operations we can run to manipulate and calculate geometry. A list of these geometry functions are shown below. For all of these, it is assumed that the number is in radians.
As well as the basic sin, cos and tan operations, we also have functions for the arc versions of each (denoted with an a in front of the function), and the hyperbolic versions (denoted with an h at the end).
let x = 1.4; // Geometry mathematical functions Math.sin(x); Math.cos(x); Math.tan(x); Math.asin(x); Math.acos(x); Math.atan(x); Math.sinh(x); Math.cosh(x); Math.tanh(x); Math.asinh(x); Math.acosh(x); Math.atanh(x);
ParseFloat and ParseInt
Being able to do maths in Javascript is great, but if you remember from our article on types, a number written as a string will not be treated as a number in Javascript. To change a number which is a string, such as «5» to a real number, we can use the function parseFloat (which changes the number to a float), or parseInt , which changes the number to an integer — the difference of course being that an integer has no decimals, while a float does.
Both of these functions accept both numbers, and numbers in mathematical notation.
let myNumber = "12345" // type: String let myOtherNumber = "1.3453"; // type: String // Let's parse our numbers let parseNumber = parseFloat(myNumber); // Returns 12345 type: Number let parseNumber = parseFloat(myOtherNumber); // Returns 1.3453 type: Number let parseNumber = parseInt(myOtherNumber); // Returns 1 type: Number
These functions are very useful in vanilla Javascript, where types are not always consistent. Using these, we can take numbers stuck in strings and convert them to real numeric types which we can do calculations with.
Conclusion
Javascript has a lot of interesting ways to do mathematics, and provides many of the common mathematical constants through the Math object. As well as that, we have a number of static functions we can use to manipulate numbers through the same Math function. We’ve learned how to use all of these in this guide, as well as how to coerce a string of numbers into a number with parseInt / parseFloat . All of these techniques are important concepts in Javascript, and really useful when building applications.
More Tips and Tricks for Javascript
JavaScript Math Object
The JavaScript Math object allows you to perform mathematical tasks on numbers.
Example
The Math Object
Unlike other objects, the Math object has no constructor.
The Math object is static.
All methods and properties can be used without creating a Math object first.
Math Properties (Constants)
The syntax for any Math property is : Math.property .
JavaScript provides 8 mathematical constants that can be accessed as Math properties:
Example
Math.E // returns Euler’s number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
Math Methods
The syntax for Math any methods is : Math.method(number)
Number to Integer
There are 4 common methods to round a number to an integer:
Math.round(x) | Returns x rounded to its nearest integer |
Math.ceil(x) | Returns x rounded up to its nearest integer |
Math.floor(x) | Returns x rounded down to its nearest integer |
Math.trunc(x) | Returns the integer part of x (new in ES6) |
Math.round()
Math.round(x) returns the nearest integer:
Examples
Math.ceil()
Math.ceil(x) returns the value of x rounded up to its nearest integer:
Example
Math.floor()
Math.floor(x) returns the value of x rounded down to its nearest integer:
Example
Math.trunc()
Math.trunc(x) returns the integer part of x:
Example
Math.sign()
Math.sign(x) returns if x is negative, null or positive:
Example
Math.trunc() and Math.sign() were added to JavaScript 2015 — ES6.
Math.pow()
Math.pow(x, y) returns the value of x to the power of y:
Example
Math.sqrt()
Math.sqrt(x) returns the square root of x:
Example
Math.abs()
Math.abs(x) returns the absolute (positive) value of x:
Example
Math.sin()
Math.sin(x) returns the sine (a value between -1 and 1) of the angle x (given in radians).
If you want to use degrees instead of radians, you have to convert degrees to radians:
Angle in radians = Angle in degrees x PI / 180.
Example
Math.cos()
Math.cos(x) returns the cosine (a value between -1 and 1) of the angle x (given in radians).
If you want to use degrees instead of radians, you have to convert degrees to radians:
Angle in radians = Angle in degrees x PI / 180.
Example
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:
Example
Example
Math.random()
Math.random() returns a random number between 0 (inclusive), and 1 (exclusive):
Example
You will learn more about Math.random() in the next chapter of this tutorial.
The Math.log() Method
Math.log(x) returns the natural logarithm of x.
The natural logarithm returns the time needed to reach a certain level of growth:
Examples
Math.E and Math.log() are twins.
How many times must we multiply Math.E to get 10?
The Math.log2() Method
Math.log2(x) returns the base 2 logarithm of x.
How many times must we multiply 2 to get 8?
The Math.log10() Method
Math.log10(x) returns the base 10 logarithm of x.
How many times must we multiply 10 to get 1000?
JavaScript Math Methods
Method | Description |
---|---|
abs(x) | Returns the absolute value of x |
acos(x) | Returns the arccosine of x, in radians |
acosh(x) | Returns the hyperbolic arccosine of x |
asin(x) | Returns the arcsine of x, in radians |
asinh(x) | Returns the hyperbolic arcsine of x |
atan(x) | Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians |
atan2(y, x) | Returns the arctangent of the quotient of its arguments |
atanh(x) | Returns the hyperbolic arctangent of x |
cbrt(x) | Returns the cubic root of x |
ceil(x) | Returns x, rounded upwards to the nearest integer |
cos(x) | Returns the cosine of x (x is in radians) |
cosh(x) | Returns the hyperbolic cosine of x |
exp(x) | Returns the value of E x |
floor(x) | Returns x, rounded downwards to the nearest integer |
log(x) | Returns the natural logarithm (base E) of x |
max(x, y, z, . n) | Returns the number with the highest value |
min(x, y, z, . n) | Returns the number with the lowest value |
pow(x, y) | Returns the value of x to the power of y |
random() | Returns a random number between 0 and 1 |
round(x) | Rounds x to the nearest integer |
sign(x) | Returns if x is negative, null or positive (-1, 0, 1) |
sin(x) | Returns the sine of x (x is in radians) |
sinh(x) | Returns the hyperbolic sine of x |
sqrt(x) | Returns the square root of x |
tan(x) | Returns the tangent of an angle |
tanh(x) | Returns the hyperbolic tangent of a number |
trunc(x) | Returns the integer part of a number (x) |
Complete Math Reference
For a complete reference, go to our Complete Math Object Reference.
The reference contains descriptions and examples of all Math properties and methods.