Objects are perfect when a thing has several different named pieces of information. But often you have the opposite situation: many values of the same kind, with no individual names, that simply need to sit together in order. A list of colours, a list of prices, a list of users. For that, JavaScript gives you the array. In fact, a list of objects is itself just an array, which makes arrays one of the most-used structures in the language. This article introduces what an array is, how to read items out of it, why it can grow and shrink on the fly, and how to find out how many items it holds.
What an array is
An array is an ordered collection of values. You create one with square brackets, listing the values inside, separated by commas.
let selectedColors = ['red', 'blue'];
Where an object labels each value with a key, an array keeps its values in a sequence and refers to each one by its position. That position is called the index, and the single most important thing to learn about it is that indexing starts at zero. The first item is at index 0, the second at index 1, and so on.
Reading items by index
To read a value, write the array’s name followed by the index in square brackets.
console.log(selectedColors[0]); // red
Because counting starts at zero, selectedColors[0] is the first colour, not the second. This off-by-one feeling trips up almost every beginner, so it is worth saying plainly: the first element is index 0, and the last element of an array with n items is index n minus 1.
Arrays are dynamic
Unlike arrays in some stricter languages, a JavaScript array does not have a fixed size. You can assign a value to an index that does not yet exist, and the array simply grows to accommodate it.
selectedColors[2] = 'green'; // the array now has three items
The array started with two colours at indexes 0 and 1, and assigning to index 2 expands it to hold a third. This dynamic nature is one of the things that makes arrays so convenient: you do not have to declare up front how big the list will be.
JavaScript is also relaxed about what goes inside an array. The values do not all have to be the same type, so you can mix strings and numbers freely.
selectedColors[3] = 1; // a number, sitting alongside the strings
This is perfectly legal, and the array now holds three strings and a number. That said, just because you can mix types does not mean you usually should. In real code an array almost always holds values of one kind, a list of colours or a list of prices, because that consistency is what lets you loop over it and treat every item the same way. Mixed-type arrays are allowed, but a clean, single-type array is what you want most of the time.
How many items: the length property
Every array carries a length property that tells you how many items it currently holds.
console.log(selectedColors.length); // 4
After the expansions above, the array has four items, so its length is four. Notice the connection between length and indexing: because the indexes run from 0, the last item always sits at length minus one. So selectedColors[selectedColors.length - 1] is a reliable way to reach the final element no matter how the array has grown. The length also updates automatically as the array changes, so it always reflects the current size.
A first look at growing arrays properly
Assigning directly to an index works, but in practice you rarely know or want to manage indexes by hand. JavaScript arrays come with methods for adding and removing items, and the most common is push, which appends to the end.
selectedColors.push('yellow');
This adds a new item without you having to work out the right index, and it is the idiomatic way to grow a list. There are many more array methods for searching, removing, and transforming items, but push is the one you will reach for first, and it is enough to start building lists naturally.
Arrays or objects?
The choice between the two is usually clear once you ask what you are modelling. Use an object when a single thing has several different named attributes, like a person with a name, an age, and an email, where each value means something distinct. Use an array when you have many values of the same kind in a meaningful order, like a list of colours or a list of those person objects. The two work together constantly: an array of objects is the everyday shape of real data, a list of users, a list of products, each entry an object, the whole collection an array.
Putting it together: a shopping cart
The clearest way to see arrays earn their keep is an array of objects, the everyday shape of real data. Here is a small shopping cart, where the cart is an array and each item in it is an object.
let cart = [ { name: 'T-shirt', price: 20 }, { name: 'Mug', price: 8 }];
The cart starts with two products. Because it is an array, the items are ordered and reachable by index, and because each item is an object, every product carries its own named details.
Reading a single product works by index, and then by property.
console.log(cart[0].name); // T-shirtconsole.log(cart[0].price); // 20
cart[0] gives you the first object in the array, and .name reaches into that object for its property. This combination, an index to pick the item then a dot to pick the detail, is something you will write constantly.
A cart is never fixed, so you add to it with push rather than juggling indexes by hand.
cart.push({ name: 'Cap', price: 15 });console.log(cart.length); // 3
The new product is appended to the end, and length now reports three items. Notice you did not have to know or set the index; push handled the position for you.
The real payoff comes from looping, because once the items are uniform you can treat every one the same way. Here we add up the total price of everything in the cart.
let total = 0;for (let i = 0; i < cart.length; i++) { total = total + cart[i].price;}console.log(total); // 43
The loop runs from index 0 up to one below the length, which is exactly the valid range of indexes, and on each pass cart[i]is the current product and cart[i].price is its price. Adding each price into total gives the cart’s value, 43, and crucially this same loop works whether the cart holds three items or three hundred. That is the whole point of an array: line up many things of the same kind, then process them all with one piece of code.
Put together, this tiny example uses every idea from the article. The cart is a dynamic array, each entry is an object accessed by index, push grows it cleanly, length tracks its size, and a loop turns the ordered list into a useful result. Almost every list you build in JavaScript, a list of users, orders, messages, or search results, follows exactly this pattern.
Conclusion
An array is an ordered list of values, accessed by a zero-based index, where the first item lives at position 0. It is dynamic, growing as you assign to new positions, and flexible about types, though you will almost always keep one type per array. The length property tells you how many items it holds, and the last item always sits at length minus one. Reach for push to add items cleanly rather than juggling indexes, and remember the division of labour with objects: objects name the parts of one thing, arrays line up many things in order. Together they are the foundation of nearly every data structure you will build in JavaScript.
See you soon.
[…] JavaScript Arrays: An Introduction […]
[…] JavaScript Arrays: An Introduction […]