Help with returning largest numbers in arrays

Tell us what’s happening:
I am pretty sure I am misunderstanding the code. I tried various ways to solve the challenge and ended up peeking at a solution. :frowning: I was close but was missing the inner loop.

When I add the inner loop it says that s is not defined. I feel like I am missing something simple, but I could use some pointers. I tried to comment through the code to see if I could figure out what was missing, but I am at a loss.

Please help me understand if my thinking is off in my comments. Am I misunderstanding the code or am I missing something simple?

Your code so far


function largestOfFour(arr) {
// You can do this!
let newArr = []; // create an empty array for the new set of max values
for (let i = 0; i < arr.length; i++)  { //Use a for loop to iterate through the outer array
let largestNumber = arr[i][0]; // iterate through the first sub-array
for (let s = 1; s < arr[i].length; s++);  {
  if (arr[i][s] > largestNumber)  {
    largestNumber = arr[i][s]; // add the largest number to the new array
  }
}
newArr[i] = largestNumber;
}
return newArr;
}

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 6.3; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0.

Challenge: Return Largest Numbers in Arrays

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays

You have an extra character that does not belong and is causing unexpected results.

HINT: It is near the end of the line.

1 Like

Got it! Thank you. I kept looking and looking for something like that. Once I removed the semicolon, the code was good to go. I appreciate the help.

What is more important is to understand why the semi-colon caused the error to show.

The reason is because when JavaScript sees a semi-colon before a code block (the part that starts with {), It treats the code inside the block as being unrelated to the line before it. Even though you defined i as 1 in the for loop definition, that is only local to it and a valid code block after it. The semi-colon at right after the ) ends up being the same as not even having the line at all, so JavaScript sees the s variable and says "Hey, nothing has been defined for a variable named s.

1 Like

That makes sense. I have seen in several challenges that a semicolon (or missing semicolon) changes how the code is processed. Thank you for the explanation of why that is.