How to find the second largest element in a user-input JavaScript array?

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say following is our array −

var numbers=[10,50,80,60,89];

To find the second largest element, the code is as follows −


var numbers=[10,50,80,60,89];
var firstLargerNumber = Number.MIN_SAFE_INTEGER;
var secondlargerNumber = firstLargerNumber;
for(var tempNumber of numbers){
   if(tempNumber > firstLargerNumber){
      secondlargerNumber = firstLargerNumber;
      firstLargerNumber = tempNumber;
   else if(tempNumber > secondlargerNumber){
      secondlargerNumber = tempNumber;
console.log("The second largest number="+secondlargerNumber);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo138.js.


This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo138.js
The second largest number=80
Published on 11-Sep-2020 06:48:06