+ 2
Is this true?
I found this question in JS challenge mode : var x; for(i=0; i<10; i++){ for(j=0; j<=2; j++){ ++x; } } alert(x); //the right answer was 30 I'm wondering how it works, it hurts my mind (please stop this madness) could someone please help? thanks.
5 Respostas
+ 3
Ah, that would be since it's not initialized.
var x = 0;
Would fix it.
+ 11
i varies from 0 to 9 => 10 values
j varies from 0 to 2 => 3 values
There will be 30 iterations in total and x is increased by 1 in each iteration. So, output is 30.
+ 3
Inner loop runs 3 times.
Outer loop runs 10 times.
3 x 10 = 30. (itterations)
Essentially, the inner loop finishes before the outer loop continues.
So it will run like so:
i = 0, j = 0.
i = 0, j = 1
i = 0, j = 2
Then,
i = 1, j = 0
i = 1, j = 1
i = 1, j = 2
etc...
Until the outer loop is finished.
(When i < 10 is false)
+ 3
but alert(x) returns Not a Number, how is it?
+ 3
:D problem solved... thank you @Rrestoring faith
and of course you too Mr. Krishna. Thank you so much