Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to find largest of three numbers - JavaScript
We are required to write a JavaScript function that takes in three or more numbers and returns the largest of those numbers.
For example: If the input numbers are ?
4, 6, 7, 2, 3
Then the output should be ?
7
Method 1: Using Math.max() with Spread Operator
The simplest approach is using the built-in Math.max() function with the spread operator:
const findLargest = (...nums) => {
return Math.max(...nums);
};
console.log(findLargest(4, 6, 7, 2, 3));
console.log(findLargest(15, 8, 23, 1));
7 23
Method 2: Using Loop Iteration
For manual comparison, we can iterate through the numbers and track the maximum:
const findGreatest = (...nums) => {
let max = -Infinity;
for(let i = 0; i < nums.length; i++){
if(nums[i] > max){
max = nums[i];
}
}
return max;
};
console.log(findGreatest(5, 6, 3, 5, 7, 5));
console.log(findGreatest(-10, -5, -20));
7 -5
Method 3: Using reduce() Method
We can also use the reduce() method for a functional programming approach:
const findLargestReduce = (...nums) => {
return nums.reduce((max, current) => current > max ? current : max, -Infinity);
};
console.log(findLargestReduce(12, 45, 23, 67, 1));
console.log(findLargestReduce(3.5, 2.1, 9.8));
67 9.8
Handling Edge Cases
Here's how these methods handle special cases:
// Empty array console.log(Math.max()); // -Infinity // Single number console.log(findLargest(42)); // Negative numbers console.log(findLargest(-1, -5, -3));
-Infinity 42 -1
Comparison
| Method | Performance | Readability | Best For |
|---|---|---|---|
Math.max() |
Fastest | Highest | General use |
| Loop iteration | Good | Medium | Learning/custom logic |
reduce() |
Slower | High | Functional programming |
Conclusion
Use Math.max() with spread operator for the most efficient and readable solution. The loop method provides better understanding of the underlying logic for learning purposes.
Advertisements
