Open In App

Maximum of Two Numbers in JavaScript

Finding the maximum of two numbers is a popular JavaScript operation used in many different programming tasks. This can be accomplished in a variety of ways, each having unique benefits and applications.

There are several approaches for determining the maximum of two numbers in JavaScript which are as follows:



Using Math.max()

In JavaScript, you can find the maximum of two numbers using the Math.max() method. This method takes multiple arguments and returns the largest of them. Here’s how you can use it to find the maximum of two numbers:



Syntax:

Math.max(num1, num2);

Example: Finding the maximum of two numbers using Math.max() method.




let max = Math.max(100, 10);
console.log("The Maximum Value is ", max);

Output
The Maximum Value is  100

Using Conditional Operator (Ternary Operator)

The conditional operator, also known as the ternary operator, is a concise way to write conditional statements in many programming languages, including JavaScript. It takes three operands: a condition followed by a question mark (?), an expression to evaluate if the condition is true, and a colon (:) followed by an expression to evaluate if the condition is false.

Syntax:

let max = num1 > num2 ? num1 : num2;

Example: Finding maximum of two numbers using the conditional operator.




let num1 = 80;
let num2 = 30;
let max = num1 > num2 ? num1 : num2;
console.log("The Maximum Value is ", max);

Output
The Maximum Value is  80

Using Math.max() with Spread Syntax

This approach utilizes the Math.max() method along with the spread syntax (…) to find the maximum of two numbers. The spread syntax allows us to pass an array of numbers as arguments to Math.max(), effectively comparing all the numbers in the array and returning the maximum value.

Syntax:

Math.max(...[num1, num2]);

Example: Demonstration to find maximum of two numbers using spread syntax with Math.max() method.




let num1 = 150;
let num2 = 20;
let max = Math.max(...[num1, num2]);
console.log("The Maximum Value is ", max);

Output
The Maximum Value is  150

Article Tags :