Arrays: ordered lists
An array is an ordered list. Each item has a position, called its index, starting from 0 โ not 1. This trips up nearly every beginner at least once.
Common array methods
| Method | Does |
|---|---|
.push(item) | Adds an item to the end |
.pop() | Removes the last item |
.includes(item) | Returns true/false if the array contains it |
.indexOf(item) | Returns the position of an item, or -1 if not found |
Looping through an array
.forEach() runs a function once for every item in the array automatically โ no manual index tracking needed. It's the standard way to loop through arrays in modern JavaScript.
Objects: labeled data
Where an array uses numbered positions, an object uses named keys. Use objects whenever data has labeled fields โ a user profile, a product with a name/price/description โ rather than a simple ordered list.
Changing and adding properties
Arrays of objects: the pattern you'll use constantly
This combination โ a list of objects โ is how almost all real-world data looks: a list of products, a list of comments, a list of users. Getting comfortable with this pattern is one of the most valuable things in this whole course.
Try it yourself
title and author properties. Use .forEach() to log each one as "Title by Author".
Level up: filtering data
users array from above, write a loop that only logs users who are 25 or older. This combines everything so far: arrays, objects, and the if statement from Lesson 2.
1. What index does the first item in an array have?
2. Which is best for data with labeled fields, like a user's name and age?
3. What does .forEach() do?
.forEach() is your go-to for looping through any array.