The dot notation in this case is actually assigning a property to the array instead of pushing a new value into it.
const myArray = ['apples', 'bananas'];
console.log(myArray);
myArray[2] = 'peach';
console.log(myArray);
You might be drawn towards objects because of this behavior, where properties can be easily assigned:
const myObject = {
id: 1,
name: 'Pig',
type: 'animal',
}
// Standard dot-notation assignment
myObject.sound = 'Oink!';
console.log(myObject);
// "Computed" assignment
myObject['emoji'] = '🐷';
console.log(myObject);
For further insight on this topic, check out this resource.
But why can't you do something like this with arrays:
const myArray = ['choclate', 'strawberry'];
myArray.pinapple = 'Tasty';
Arrays function more as lists, so adding attributes like a "describer" doesn't align with their purpose.
While setting properties for an Array is possible (as they are based on JavaScript objects), it's not typically used in the way you may think.
Here's when I might employ the "dot notation" assignment for an Array:
let zoo = ['Dolphin', 'Lion', 'Monkey'];
console.log(zoo);
// Built-in property
console.log('I have', zoo.length, 'animals in my zoo!');
// Adding a property "income"
zoo.income = 500;
console.log('My zoo has £%s', zoo.income);
// Operating on income property
zoo.income += 50;
console.log('My zoo has £%s', zoo.income);
// Implementing a method for closing down the zoo
zoo.closeDown = () => {
zoo = [];
zoo.income = 0;
return true;
}
zoo.closeDown();
console.log(zoo);
console.log('My zoo has £%s', zoo.income);
In some scenarios, it might make sense to maintain animals in a zoo as an array and build up methods and properties from there, rather than using an object.
If you're interested in retrieving a list of these properties/methods, you can do so like this:
const myArray = ['Foo', 'Bar'];
myArray.isCool = true;
console.log(myArray);
console.log(myArray.length);
let i;
for (i in myArray) {
console.log(i, myArray[i]);
}
By using the for (i in ...)
syntax, we iterate through the array's properties as if it were an object since arrays extend the Object class to some extent.
Learn more at this link.