Array vs Object in JavaScript – Learn the Difference
Here are three main differences between an array and a properties object:
How to Define an Array and an Object
A pair of square brackets ([...]
) defines JavaScript’s array object. However, we use braces ({...}
) to define properties objects.
Let’s see some examples:
Example 1: An array with two unnamed values
Above is an array object containing two unnamed values.
Example 2: An object with two properties
Above is a properties object containing two properties named month
and year
.
We initialized the month
property with a string value while year
got assigned a number.
How to Name the Values of an Array and an Object
An array does not permit users to name its items. However, you can assign any name to the values of a properties object.
Here’s an example:
You can see that we could name each value in our properties object. However, we could not assign names to the array’s items.
How to Access the Values of an Array and an Object
You can use the dot notation or square bracket syntax to access a properties object’s value.
However, you can use only the square bracket notation to access an array’s value.
Let’s see some examples.
Example 1: How to access a properties object’s value
The snippet above used the dot notation to access the propertiesObject
’s value.
Here’s the square bracket alternative:
Now, let’s see an example of retrieving an array’s value.
Example 2: How to access an array object’s value
The snippet above used the square bracket syntax to access the arrayObject
’s value.
Remember that the square bracket is the only way to access an array’s value. Using the dot notation will throw an error.
Here’s an example:
The snippet above threw an error because you cannot use the dot syntax to access an array’s value.