Return Largest Numbers in Arrays - Loop question

Tell us what’s happening:

I don’t understand why var largestNumber = arr[n][0]; keeps the last value assigned to it and doesn’t get reassigned to the first element of [n]. For example, in [32, 35, 37, 39], largestNumber gets first reassigned to 35 which is [n][1], but since it’s inside a loop that reassigns it to [n][0] I expected to always have the value 32.

Your code so far

function largestOfFour(arr) {
  var results = [];

  for (var n = 0; n < arr.length; n++) {
    var largestNumber = arr[n][0];
    console.log(`LN[n][0]: ${largestNumber}`);
    for (var sb = 1; sb < arr[n].length; sb++) {
      if (arr[n][sb] > largestNumber) {
        largestNumber = arr[n][sb];
        console.log(`LN: ${largestNumber}`);

    results[n] = largestNumber;

  console.log(`results: ${results}`);

  return results;

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36.

Link to the challenge:

after this if statement is executed, the sb variable is increased by one and the body of the function is executed again, the body of this loop doesn’t include the initalization of the largestNumber variable. Once you get sb < arr[n].length evaluating as false, then the n variable is increased by one and the body of that loop is executed again, the body of this loop includes the initialization of largestNumber (note that the two loops are nested in each other),

@RenanMDP I have blurred out your solution as it is a fully-working solution to pass all of the tests. We don’t want to spoil it for anyone still working on this challenge.

1 Like