Finding largest integer in an array in JavaScript
var arr = [3, 6, 2, 56, 32, 5, 89, 32];
var largest = arr[0];
for (var i = 0; i < arr.length; i++) {
if (largest < arr[i] ) {
largest = arr[i];
}
}
console.log(largest);
- You need to define
i
or else it become a global variable. - Don't redefine largest in the loop.
- Since you're looping through the array, use
i < array.length
instead ofi <= largest
. - Since you're comparing each of the items in the array to
largest
, useif(largest < array[i])
instead ofif(array > largest)
- You should set largest equal to the first element in the array because what if all the numbers are negative?
array
is a bad variable name because it's too similar toArray
(the array constructor). Tryarr
instead.
One liner:
var largest = Math.max.apply(0, array);
More info here: Javascript max() function for 3 numbers
The code below is fixed and should work. The problem was that in this line if (array>largest) {
You were not providing the index of the array. By changing the code to this if (array[i]>largest) {
it works. Notice that I added the [i]
to the end of array
in the if statement.
var array = [3 , 6, 2, 56, 32, 5, 89, 32];
var largest= 0;
for (i=0; i<array.length; i++){
if (array[i]>largest) {
largest=array[i];
}
}
console.log(largest);