Find second largest number in array JavaScript

In this program, you will learn to find the largest number in an array by using for loop.

Program for second largest number in array for loop

 <script>
  var array = [5 , 60, 1, 56, 24, 6, 9, 38];
  var largest=array[0];
  var Second_largest=array[0];
  var size=array.length;
  for(i=1;i<size;i++)
  {
     if(array[i]>largest){
        Second_largest=largest;
        largest=array[i];
      }
      else if(array[i]>Second_largest && array[i]!=largest){
	 Second_largest=array[i];
       }
  }
  document.write(Second_largest+" is second Largest number in an array");
</script> 
Run now

output

56 is second Largest number in an array

Logic to find second largest number in an array

  • Declares an array with 6 elements at the beginning.
  • Declare largest and Second_largest variable with an initial value of an array.
  • Find the size of the array and store it in variable size by using the length method i.e array.length.
  • Inside the loop compare one by one array elements with the largest value you have declared at the beginning.
  • If the array element is greater than the largest value then copy the largest value to Second_largest and the current array value to largest.