Math is a built-in object in Javascript, used to support complex operations during runtime.
The Math object in Javascript provides methods to perform basic operations such as addition, subtraction, multiplication, division, and modulo. Here are some examples:
Addition:
var sum = Math.add(2, 3);
console.log(sum); // 5
Subtraction:
var difference = Math.subtract(5, 3);
console.log(difference); // 2
Multiplication:
var product = Math.multiply(4, 5);
console.log(product); // 20
Division:
var quotient = Math.divide(10, 2);
console.log(quotient); // 5
Modulus:
var remainder = Math.modulo(10, 3);
console.log(remainder); // 1
The Math object provides methods to perform mathematical operations such as square root, exponentiation, and rounding numbers. Here are some examples:
Square root:
var squareRoot = Math.sqrt(25);
console.log(squareRoot); // 5
Exponentiation:
var power = Math.pow(2, 3);
console.log(power); // 8
Rounding numbers:
var roundedNumber = Math.round(3.7);
console.log(roundedNumber); // 4
The Math object provides mathematical constants such as pi (Ï€), e, and constants related to logarithms.
Pi constant:
var pi = Math.PI;
console.log(pi); // 3.141592653589793
Constant e:
var e = Math.E;
console.log(e); // 2.718281828459045
Natural logarithm constant:
var naturalLogarithm = Math.LN10;
console.log(naturalLogarithm); // 2.302585092994046
In addition to the mentioned operations and constants, the Math object also provides many other useful methods such as:
Find absolute value:
var absoluteValue = Math.abs(-5);
console.log(absoluteValue); // 5
Find the maximum or minimum value in a list of numbers:
var maxNumber = Math.max(1, 2, 3, 4, 5);
console.log(maxNumber); // 5
var minNumber = Math.min(1, 2, 3, 4, 5);
console.log(minNumber); // 1
Sin, cos and tan:
var sineValue = Math.sin(0);
console.log(sineValue); // 0
var cosineValue = Math.cos(Math.PI);
console.log(cosineValue); // -1
var tangentValue = Math.tan(Math.PI / 4);
console.log(tangentValue); // 1