Know the difference between JavaScript Arrays and Objects - and know when to use them.
Difference:
Arrays use numbered indexes
Objects use named indexes
When to use:
Use Arrays when you want the keys to be numbers.
Use Objects when you want the keys to be strings.
How to use Arrays
const pets = ["cats","hamsters","dogs"];
here you are directly assigning the elements in the array.
you can access the elements in the array by
pets[0];
pets[1];
...
pets[pets.length-1];
the starting index is always 0 and ends at array.length-1.
In case of an empty arrays:
const arr = new Array();
const arr = [];
where either of the above can be used to make a new empty array.
In order to add to the array, simply arr[index] = value
or arr.push(value)
;
const arr = new Array(size);
can be used to create an empty array of the size defined.
How to use objects
const pet = {name:"Snuffle", lastName:"Chungus", age:69};
The line above demonstrates how you can create a key-value pair. This keys can be used later to get the value.
const pet = [];
pet["name"] = "Snuffle";
pet["lastName"] = "Chungus";
pet["age"] = 69;
The codeblock above shows how key-value pairs are added to an empty object named pet
.
Top comments (4)
First, thanks for sharing things.
But, be precise, especially when you target beginners.
element names
: keys, or accessorThere is no such undefined size. The size is defined and it's 0.
Variable pet is an array, and you talk about object.
Also, you are assigning a property on person and not on pet
Thank you for your valuable input, I'll update the article with your suggestions in mind <3
Object keys can be
symbol
s as well asstring
s. With some magic, it is also possible to use arrays as keys to access object properties.Amazing! Didn't know this was possible, thanks for sharing the article - learnt something new today!