Question about the procedural approach to solving Largest Numbers in Arrays challenge

Hello. I wondered how JavaScript knows to append results to the variable results with the statement results[n] = largestNumber; in the basic code solution provided on freeCodeCamp Algorithm Challenge Guide: Return largest Numbers in Arrays

I would think we would need to use results.push(largestNumber) instead.

function largestOfFour(arr) {
  var results = [];
  for (var n = 0; n < arr.length; n++) {
    var largestNumber = arr[n][0];
    for (var sb = 1; sb < arr[n].length; sb++) {
      if (arr[n][sb] > largestNumber) {
        largestNumber = arr[n][sb];
      }
    }

    results[n] = largestNumber;
  }

  return results;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
2 Likes

You can always slap a value into a JS array using bracket notation. Heck, you can even skip indexes. It just happens in the code example the you first put a value at index 0, then at 1, then 2, and so on.

IMO, using .push() is better because the intention is clearer.

3 Likes

This is such an amazing explanation. Thank you so much. I just have one issue, when you called
results[n]= largestNumber;

why didn’t you call [sb] as well, so we’d have:

results[n][sb]= largestNumber;

Please advice.

Looking more closely it seems because it was applied inside the outer array [n].

i think using .push() is better, imagine the lenght of the array is not known … then we would value the .push() method