Skip to content
Codewilds

Lesson 15 of 34 · Arrays

JavaScript Arrays: Methods and Loops for Beginners

easy10 XP3 min read

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], not arr[arr.length].
  • Forgetting which methods mutate. push, pop, shift and unshift change the array; slice, includes, indexOf and join don't.
  • Comparing arrays with ===. [1, 2] === [1, 2] is false, 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:

  1. addLoot(bag, item) adds item to the end of bag, but only if the bag doesn't already contain it. It changes the original array and returns bag.
    • addLoot(["sword"], "shield") → ["sword", "shield"]
    • addLoot(["gem"], "gem") → ["gem"] (no duplicates)
  2. takeTopItems(bag, count) returns a new array with the first count items, without changing bag.
    • takeTopItems(["a", "b", "c", "d"], 2) → ["a", "b"]
  3. countItem(bag, item) returns how many times item appears in bag.
    • 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
Play the 8 free lessons

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

Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.

Lesson last updated on .

Write code ↓
JavaScript+10 XP

Lesson 15 is part of the full course. The first 8 lessons are free.

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
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.