I was surprised that this works in JavaScript. My questions is, is this good practice?
var contact = [];
contact[0] = {};
contact[0].name = "Peter Parker";
console.log(contact[0].name);
I was surprised that this works in JavaScript. My questions is, is this good practice?
var contact = [];
contact[0] = {};
contact[0].name = "Peter Parker";
console.log(contact[0].name);
Which part? Setting 0
of contact
is generally not good practice when the array is empty - instead, you should make an object, then push
that object into the array.
On the other hand, if you're talking about setting a property of contact[0]
- yep! That's the entire point of objects - you can think of them similarly to Python dictionaries, except you don't need to use bracket notation to access it.
You can also define the names right inside of the object:
var contact = {name: "Peter Parker"};
To push the object into an array called contacts
:
contacts.push(contact);
Nothing wrong is here, or surprise. You get equivalent of next code
var contact = [{
'name': "Peter Parker"
}];
At first you create array, and then put object in it.
There is nothing wrong with the code provided nor is it good or bad practice; that completely depends on the context (use the right tool for the right job concept).
All you're doing is creating an array where the first item is an object. You can nest arrays inside of arrays or objects inside of objects, or go even further and nest them multiple times.