+ 3

Can someone pls explain why this code is outputting 12 ?

var arr = [1, 2, 3, 4]; var length = arr.length; for(var i =0; i < length; i++) { length--; document.write(arr[i]); }

28th May 2021, 4:32 PM
Lara
Lara - avatar
4 Answers
+ 14
The loop runs 2 times because the length variable is changed 2 times and its value at the end of the second iteration is 2.
28th May 2021, 4:41 PM
Igor Makarsky
Igor Makarsky - avatar
+ 3
Lara, please, stop being lazy, I gave you a great tool for step-by-step tracking of code execution. take advantage of it! try to do most of the work yourself
28th May 2021, 4:35 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 2
Hey, I'm not being lazy before i asked the question, i tried solving it with python Tutor but I'm still confused :( . I understand the initial length is 4 then length-- is 3, was 12 gotten by multiplying both values or wah? Damn JavaScript gives me headache and always makes me feel dump. I really don't know what to do to help me understand JS but i won't give up.
28th May 2021, 4:48 PM
Lara
Lara - avatar
+ 1
Lara length = 4; for (i = 0; i < length; i++) After this iteration length will be increment by 1 so length will be 3 and a[0] will be 1 Now your 2nd iteration will look like this: for (i = 1; i < 3; i++) after this iteration length will be 2 and a[1] will be 2 Now your 3rd iteration will look like this: for (i = 2; i < 2; i++) now this will not execute because of 2 < 2 false So your final result will be 12
28th May 2021, 5:18 PM
A͢J
A͢J - avatar