Adding contents in array

Why is the length of this array is still 3 after we assigned new property into it?

var myArray = ["foo",42,"bar"];
myArray.baz="baz";
console.log(myArray.length);
console.log(myArray.baz);

And what about this code snippet?

var myArray = ["foo",42,"bar"];
myArray["3"]= "baz";
console.log(myArray.length);
console.log(myArray[3]);

So if we want to add one more element into an array, we should use this kind of syntax?

myArray["3"]= "baz";

Valid array indexes are integers or strings “look” like integers. Only valid array indexes get counted in the length of an array, so since “baz” is not a valid array index, it does not increase the length.

Because “3” looks like 3, it will be considered a valid array index and change the length of the array.

No, it is highly recommended to use proper array methods such as push and unshift for adding elements to an array. Using a built-in method guarantees properties like length have the correct value. For example, let’s say you have:

var myArray = [];
console.log(myArray.length); // yields 0
myArray[0] = 'foo';
console.log(myArray.length); // yields 1
myArray[10] = 'bar';
console.log(myArray.length); // yields 11

11? What does myArray look like now? Let’s see:

console.log(JSON.stringify(myArray));

The above console.log yields:

[“foo”,null,null,null,null,null,null,null,null,null,“bar”]

You can see how this would cause trouble when looping through the array when you thought you only had two elements in it.

1 Like

thanks for the clarification.