+ 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.

2nd Aug 2017, 3:17 AM
Oeoes Roy
Oeoes Roy - avatar
5 Antworten
+ 3
Ah, that would be since it's not initialized. var x = 0; Would fix it.
2nd Aug 2017, 5:34 AM
Rrestoring faith
Rrestoring faith - avatar
+ 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.
2nd Aug 2017, 3:41 AM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 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)
2nd Aug 2017, 3:45 AM
Rrestoring faith
Rrestoring faith - avatar
+ 3
but alert(x) returns Not a Number, how is it?
2nd Aug 2017, 4:04 AM
Oeoes Roy
Oeoes Roy - avatar
+ 3
:D problem solved... thank you @Rrestoring faith and of course you too Mr. Krishna. Thank you so much
2nd Aug 2017, 5:49 AM
Oeoes Roy
Oeoes Roy - avatar