Lesson 15 of 34 · Arrays
JavaScript Arrays: Methods and Loops for Beginners
A player's inventory, the scores on a leaderboard, the messages in a chat: most programs work with lists of things. In JavaScript, lists are arrays, and they're one of the tools you'll reach for most often.
This lesson covers creating arrays, reading and changing items, the essential array methods, and the different ways to loop over an array.
Creating arrays and reading items
An array is an ordered list of values inside square brackets. Each item has an index, starting at 0:
const party = ["Ada", "Linus", "Grace"];
console.log(party[0]); // Ada
console.log(party[2]); // Grace
console.log(party.length); // 3
console.log(party[3]); // undefined (no item there)
console.log(party.at(-1)); // Grace (negative indexes count from the end)
The last item is always at index length - 1. Arrays can hold any type of value, even a mix, and even other arrays: [1, "two", true, [3, 4]].
You can replace an item by assigning to its index:
party[1] = "Margaret";
console.log(party); // [ 'Ada', 'Margaret', 'Grace' ]
Wait, party is a const. Why can we change it? const only stops you from pointing the variable at a different array. The array itself can still be modified.
Adding and removing items
These methods change the original array (they mutate it):
const loot = ["sword"];
loot.push("shield"); // add to the end → [ 'sword', 'shield' ]
loot.unshift("map"); // add to the start → [ 'map', 'sword', 'shield' ]
const last = loot.pop(); // remove from the end, returns 'shield'
const first = loot.shift(); // remove from the start, returns 'map'
console.log(loot); // [ 'sword' ]
Reading without changing
These methods leave the original array alone:
const items = ["potion", "rope", "torch", "rope"];
console.log(items.includes("torch")); // true
console.log(items.indexOf("rope")); // 1 (first match)
console.log(items.indexOf("gem")); // -1 (not found)
console.log(items.slice(1, 3)); // [ 'rope', 'torch' ] (end index excluded)
console.log(items.join(", ")); // potion, rope, torch, rope
slice works just like it does on strings, and slice() with no arguments makes a quick copy of the whole array.
Looping over arrays
for...of
When you need each value, for...of is the cleanest choice:
const scores = [12, 7, 30];
let total = 0;
for (const score of scores) {
total += score;
}
console.log(total); // 49
Classic for loop
When you need the index too, use a counting loop:
for (let i = 0; i < scores.length; i++) {
console.log(`#${i + 1}: ${scores[i]}`);
}
forEach
Arrays also have a forEach method that calls a callback for every item, passing the item and its index:
scores.forEach((score, index) => {
console.log(index, score);
});
forEach is handy for quick side effects, but you can't break out of it early. When you need to stop early, use for...of with break.
Common mistakes
- Off-by-one at the end. The last item is
arr[arr.length - 1], notarr[arr.length]. - Forgetting which methods mutate.
push,pop,shiftandunshiftchange the array;slice,includes,indexOfandjoindon't. - Comparing arrays with
===.[1, 2] === [1, 2]isfalse, because two separate arrays are never the same object, even when their contents match.
Assignment
Manage a hero's loot bag (an array of strings) with three functions:
addLoot(bag, item)addsitemto the end ofbag, but only if the bag doesn't already contain it. It changes the original array and returnsbag.addLoot(["sword"], "shield")→["sword", "shield"]addLoot(["gem"], "gem")→["gem"](no duplicates)
takeTopItems(bag, count)returns a new array with the firstcountitems, without changingbag.takeTopItems(["a", "b", "c", "d"], 2)→["a", "b"]
countItem(bag, item)returns how many timesitemappears inbag.countItem(["gem", "sword", "gem"], "gem")→2
Premium lesson
Unlock the full Learn JavaScript course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Arrays and lists in other languages
- Python Lists: Indexing and Slicing · Python
- Go Arrays vs Slices: Slicing and range · Go
- Java Arrays and the for-each Loop · Java
- C# Arrays and the foreach Loop · C#
Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.
Lesson last updated on .