Introduction
In this article, we will cover Math functions in JavaScript. Before we start, Let's understand the objective of this demonstration, which tells what exactly will be covered in this article.
- Math.round()
- Math.abs()
- Math.sqrt()
- Math.pow()
- Math.floor()
- Math.max()
- Math.min()
- Math.ceil()
- Math.random()
- Math.trunc()
- Math.cbrt()
So, Let's get started.
What is Math Function in JavaScript?
In computer programming, a math function refers to a built-in function that allows you to perform mathematical calculations on numerical data. These functions are part of the programming language's standard library and can be called in your code to perform various math operations.
Math.round() in JavaScript
This function rounds a number to the nearest integer.
let num1 = 4.4;
let num2 = 4.6;
console.log(Math.round(num1));
// Output: 4
console.log(Math.round(num2));
// Output: 5
Math.abs() in JavaScript
This function returns the absolute value of a number.
let num = -3;
console.log(Math.abs(num));
// Output: 3
Math.sqrt() in JavaScript
This function returns the square root of a number.
let num = 16;
console.log(Math.sqrt(num));
// Output: 4
Math.pow() in JavaScript
This function returns the result of a base raised to an exponent.
let base = 2;
let exponent = 3;
console.log(Math.pow(base, exponent));
// Output: 8
Math.floor() in JavaScript
This function rounds a number down to the nearest integer.
let num1 = 4.4;
let num2 = 4.6;
console.log(Math.floor(num1));
// Output: 4
console.log(Math.floor(num2));
// Output: 4
Math.max() in JavaScript
This function returns the largest of zero or more numbers.
let num1 = 5;
let num2 = 7;
let num3 = 3;
console.log(Math.max(num1, num2, num3));
// Output: 7
Math.min() in JavaScript
This function returns the smallest of zero or more numbers.
let num1 = 5;
let num2 = 7;
let num3 = 3;
console.log(Math.min(num1, num2, num3));
// Output: 3
Math.ceil() in JavaScript
This function returns a random number between 0 (inclusive) and 1 (exclusive).
let num1 = 4.4;
let num2 = 4.6;
console.log(Math.ceil(num1));
// Output: 5
console.log(Math.ceil(num2));
// Output: 5
Math.random() in JavaScript
This function returns the smallest of zero or more numbers.
console.log(Math.random());
// Output: a random number between 0 and 1
Math.trunc() in JavaScript
This function removes the decimal part of a number, returning only the integer part.
let num1 = 4.4;
let num2 = -4.6;
console.log(Math.trunc(num1));
// Output: 4
console.log(Math.trunc(num2));
// Output: -4
Math.cbrt() in JavaScript
This function returns the cube root of a number.
let num = 27;
console.log(Math.cbrt(num));
// Output: 3
Summary
In this article, I have tried to cover Math functions in Javascript.