I am unable to understand initialization

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

Now If i do arr.length I get 0

Instead of console.log(arr[i]), if I put arr[i]=undefined in the loop
arr.length comes out to be 5

Why is this so? Isn’t javascript initialising the values with undefined in the first case? Because it is console.logging undefined in that case.

If you create 5 elements with undefined values, the array still has 5 elements, so the length will be 5.

With the code below, you have not added any elements to the array, which is why you end up logging undefined 5 times. You are attempting to reference elements with indices 0 through 4 but they do not exist, so you log undefined.

let arr=[ ]
for(let i=0;i<5;i++) {
  console.log(arr[i])
}
1 Like

When you declares arr = [ ] you are saying that exist and empty array. Remember that and array consist in several values in a list, then when in the loop you say arr[i] = undefined, you are saying that that position exist in de array, but is empty, think it as the diference to make a empty list:

THINGS TO DO:

And make a list with points to anote those things:

Things to do

In the second case you are creating those “positions” even if you let empty, the marker exists

1 Like