+ 1

Can anyone explain why it gives output 5.

function test(Number) { while(Number<5){ Number++; } return Number; } alert (test (2))

24th Mar 2017, 2:57 PM
Mohit Kumar
Mohit Kumar - avatar
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.
24th Mar 2017, 3:08 PM
Cyrus Ornob Corraya
Cyrus Ornob Corraya - avatar
+ 2
Awesome, my pleasure :)
24th Mar 2017, 3:08 PM
Qaanita Fataar
Qaanita Fataar - avatar
+ 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)
24th Mar 2017, 3:05 PM
Qaanita Fataar
Qaanita Fataar - avatar
+ 1
thanks! Now my confusion is clear.
24th Mar 2017, 3:07 PM
Mohit Kumar
Mohit Kumar - avatar