Here is your snippet which will log #
in incrementing value for each iteration in your outer loop:
for (index1 = 1; index1 < 8; index1++) {
var op = '#';
for (index2 = index1; index2 - 1; index2--) {
op = op + '#';
}
console.log(op);
}
To explain why is that so, first, let's dissect your loops:
for (index1 = 1; index1 < 8; index1++) {
var op = '#';
. . .
In this part, you created a variable op
with a value #
. For 7 iterations, it will be re-instantiated to the default value #
.
But why is that the variable increments for each iteration? Let's move on to the inner loop:
for (index2 = index1; index2 - 1; index2--) {
op = op + '#';
}
For each iteration inside this inner loop, you are appending an additional #
to the default value of op
.
Anyway, let's see how many iterations the inner loop is making for each iteration of the outer loop:
var x = 0;
for (index1 = 1; index1 < 8; index1++) {
//var op = '#';
for (index2 = index1; index2 - 1; index2--) {
//op = op + '#';
x++;
}
console.log(x);
x = 0;
//console.log(op);
}
As you can see, it's making 0, 1, 2, 3, 4, 5, 6
iterations for each outer loop iteration. Meaning, on the first iteration, it doesn't append a #
, adds 1 #
on the second, and so on and so forth. So it justifies the results on your code.
#
##
###
####
#####
######
#######
Side note: Noticed something weird? Honestly, I find this loop very weird. But if I'm correct, it is because 0 is falsy and thus it wont execute the iteration, which is the second parameter in the loop. Please add a comment if my guess is right.
Anyway, I guess I have to post that as a question. I'll update this answer once I get responses from my question.
EDIT: Sorry, there were only 7 iterations for the console.log(x)
. As for the weirdness of the loop condition, my guess is correct. index2 - 1
can also be written as index2 - 1 != 0
or more accurately !!(index2 - 1)
. !!
converts anything into Boolean. Any falsey value will become false: 0
, null
, ''
(empty string), undefined
, NaN
, and false
.
As for your question (darn, i almost forgot coz of the weird loop), lets go back to the code:
for (index1 = 1; index1 < 8; index1++) {
var op = '#';
for (index2 = index1; index2 - 1; index2--) {
op = op + '#';
}
//console.log(op);
}
//let's see if the variable resides outside the outer loop
console.log(op);
TADA! It still logs #######
. This is because of variable hoisting as what @Cristy said.