Math Functions in JavaScript with Examples

math functions in javascript

The Math object gives you a set of built-in functions and constants for working with numbers in JavaScript. You do not need to create it before use because it works directly.

It helps you do tasks like:

  • Rounding
  • Finding maximum
  • Minimum values
  • Generating random numbers.

You can also use it for advanced work like trigonometry and logarithms.

What are JavaScript Math Functions?

Math functions are built-in functions and tools inside the Math object that solve common number tasks. They save time and reduce errors because you do not need to write your own code for the same job.

Here are some of them:

  • Math.round()
  • Math.floor()
  • Math.ceil()
  • Math.max() and Math.min()
  • Math.random()
  • Math.sqrt()
  • Math.pow()
  • Math.abs()
  • Math.trunc()
  • Math.sign()
  • Math.log() and related methods
  • Trigonometric methods like Math.sin()

Here is a quick example:

let num = 5.7;
let rounded = Math.round(num);
console.log(rounded); // Output: 6

In this example, the Math.round() method changes 5.7 to the nearest integer, which is 6.

List of Math Functions in JavaScript

There are many types of built-in functions in the Math object. Let’s take each one in-depth.

Math.round()

Math.round(x) returns the integer closest to the given number. Values at .5 or higher round up.

console.log(Math.round(2.6)); // 3

Math.floor()

Math.floor(x) returns the largest integer less than or equal to the number.

console.log(Math.floor(2.6)); // 2

Math.ceil()

Math.ceil(x) returns the smallest integer greater than or equal to the number.

console.log(Math.ceil(2.1)); // 3

Math.max()

Math.max() returns the largest number from a set of values.

console.log(Math.max(3, 7, 2)); // 7

Math.min()
Math.min() returns the smallest number from a set of values.

console.log(Math.min(3, 7, 2)); // 2

Math.random()

Math.random() returns a random number between 0 (inclusive) and 1 (exclusive).

console.log(Math.random()); // 0.482... (varies)

Math.sqrt()

Math.sqrt(x) returns the square root of a number.

console.log(Math.sqrt(16)); // 4

Math.pow()

Math.pow(base, exponent) returns the base raised to the given power.

console.log(Math.pow(2, 3)); // 8

Math.abs()

Math.abs(x) returns the absolute (non-negative) value of a number.

console.log(Math.abs(-5)); // 5

Math.trunc()

Math.trunc(x) removes the fractional part, keeping only the integer.

console.log(Math.trunc(7.89)); // 7

Math.sign()

Math.sign(x) returns 1 if positive, -1 if negative, or 0 if zero.

console.log(Math.sign(-42)); // -1

Math.log()

Math.log(x) returns the natural logarithm (base e) of a number.

console.log(Math.log(10)); // 2.302...

Math.log2()

Math.log2(x) returns the base-2 logarithm of a number.

console.log(Math.log2(8)); // 3

Math.log10()

Math.log10(x) returns the base-10 logarithm of a number.

console.log(Math.log10(100)); // 2

Math.sin()

Math.sin(radians) returns the sine of an angle given in radians.

console.log(Math.sin(Math.PI / 2)); // 1

Math.cos()

Math.cos(radians) returns the cosine of an angle given in radians.

console.log(Math.cos(0)); // 1

Math.tan()

Math.tan(radians) returns the tangent of an angle in radians.

console.log(Math.tan(Math.PI / 4)); // 0.9999999999999999

Math.asin()

Math.asin(x) returns the arcsine (in radians) for a given ratio.

console.log(Math.asin(1)); // 1.5707...

Math.acos()

Math.acos(x) returns the arccosine (in radians) for a given ratio.

console.log(Math.acos(1)); // 0

Math.atan()

Math.atan(x) returns the arctangent (in radians) for a given number.

console.log(Math.atan(1)); // 0.7853...

Math.PI

Math.PI holds the value of π (approximately 3.14159).

console.log(Math.PI); // 3.14159...

How Math Functions Handle NaN and Infinity

When a Math function gets NaN (Not-a-Number) as input, the result is always NaN. This is because any calculation with NaN cannot give a valid number.

For example:

console.log(Math.sqrt(NaN)); // NaN
console.log(Math.max(10, NaN)); // NaN
console.log(Math.min(NaN, 3)); // NaN

Some methods, like Math.max() and Math.min(), will return NaN if any of their inputs is NaN, even if the other values are fine.

Infinity values behave differently:

  • Infinity is treated as the largest possible number.
  • -Infinity is treated as the smallest possible number.

Here are examples:

console.log(Math.max(5, Infinity)); // Infinity
console.log(Math.min(5, -Infinity)); // -Infinity
console.log(Math.max(-Infinity, -5)); // -5
console.log(Math.min(Infinity, 5)); // 5

Use Math with Loops and Arrays

Math functions are often used inside loops to process lists of numbers. For example, you can find the highest or lowest value in an array by checking each number one by one:

let numbers = [5, 8, 2, 9, 3];
let highest = -Infinity;

for (let num of numbers) {
  highest = Math.max(highest, num);
}

console.log(highest); // 9

You can also use loops to make random numbers for games, tests, or sample data:

for (let i = 0; i < 5; i++) {
  let randomNum = Math.floor(Math.random() * 10); // 0 to 9
  console.log(randomNum);
}

Examples

Find the highest score in a game:

let scores = [85, 92, 78, 99, 88];
let highest = Math.max(...scores);
console.log(highest); // 99

This code spreads the scores array into Math.max() to find the top score without writing a loop.

Create a random integer between two values:

let min = 10;
let max = 20;
let randomInt = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(randomInt); // Between 10 and 20

The code uses Math.random() and Math.floor() together to make a random integer in a given range.

Calculate the hypotenuse with Pythagoras:

let a = 3;
let b = 4;
let hypotenuse = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
console.log(hypotenuse); // 5

This uses Math.pow() and Math.sqrt() to find the length of the hypotenuse in a right triangle.

Normalize an array of numbers:

let numbers = [2, 4, 6, 8];
let maxNum = Math.max(...numbers);
let normalized = numbers.map(num => num / maxNum);
console.log(normalized); // [0.25, 0.5, 0.75, 1]

The code divides each number by the largest value to create numbers between 0 and 1.

Wrapping Up

In this article, you learned what the JavaScript Math object is and how to use its functions in simple and advanced ways. Here is a quick recap:

  • The Math object has many built-in methods for number tasks.
  • You can round, find max or min, and work with powers or roots.
  • Trigonometric and logarithmic methods are also available.
  • You can use Math with arrays and loops for many practical tasks.

FAQs

How to use Math.random() in JavaScript?

To use Math.random(), call it without parameters. It returns a number between 0 (inclusive) and 1 (exclusive).
let num = Math.random(); console.log(num); // Example: 0.567834 

How to round numbers with Math.round() in JavaScript?

Math.round() rounds a number to the nearest integer. It rounds up for decimals 0.5 or higher.
console.log(Math.round(4.5)); // 5 console.log(Math.round(4.4)); // 4 

What is the difference between Math.floor() and Math.ceil()?

Math.floor() rounds down to the nearest integer. Math.ceil() rounds up to the nearest integer.
console.log(Math.floor(4.9)); // 4 console.log(Math.ceil(4.1)); // 5 

How to get the largest value using Math.max() in JavaScript?

Math.max() returns the largest number among given arguments.
console.log(Math.max(3, 7, 2, 9)); // 9 

Similar Reads

JavaScript Nullish Coalescing Operator Guide with Examples

The JavaScript nullish coalescing operator (??) gives a default value when a variable is null or undefined. Understand the Nullish…

JavaScript math.exp: How to Calculate e^x

Math.exp is a built-in JavaScript function that returns the value of e raised to a given number. Here, e is…

JavaScript Hoisting: How It Works with Examples

You will face hoisting early when you write JavaScript. It affects how your code runs, and it may confuse you…

JavaScript Object Methods with Examples

JavaScript object methods are simple ways to handle data inside objects. An object can hold many values, and methods give…

JavaScript Math asin: How it Works with Examples

Math.asin() finds the arc sine of a number in JavaScript. It helps you work with angles from values. You get…

JavaScript this Keyword: How It Works in Depth with Examples

The this keyword links code, context, and object reference in JavaScript. You can use it to refer to the owner…

Understanding Data Types and Conversion in JavaScript

JavaScript works with different kinds of values. Each value has a type, known as a data type. These types help…

JavaScript Math atan: Arc Tangent of a Number in Radians

Math.atan() function in JavaScript helps you to solve math problems in your code. It turns a number into an angle.…

How Does JavaScript Work to Run Code in the Web Browser

Click a button on a website. Something changes. A menu opens or a message pops up. That’s how JavaScript works.…

JavaScript with Function Guide: Syntax with Examples

JavaScript has a statement called "with" that changes how code accesses object properties. The"with" Function makes a temporary scope, so…

Previous Article

HTML Elements and Tags: Elements vs Tags Explained

Next Article

PHP array_column: How to Extract Values from Arrays

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.