+ 4

Can someone please explain why this code alerts 12? I can't quite get my head around it

var k = 6; for (var i = 0; i < k; i++) { k += 0.5; } alert(i);

28th Jun 2019, 7:47 AM
Jesse Brite
Jesse Brite - avatar
1 Respuesta
+ 7
If you go through the whole loop, it's easier: i = 0, k = 6 i = 1, k = 6.5 i = 2, k = 7 i = 3, k = 7.5 i = 4, k = 8 i = 5, k = 8.5 i = 6, k = 9 i = 7, k = 9.5 i = 8, k = 10 i = 9, k = 10.5 i = 10, k = 11 i = 11, k = 11.5 i = 12, k = 12, therefore i will be 12
28th Jun 2019, 7:53 AM
Airree
Airree - avatar