Basic JavaScript - Nesting For Loops breakdown

Tell us what’s happening:

I am person who cannot move without getting to know what is happening, so I m stuck on outer loop. pls help me understand

  1. When I do for (let i = 0; i < arr[i].length; i++) it prints 2 list of array
  2. When I do for (let i = 0; i < arr.length; i++) it prints 3 list of array

Am i getting too much greedy? I m having hard time understanding this, the nest sub array is different animal for me.

Your code so far

const arr = [
  [1, 2], [3, 4], [5, 6]
];

for (let i = 0; i < arr[i].length; i++) {
  //for (let j = 0; j < arr[i].length; j++) {
    console.log(arr);
  //}
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36

Challenge Information:

Basic JavaScript - Nesting For Loops

1 Like

What did you expect to happen instead? What were you trying to achieve with changes made to the example?

I’m asking because otherwise it’s hard to say why it might be surprising. Code does what’s written in it. If change was made for a specific purpose and result is not as expected - that’s something that can be explained - either what’s wrong or why something else happens.

Strange thing, I ran the code which I explained above, both ran fine. I think now my confusion is around the nested loop

for (let i = 0; i < arr.length; i++) {
  for (let j = 0; j < arr[i].length; j++) {
    console.log(arr[i][j]);
  }
}

From my understanding is
when i = 0 which is item [1, 2] is array, it goes down to nested loop and j = 0; and j is less than length of [1, 2], it will console logging first item from arr and as j is asking what is first item of first item, it is printing that out?

Is that correct?

1 Like

Let’s add some printouts:

for (let i = 0; i < arr.length; i++) {
  console.log('i', i);
  console.log(`arr[${i}]`, arr[i]);
  for (let j = 0; j < arr[i].length; j++) {
    console.log('  j', j)
    console.log(`  arr[${i}][${j}]`, arr[i][j])
  }
}

Does this helps?

1 Like

yes thank you. As I wrote it down, it is pretty much same

1 Like