+ 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!
5 Answers
+ 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...
+ 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...
+ 4
Now I see, it was definitely a silly question. Thanks for the answers!
+ 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).
+ 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