Basic js for loop question

I just cant wrap my brain around this. when I console.log J++ i get
0
0
0
2
why is that if j++ is j = j +1?

function multiplyAll(arr) {
  let product = 1;
  // Only change code below this line
    for (let i = 0; i < arr.length; i = i + 1) {
     
       for (let j = 0; j < arr[i].length; j++) {
        console.log(arr[i].length)
   
        console.log(j++, "J")

       }
    }
  // Only change code above this line
  return product;
}

multiplyAll([[1, 2], [3, 4], [5, 6, 7]]); or paste code here

Look this:
j++
means j = j +1
You are making a variable assignment here.

Online instruction, this returns the actual value of j not the assignment.

So try this:
console.log(j+1, "J")

But be careful, there’s also an increment for j every loop

If you want to see the value of j, simply call console.log(j, "J")

Take this examples to look what happens:

let test = 1;
console.log("variable assignment:",  test++); //Here returns 1, the actual value
//After that test value is equal to 2

//So
console.log("Simple sum NOT assignment:", test+1) //test +1 ==> 2 + 1 = 3

NOTE: You shouldn’t assign variables in a console.log or in a simple function call.

1 Like
function multiplyAll(arr) {
  let product = 1;
  // Only change code below this line
    for (let i = 0; i < arr.length; i = i + 1) {
      console.log('i:', i)
       for (let j = 0; j < arr[i].length; j++) {
        //console.log(arr[i].length)
        console.log('     j:', j)
       }
    }
  // Only change code above this line
  return product;
}

multiplyAll([[1, 2], [3, 4], [5, 6, 7]]);

This has helped me tremendously, I think I understand now. Thank you!

2 Likes

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