5.5 Objects v. Arrays

5.5 Objects v. Arrays

Objects represent a special data type that is mutable and can be used to store a collection of data (rather than just a single value).
Arrays are a special type of variable that is also mutable and can also be used to store a list of values.
So what exactly is the difference between objects and arrays, when do you use which, and how to do work with each of them?


Objects are used to represent a “thing” in your code. That could be a person, a car, a building, a book, a character in a game — basically anything that is made up or can be defined by a set of characteristics.
In objects, these characteristics are called properties that consist of a key and a value.
// Basic object syntax let object = { key: 'value' }; // Example 'person' object let person = { name: 'Zac', age: 33, likesCoding: true };


We use arrays whenever we want to create and store a list of multiple items in a single variable. Arrays are especially useful when creating ordered collections where items in the collection can be accessed by their numerical position in the list.
Just as object properties can store values of any primitive data type (as well as an array or another object), so too can arrays consist of strings, numbers, booleans, objects, or even other arrays.

Wrapping Up

Objects represent “things” with characteristics (aka properties), while arrays create and store lists of data in a single variable. Both dot and bracket notation allow us to access, add, change, and remove items from an object, while zero-based indexing and a variety of built-in methods let us access and alter items in an array. Finally, we can iterate over object properties and array items using various loops (e.g. for, for…in, for…of, forEach()).
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.