0

I was trying to answer this question where I encountered a weird loop condition.

for (index1 = 1; index1 < 8; index1++) {
  var op = '#';
  for (index2 = index1; index2 - 1; index2--) { //this loop is weird to me
    op = op + '#';
  }
  console.log(op);
}

Upon checking how many iterations the inner loop is making for each outer loop iteration I get this:

var x = 0;

for (index1 = 1; index1 < 8; index1++) {
  //var op = '#';
  for (index2 = index1; index2 - 1; index2--) {
    var log = {};
    log.a = x; //check value before increment
    x++;
    log.b = x; //check value after increment
    console.log(`outer: ${index1}, inner: ${index2}`, log);
  }
  console.log(x);
  x = 0;
  //console.log(op);
}

As you can see, it logs 0, 1, 2, 3, 4, 5, 6.

My questions is:

Is the inner loop not iterating on the first outer loop iteration because index2 - 1 is equal to zero, which is falsy?

xGeo
  • 2,149
  • 2
  • 18
  • 39

1 Answers1

1

Is the inner loop not iterating on the first outer loop iteration because index2 - 1 is equal to zero, which is falsy?

That's correct. Any falsey value provided to the condition to the loop immediately halts the loop.

Falsey values are 0, NaN, null, undefined, "" and false.

llama
  • 2,535
  • 12
  • 11
  • There's your vote since you're the first to post an answer though @Someprogrammerdude should also be given the credit since he clarified my guess. As a comment though. – xGeo Oct 07 '17 at 16:05