Array vs Object in JavaScript – Learn the Difference
Here are three main differences between an array and a properties object:
Defining 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
["June", 2022];
Above is an array object containing two unnamed values.
Example 2: An object with two properties
{ month: "June", year: 2022 }
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.
Naming 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:
// Define an array object:const arrayObject = ["Blue", "White", "Pink", "Green"];
// Define a properties object:const propertiesObject = { carColor: "Blue", laptopColor: "White", shoeColor: "Pink", keyBoardColor: "Green",};
You can see that we could name each value in our properties object. However, we could not assign names to the array’s items.
Accessing 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
// Define a properties object:const propertiesObject = { carColor: "Blue", laptopColor: "White", shoeColor: "Pink", keyBoardColor: "Green",};
// Retrieve the propertiesObject's "White" value:propertiesObject.laptopColor;
// The invocation above will return: "White"
The snippet above used the dot notation to access the propertiesObject
’s value.
Here’s the square bracket alternative:
// Define a properties object:const propertiesObject = { carColor: "Blue", laptopColor: "White", shoeColor: "Pink", keyBoardColor: "Green",};
// Retrieve the propertiesObject's "White" value:propertiesObject["laptopColor"];
// The invocation above will return: "White"
Now, let’s see an example of retrieving an array’s value.
Example 2: How to access an array object’s value
// Define an array object:const arrayObject = ["Blue", "White", "Pink", "Green"];
// Retrieve the arrayObject's "White" value:arrayObject[1];
// The invocation above will return: "White"
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:
// Define an array object:const arrayObject = ["Blue", "White", "Pink", "Green"];
// Retrieve the arrayObject's "White" value:arrayObject.1;
// The invocation above will return: "Uncaught SyntaxError"
The snippet above threw an error because you cannot use the dot syntax to access an array’s value.