Which lesson to refer to?

Hello, I was able to pass the previous challenge but this one was more difficult but I realized I don’t fully understand the storing of data. I understand the for loop and nested for loop but I don’t quite understand why the the following code

let largestNumber = arr[i][0];

Is after the first for loop. Can someone tell me which lesson I could go back to to master this basic information?

  **Your code so far**

function largestOfFour(arr) {
let results = [];
for (let i = 0; i < arr.length; i++) {
  let largestNumber = arr[i][0];
  for (let j = 1; j < arr[i].length; j++) {
    if (arr[i][j] > largestNumber) {
      largestNumber = arr[i][j];
    }
  }
  results[i] = largestNumber;
}

return results;
}
  **Your browser information:**

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

Challenge: Return Largest Numbers in Arrays

Link to the challenge:

What do you not understand?
The point of the line is, to make sure whatever value the “largestNumber” has, is a number that’s actually present within the array. It has nothing to do with storing data, but with the logic to find the largest number - an obviously the first number in the sub-array is part of the sub array and as such a valid candidate for the largest number.

Not sure how to phrase the question but I dont understand why set the largest number after the first for loop when in the previous challenge it was before the for loop. What would that be? I dont quite get it

So why does this work

function largestOfFour(arr) {

  let results = [];

  

  for (let i = 0; i < arr.length; i++) {

    let highest = -Infinity;

But not when its before the first for loop like this

function largestOfFour(arr) {

  let results = [];

  let highest = -Infinity;

  for (let i = 0; i < arr.length; i++)

Ignore the inifity

Because the highest number is calculated in the inner loop.

Just look at the example and write down what the code does on a piece of paper.
If the array would be [[1,2,3,40], [1,2,3,4]] what would be the final output?
With the declaration within the loop: [40, 4]
With the declaration before: [40, 40]

Ahh I see, that makes sense but I think I need more practice with this. What topic would this be? I want to not have to think about it too hard. Is there a challenge where this is focused on in more detail? Thanks!

Well in programming, thinking hard about things inbetween googling solution or consoulting forums/others is kind of a big part of the process :wink:
Unfortunatly I cannot point you to any resource because… well I wouldn’t even know where to look. It’s just how this specific algorithm works and it’s the general issue of thinking about how to set the innitial value of variables, or where and how to declare them and whatnot…

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.