Mathematical operations are fundamental in JavaScript for performing calculations and manipulating numerical data. JavaScript provides a built-in Math object with various methods and properties for carrying out mathematical operations. In this chapter, we'll explore mathematical operations from basic arithmetic to advanced mathematical functions, covering everything you need to know to perform mathematical tasks effectively in JavaScript.
JavaScript supports basic arithmetic operations such as addition, subtraction, multiplication, and division.
Adds two numbers together.
const sum = 10 + 5;
console.log(sum); // Output: 15
Subtracts one number from another.
const difference = 10 - 5;
console.log(difference); // Output: 5
Multiplies two numbers.
const product = 10 * 5;
console.log(product); // Output: 50
Divides one number by another.
const quotient = 10 / 5;
console.log(quotient); // Output: 2
JavaScript’s Math
object provides various advanced mathematical functions for more complex calculations.
Returns the largest of zero or more numbers.
const largestNumber = Math.max(10, 20, 30);
console.log(largestNumber); // Output: 30
Returns the smallest of zero or more numbers.
const smallestNumber = Math.min(10, 20, 30);
console.log(smallestNumber); // Output: 10
Returns the square root of a number.
const squareRoot = Math.sqrt(25);
console.log(squareRoot); // Output: 5
Returns the base to the exponent power.
const power = Math.pow(2, 3);
console.log(power); // Output: 8 (2 raised to the power of 3)
JavaScript’s Math
object also provides various mathematical constants and properties.
Represents the mathematical constant π (pi).
console.log(Math.PI); // Output: 3.141592653589793
Represents the mathematical constant e, the base of natural logarithms.
console.log(Math.E); // Output: 2.718281828459045
Mathematical operations are essential in JavaScript for performing calculations and manipulating numerical data. By understanding the basic arithmetic operations, advanced mathematical functions, and constants provided by the Math object, you'll be equipped to handle a wide range of mathematical tasks in your JavaScript applications. Experiment with different mathematical operations and explore additional functionalities provided by the Math object to enhance your mathematical skills. With practice and experimentation, you'll become proficient in performing mathematical operations in JavaScript. Happy coding !❤️