Arrays & objects: the basics
Create, read, update and loop over arrays and objects — JavaScript’s two workhorse structures.
Almost all real data is a collection: a list of products, a user profile, a table of scores. JavaScript's two workhorse structures are arrays (ordered lists) and objects (named properties). This lesson covers the basics of both; the following lessons go deeper.
Arrays: ordered lists#
Arrays can hold any mix of types, including other arrays and objects — but in practice, keep each array to one kind of thing.
Adding and removing items
push, pop, shift, unshift and index assignment mutate (change) the array in place.
splice and slice
Mnemonic: splice has a "p" for "permanent change". Modern JavaScript also has toSpliced, a non-mutating version — covered in Array methods.
Searching
Looping over an array
Objects: named properties#
An object groups related values under keys (property names):
Dot vs bracket notation
Use dot notation normally. Use brackets when the key is in a variable or isn't a valid identifier:
Adding, changing and removing properties
Methods: functions inside objects
Inside a method, this refers to the object the method was called on. There's a full lesson on this later.
Looping over an object
Arrays of objects: real-world data#
Most data from APIs looks like this:
References: why copies surprise people#
Arrays and objects are stored by reference. Assigning one to another variable doesn't copy it — both names point to the same data:
=== on objects compares identity, not contents. Copying and comparing are covered properly in Objects in depth and Destructuring & spread.
Arrays or objects?#
For lookups by arbitrary keys (like ids) or when keys aren't strings, a Map is often better — see Map, Set, WeakMap & WeakSet.
Common mistakes#
- Reading
arr[arr.length]— the last element is atlength - 1. - Using
obj.keywhenkeyis a variable. - Thinking
const arr = []can't change — it can be mutated, just not reassigned. - Expecting
===to compare the contents of two arrays or objects.
What's next#
You can store and access collections. Next, transform them like a pro with array methods: map, filter, reduce, find, sort and more.
Check your understanding
Quick quiz
1.Given
const langs = ["JS", "Python", "Java"];, what islangs[langs.length - 1]?2.Which is the right way to read a property whose name is stored in a variable
key?3.Which array method adds an item to the **start** of an array?
Finished reading?
Mark this lesson complete to track your progress.