Largest Number in JavaScript
In this article, we will see how to find the largest number in javascript with example codes. If you have two are more numbers in the array, you can use Math.max.apply() method.
Mehtod 1
let arr = [44, 28, 18, 55, 68, 11, 70];
let largest = Math.max.apply(null, arr);
document.write(largest);
- See the above code, we have created an array and inside it, we gave some random numbers.
- To find the largest number, we need to use Math.max.apply() method and pass the value “null” and your array name as in the above code.
- See the output the largest number is displayed successfully.
Method 2
let arr = [3, 45,89,99, 98, 95];
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max)
max = arr[i];
}
document.write(max);
- In this above code, we have created and assigned the first value of an array to the “max” variable.
- Then we create a loop and it runs until the array length, so we set the condition arr.length.
- Inside the loop, we check the condition “arr[i] > max”, if the condition is true max value is changed to the largest number.
- Finally print the max value and it returns the largest value of an array.