+ 1

JavaScript

I do not understand how this works, please someone help me out. var arr = [1,2,3,4]; var length = arr.length; for (var i = 0; i < length; i++){ length--; document.write(arr[i]); } answer is 12 but I have no idea how we got here please can someone explain it to me. Thank you in advance.

6th Oct 2021, 9:19 AM
Kelvin Wambua
Kelvin Wambua - avatar
1 Odpowiedź
+ 3
Kelvin Wambua 1st iteration of loop: length = 4, I =0 length = length -1 = 3 arr [I] = arr[0] =1//it will be printed 2nd iteration of loop: length = 3, I = 1 length = length - 1 = 2 arr[I] = arr[1] = 2 // it will be printed 3rd iteration of loop: length = 2, I = 2 So the condition ( I < length ) will be false and loop will be terminated. That's why the output is 12
6th Oct 2021, 9:39 AM
Rupali Haldiya
Rupali Haldiya - avatar