+ 5

Trouble with JS challenge question (function calc())

Why is the output 9? function calc(i) { return i*i; } for(var i =1; i<3; i++) {} document.write(calc(i)); There's something really basic I'm missing here and I don't know what it is. Thank you in advance!

6th Aug 2017, 2:21 PM
alessandra
alessandra - avatar
5 odpowiedzi
+ 12
for ( var i = 1; i < 3; i++ ) {} iterates until i = 3. Then you call calc with 3 -> it returns 9 and that gets printed...
6th Aug 2017, 2:32 PM
Nikolay Nachev
Nikolay Nachev - avatar
+ 10
it goes a bit different: 1.take the initial value, 2. do the loop body, 3. do the increment, 4. check the condition, if true go to 2...
6th Aug 2017, 4:14 PM
Nikolay Nachev
Nikolay Nachev - avatar
+ 4
Now I see, it was definitely a silly question. Thanks for the answers!
6th Aug 2017, 5:40 PM
alessandra
alessandra - avatar
+ 3
i < 3 means "iterate while i is minor than 3". When the i in your code is not anymore minor than 3? When it become equals to 3 after the last i++ (i=2+1).
6th Aug 2017, 4:14 PM
Marco Minervino
Marco Minervino - avatar
+ 1
for(var i=1 ;i<3 ;i++) {} first i =1 iterated once making i = 2 iterated again making i = 3 so the idea is...loop stops iterating when i = 3 becoz meaning of the condition is(if i<3 , then do i++) but by then" i "have the value of 3.. now calc(3) = 3*3 = 9
7th Aug 2017, 1:46 AM
sayan chandra
sayan chandra - avatar