-6

I was wondering if anyone can somebody please explain to me how this loop works?.

for (var x = 0; x < numbers.length; x++) {
  if (numbers[x] > largest)
    largest = numbers[x];
  }
}  
dippas
  • 58,591
  • 15
  • 114
  • 126
  • 4
    Any JavaScript tutorial or book should explain very early how loops work. What part exactly do you not understand in this particular loop? – JJJ Jun 10 '17 at 08:28
  • loop work fine? what are you looking for exactly? – Ali Jun 10 '17 at 08:29
  • 2
    this is a good start https://www.w3schools.com/js/js_loop_for.asp – Tik Jun 10 '17 at 08:29

2 Answers2

0

Here is an explanation of everything happening in the for loop

//                  keeps the for loop going while x is less than numbers.length which is the length of nmbers
// sets x to 0 initialy |          increases x by +1 each time it restarts to begin the loop
//       V              V            V
for (var x = 0; x < numbers.length; x++) {
    //   Executes code if numbers[x] is greater than largest
    //            V
    if (numbers[x] > largest){
        //   sets largest to numbers[x] if numbers[x] is greater than largest
        //      V
        largest = numbers[x];
    }
}
dippas
  • 58,591
  • 15
  • 114
  • 126
0

I think you are trying to get the largest number from the array, so here is how I would do it:

// https://stackoverflow.com/questions/1669190/javascript-min-max-array-values

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

Array.prototype.max = function() {
  return Math.max.apply(null, this);
};

Array.prototype.min = function() {
  return Math.min.apply(null, this);
};

document.write(array.max());
KingCoder11
  • 415
  • 4
  • 19