I’m currently learning JavaScript on FreeCodeCamp, and I encountered an example involving nested for loops in JavaScript in one of their exercises:
var arr = [[1, 2], [3, 4], [5, 6]]; for (var i = 0; i < arr.length; i++) { for (var j = 0; j < arr[i].length; j++) { console.log(arr[i][j]); } }
When I run this code, the output is 1 2 3 4 5 6 undefined. I have a basic understanding of for loops and know that [i] and [j] are used to access elements in the array. However, I’m confused about why it only prints those numbers at the end. I found a question from a few years ago about writing for loops, but it didn’t explain how they work.
To better understand, I broke down the code into smaller parts: var arr = [[1, 2], [3, 4], [5, 6]]; for (var i = 0; i < arr.length; i++) { console.log(arr[i]); }
This prints: [1, 2] [3, 4] [5, 6] undefined var arr = [[1, 2], [3, 4], [5, 6]]; for (var i = 0; i < arr.length; i++) { for (var j = 0; j < arr[i].length; j++) { console.log(arr[i]); } } This prints:
[1, 2] [1, 2] [3, 4] [3, 4] [5, 6] [5, 6] undefined
var arr = [[1, 2], [3, 4], [5, 6]]; for (var i = 0; i < arr.length; i++) { for (var j = 0; j < arr[i].length; j++) { console.log(arr[j]); } }
[1, 2] [3, 4] [1, 2] [3, 4] [1, 2] [3, 4] undefined
I understand the first two instances with arr[i], where the loop iterates through the array and prints out each individual element (which in this case is an array). In the second instance, it prints them twice due to the two loops.
However, I have a few questions:
- Why is the last array in arr[j] not printed out (where did the [5, 6] go)?
- Why does arr[i][j] print only the numbers and eliminate the arrays?
- Where does the ‘undefined’ in the output come from?
Could someone help clarify these points and explain the steps the code takes before printing the output in the console? I want to fully understand the concept of nested for loops in JavaScript but am unsure how to search for the right information.