+ 1

Can you describe this code for me?

var arr =[1,2,3,4] var count=0 for(var x = 0; x<arr.lenght; x++){ x=arr[x] count++ } document.write(count)

22nd Feb 2020, 5:54 PM
Arsham Aazami
Arsham Aazami - avatar
2 Answers
+ 1
I don't know much JavaScript but I think it is easy the for loop iterates until x reaches the length of array. Let's make it more simple. count. = 0 arr.length = 4 arr = [1,2,3,4] indx 0 1 2 3 so loop is like for (x = 0; x<4, x++){ x = arr[x] count = count + 1; } So, first it will iterate and the values will be x = arr[0] x = 1 count will become 1 Similarly for second time x = arr[1] // x become one above (x = 2) count will become 2 . . . x = arr[3] (x = 4) count will become 4 as well But now the loop will not continue because arr.length was 4 x has also become 4. So x is no longer less than arr.length so document.write(count) Will write 4 as count has also become 4. I hope you understand. If my answer is wrong, tell me!
22nd Feb 2020, 6:06 PM
Utkarsh Sharma
Utkarsh Sharma - avatar
0
Thanks for your help😉😉
22nd Feb 2020, 6:10 PM
Arsham Aazami
Arsham Aazami - avatar