0
let arr = [1,2]
arr[9]=10

My question is, if I use forEach loop, then output is different and if I use JS convention for loop, then output is different, Can someone help me to getting this ?

In situation first, if we use forEach loop,

arr.forEach((item,index)=>{  
   console.log(item,index);
}

then I am getting output this:-enter image description here

and, if I am using the convention for loop,

for(int i=0;i<arr.length;i++){
    console.log(arr[i]);
}

then, the output is this , undefined 7 times:- enter image description here

can, someone help me to getting this? why this is happening? what's the logic behind this?

  • You have a sparse array. Most array methods will only iterate over existing keys while your for-loop accesses the indices if they exist or not. – Thomas Oct 14 '22 at 12:39

0 Answers0