+ 1
Can anyone explain why it gives output 5.
function test(Number) { while(Number<5){ Number++; } return Number; } alert (test (2))
4 Answers
+ 4
You have written number < 5 after then you still increases number by 1. so at last it returned 5.
in loop number started at 2 and increased till 4.
in last loop the number still increases by 1 and breaks out.
at last the number become 5. Easy.
+ 2
Awesome, my pleasure :)
+ 1
Number will increase to 5 before the while loop registers that Number is not less than 5.
(in kinda pseudo code)
start: 2
while loop: {
2 < 5
Number =3
3 < 5
Number =4
4 < 5
Number =5
5 NOT < 5
}
return: 5
(sorry if it looks bad, I'm typing on my phone)
+ 1
thanks! Now my confusion is clear.