Javascript Data Structure Tutorial - Javascript Math








Arithmetic and Math Library Functions in JavaScript

JavaScript uses the standard arithmetic operators:

+ (addition) 
- (subtraction) 
* (multiplication) 
/ (division) 
% (modulo) 

JavaScript has buildin math library for advanced functions. For example to use square root, absolute value, and the trigonometric functions we can use them from the math library.

The arithmetic operators follow the standard order of operations.

We can use parentheses to modify that order.

Example

The following code shows some examples of performing arithmetic in JavaScript.


var x = 2; 
var y = 1.1; 
console.log(x + y); 
console.log(x * y); 
console.log((x+y)*(x-y)); 

var z = 9; 
console.log(Math.sqrt(z)); 
console.log(Math.abs(y/x)); 

To format a number to a fixed precision:

var x = 3; 
var y = 1.1; 
var z = x * y; 
console.log(z.toFixed(2)); // displays 3.30