JavaSript: return greatest value in an array

The function only reurn the greatest number if it is at first, or last index of the array. How do I fix the logical error?

 function isGreater(arr) {

  let a = arr[0];
  for(let i =0; i< arr.length;i++){
   
       //console.log(arr[i]);
    var isGreat = (a<arr[i])?arr[i]:a;
       }
       return isGreat;
     }



       console.log(isGreater([7,9,10000, 
     11,25 ,20]));
       //=>20

You store the first item in the array in a. Then on every loop you create a variable isGreat and assign it either to a or to the current value. After looking at the last item, you return isGreat. isGreat is always going to be either the first or last element in the array.

1 Like