-1

I try to understand nested for loops in javascript but it's very confusing.

I have this code and I can't understand how it works:

let n = 5;
for (let i = 0; i < n; i++) {
    for (let j = 0; j < i; j++) {
    console.log(j);
}}

In console I have : 0 1 0 1 2 0 1 2 3

And I'm trying to figure out which loop represent each number.

  • 2
    Tip: Run the program yourself using only a pen and paper. – Dai Dec 04 '21 at 20:00
  • 1
    [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173) – VLAZ Dec 04 '21 at 20:04
  • A loop doesn’t “represent” a number. Do you know how a simple loop works, exactly? Read the [documentation](//developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for). A loop executes statements as long as a condition holds. A loop is itself a statement. – Sebastian Simon Dec 04 '21 at 20:08
  • Include `i` in the log also and it will probably help you visualize better – charlietfl Dec 04 '21 at 20:09
  • Tip: `console.log({ i, j });`. – Sebastian Simon Dec 04 '21 at 20:10
  • 1
    BTW: The output is NOT "0 1 0 1 2 0 1 2 3", take a look at your console output, there should be a small number (2) left beside your first 0. It tells you that you have the first 0 two times. The output is "0 0 1 0 1 2 0 1 2 3" – Christoph Lütjen Dec 04 '21 at 20:11

1 Answers1

1

Run this code:

let n = 5;
let str = '';
for (let i = 0; i < n; i++) {
    for (let j = 0; j < i; j++)
        str += j;
   
   console.log("Outer: "+i+" Inner: "+str);
   str = '';
}

Output is:

Outer: 0 Inner: 
Outer: 1 Inner: 0
Outer: 2 Inner: 01
Outer: 3 Inner: 012
Outer: 4 Inner: 0123

As you can see, in the output above, inner loop (the one with variable j) doesn't run, because if you replace the variables with numbers it would be 0 < 0 (i < 0), which isn't true.

The best way for you to understand how nested loops work is to write each step and variable values on the paper, like so:

n = 5

STEP 1:

  • i = 0
  • i < n (0 < 5) TRUE
    • j = 0
    • j < i (0 < 0) FALSE inner loop doesn't execute
  • OUTPUT: "Outer: 0 Inner:"
  • str = ''

STEP 2:

  • i = 1
  • i < n (1 < 5) TRUE
    • j = 0
    • j < i (0 < 1) TRUE
    • str = 0
    • j = 1 (j++)
    • j < i (1 < 1) FALSE
  • OUTPUT: "Outer: 1 Inner: 0"
  • str = ''

And so on... Keep repeating this until the argument in the outer loop is false (i < n).

You must remember, in for loop the sequence of orders executed:

for(let i = 0; i < 5; i++) {
  console.log('It works');
}
  1. let i = 0; (this executes only once)

  2. i < 5 (if true run 3 and 4)

  3. run the code in loop

  4. i ++

  5. i < 5 (if true run 6 and 7)

  6. run the code in loop

  7. i++

etc.

Nixt
  • 75
  • 5