Data & LogicBeginner8 min04 / 12

Arrays

Learn how to store and work with ordered lists of data using JavaScript arrays, from basic indexing to the powerful map, filter, and reduce methods.

Imagine writing an app that tracks your favourite movies. You could create a separate variable for each one — movie1, movie2, movie3 — but that gets messy fast. What if you have 50 movies? That is exactly the problem arrays solve. An array is a single variable that holds an ordered list of values, and JavaScript gives you a rich set of tools to read, update, and transform that list with very little code.

#Creating an Array and Reading Its Length

Square brackets create an array; .length tells you how many elements it has
const fruits = ["apple", "banana", "cherry"];
const scores = [98, 72, 85, 91];

console.log(fruits);         // the whole list
console.log(scores.length);  // how many elements

#Indexing — Zero-Based Counting

Think of it like

Think of a row of lockers

Picture school lockers numbered starting from 0, not 1. The first locker is locker 0, the second is locker 1, and so on. JavaScript arrays work exactly the same way — the first element lives at index 0. This trips up almost every beginner at least once!

Access elements with bracket notation. Last valid index = length - 1
const fruits = ["apple", "banana", "cherry"];

console.log(fruits[0]); // first element
console.log(fruits[2]); // third (last) element
console.log(fruits[3]); // out of bounds — no error, just undefined
Common mistake

Off-by-one errors are silent

Trying to read an index that does not exist returns undefined — JavaScript will NOT throw an error. That means bugs like fruits[3] on a 3-element array can be easy to miss. Always remember: last valid index = array.length - 1.

#Adding, Removing, and Checking Elements

push/pop act on the end; unshift/shift act on the front; includes() checks membership
const queue = ["Alice", "Bob"];

queue.push("Carol");           // add to END
console.log(queue);            // ['Alice', 'Bob', 'Carol']

queue.pop();                   // remove from END
queue.unshift("Zara");         // add to FRONT
queue.shift();                 // remove from FRONT
console.log(queue);            // ['Alice', 'Bob']

console.log(queue.includes("Alice")); // true
console.log(queue.includes("Zara"));  // false

#Iterating Over an Array

for...of visits every element in order — clean and readable
const planets = ["Mercury", "Venus", "Earth", "Mars"];

for (const planet of planets) {
  console.log(`Planet: ${planet}`);
}

#The Big Three: map, filter, and reduce

map transforms every element; filter keeps elements that pass a test; reduce boils the list to one value. They never mutate the original, and you can chain them: numbers.filter(n => n > 2).map(n => n * 10)
const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map(n => n * 2);
console.log(doubled);

const evens = numbers.filter(n => n % 2 === 0);
console.log(evens);

const total = numbers.reduce((sum, n) => sum + n, 0);
console.log(total);
Quick check

What does `[10, 20, 30][1]` evaluate to?

Key takeaways

  • Arrays store ordered lists in a single variable using square brackets `[ ]`.
  • Indexing starts at 0 — the first element is always at index 0, and the last is at `length - 1`.
  • Use `push`/`pop` to add or remove from the end, and `unshift`/`shift` for the front.
  • `map`, `filter`, and `reduce` transform arrays without mutating the original — they are the backbone of modern JS data processing.
  • `includes()` is the quickest way to check whether a value is present in an array.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

The lesson says reading an index that does not exist returns undefined instead of throwing. What does this print?

predict-output
const fruits = ["apple", "banana", "cherry"];

console.log(fruits[0]);
console.log(fruits[3]);
Fix the bug#2

This code has a bug — what's wrong?

fix-bug
const scores = [98, 72, 85, 91];

// Try to log the last score
console.log(scores[scores.length]);
Fill in the blank#3

Complete the code so it adds "Carol" to the END of the queue, then checks that "Alice" is present. Fill in the two array methods from the lesson.

const queue = ["Alice", "Bob"];

queue.("Carol");            // add to the end
console.log(queue.("Alice")); // check membership -> true
Reorder the lines#4

Put the lines in order to: start from numbers, keep only the even numbers with filter, then double each survivor with map, and finally log the result.

1
console.log(doubled);
2
const evens = numbers.filter(n => n % 2 === 0);
3
const doubled = evens.map(n => n * 2);
4
const numbers = [1, 2, 3, 4, 5];
Your turn
Practice exercise

You have an array of product prices. Write code that: (1) adds a new price of 15 to the end of the array using push, (2) uses filter to keep only prices above 10, and (3) uses map to apply a 10% discount to those filtered prices. Log the final discounted prices.

Try it live — edit the code and hit Run to see the output:

solution.js · editable