Hesham Abdalla
Hesham Abdalla

Reputation: 15

Nested for loops with if/else in Javascript

I just don't get it why when I use this,

for(in=1; in<=3;in++) {
    for(out=1; out<=2; out++) {
        console.log('*')
    }
}

it prints 6 stars which seems right to me, And when i use it with if/else like this,

for(in=0; in<=3; in++) {
    for(out=0; out<=2; out++) {
        if(in == 9) {
            console.log('inside');
        }
    }
    console.log('outside');
}

(outside) will be printed 4 times I really don't get it why is it like this ?

Upvotes: 0

Views: 4152

Answers (1)

Paulo Mendes
Paulo Mendes

Reputation: 728

console.log('outside') is inside the first loop which goes from 0 to 3, so it's printed four times. 'inside' is never printed because in never reaches 9

Upvotes: 5

Related Questions