How to Get the Maximum of Two Numbers in JavaScript


When working with numbers in JavaScript, determining the larger of two values is a common operation. Whether you’re building a simple calculator or implementing complex algorithms, knowing how to find the maximum is useful. Let’s dive into various techniques to achieve this.


Using the Math.max() Function

You can directly access the parent element’s classList property and use the add method to add a class.

JavaScript
const num1 = 8;
const num2 = 12;

const maximum = Math.max(num1, num2);

// Output: 12
console.log(maximum);

Here, Math.max() is invoked with two numeric arguments, num1 and num2. The function returns the greater of the two, which is then logged to the console.

Using Conditional (Ternary) Operator

A concise way to find the maximum of two numbers is by using the conditional (ternary) operator.

JavaScript
const num1 = 8;
const num2 = 12;

const maximum = num1 > num2 ? num1 : num2;

// Output: 12
console.log(maximum);

In this example, the condition num1 > num2 is evaluated. If true, num1 is assigned to maximum; otherwise, num2 is assigned.

Using Math.max() with Spread Syntax

ES6 introduced the spread syntax (…), allowing us to pass an array of values to Math.max() using the spread operator.

JavaScript
const num1 = 8;
const num2 = 12;

const maximum = Math.max(...[num1, num2]);

// Output: 12
console.log(maximum);

By spreading the array [num1, num2], we can find the maximum of the two numbers directly.


🧪Practice Coding Problem: Find Maximum number

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

Write a function findMaximum that takes two parameters, a and b, and returns the maximum of the two numbers.

Implement the findMaximum function and test it with different sets of numbers.

JavaScript
function findMaximum(a, b) {
// > > > 👉 Write code here 👈 < < <
}

// Testing the function
console.log(findMaximum(5, 10)); // Output: 10
console.log(findMaximum(-3, 0)); // Output: 0
console.log(findMaximum(8, 8)); // Output: 8
Please attempt before seeing the Answer:
JavaScript
function findMaximum(a, b) {
  return a > b ? a : b;
}

Hopefully, understanding these techniques will help in your Javascript journey. Keep Max(coding) 🚀 ! 😄

Scroll to Top