← thecodex.expert · The Codex Family of Knowledge
JavaScript Course Lesson 11 of 16
The Codex / JavaScript / Arrays

Arrays

JavaScript's ordered list — creating, accessing, modifying, looping, and the methods every developer uses daily.

What it is, in plain English: An array is an ordered list of values. It can hold anything — numbers, strings, objects, even other arrays — and you access each item by its position number (starting from 0). Arrays are the most-used data structure in JavaScript. You'll use them in almost every program you write.
Where this bites you

sort() doesn't return a sorted copy; it rearranges the array you call it on and returns that same array. const ranked = scores.sort(...) therefore leaves both names pointing at one reordered array, and the original order is gone. Anything that relied on it, such as "the order players signed up", silently changes too.

const signupOrder = [42, 7, 19];          // scores, in the order players signed up

const ranked = signupOrder.sort((a, b) => b - a);

console.log("ranked:", ranked);              // [ 42, 19, 7 ]
console.log("signup order:", signupOrder);   // [ 42, 19, 7 ]  <- original order lost

Working with lists of things

Almost every program needs to work with collections of things — a list of products, a set of scores, a queue of messages. In JavaScript, that's an array: an ordered list where each item has a numbered position.

Creating an array

// Square brackets, items separated by commas
const colours = ["red", "green", "blue"];
const scores  = [95, 87, 72, 100, 68];
const mixed   = ["Alice", 30, true, null];   // arrays can hold any types
const empty   = [];                           // empty array

Accessing items — index starts at 0

const colours = ["red", "green", "blue"];
//               index:  0       1       2

console.log(colours[0]);       // "red"    — first item
console.log(colours[1]);       // "green"  — second item
console.log(colours[2]);       // "blue"   — third item
console.log(colours[3]);       // undefined — past the end

console.log(colours.length);  // 3 — how many items
console.log(colours.at(-1));  // "blue"  — last item (modern)
console.log(colours.at(-2));  // "green" — second-to-last

Adding and removing items

const cart = ["apple", "bread"];

// Add to the END:
cart.push("milk");
console.log(cart);   // ["apple", "bread", "milk"]

// Remove from the END (returns the removed item):
const removed = cart.pop();
console.log(removed); // "milk"
console.log(cart);    // ["apple", "bread"]

// Add to the BEGINNING:
cart.unshift("eggs");
console.log(cart);    // ["eggs", "apple", "bread"]

// Remove from the BEGINNING:
cart.shift();
console.log(cart);    // ["apple", "bread"]

Looping over an array

const names = ["Alice", "Bob", "Charlie"];

// for...of — cleanest, use this most of the time
for (const name of names) {
  console.log(`Hello, ${name}!`);
}

// forEach — useful when you need the index too
names.forEach((name, index) => {
  console.log(`${index + 1}. ${name}`);
});
// 1. Alice
// 2. Bob
// 3. Charlie

The three most useful array methods

These three methods transform arrays without changing the original:

const prices = [10, 25, 5, 40, 15];

// map — transform every item, produce a new array
const doubled = prices.map(price => price * 2);
console.log(doubled);   // [20, 50, 10, 80, 30]

// filter — keep only items that pass a test
const expensive = prices.filter(price => price > 15);
console.log(expensive); // [25, 40]

// reduce — combine all items into one value
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total);     // 95

Finding things

const nums = [3, 7, 2, 9, 4];

nums.includes(7);              // true  — does it contain 7?
nums.indexOf(9);               // 3     — what index is 9 at? (-1 if not found)
nums.find(n => n > 5);         // 7     — first item matching condition
nums.findIndex(n => n > 5);    // 1     — index of first match
nums.some(n => n > 8);         // true  — does ANY item pass?
nums.every(n => n > 0);        // true  — do ALL items pass?

The copy trap — arrays are reference types

const a = [1, 2, 3];
const b = a;           // b points to the SAME array as a!

b.push(4);
console.log(a);        // [1, 2, 3, 4] — a changed too!

// Fix: copy with spread
const c = [...a];      // c is a NEW array with the same values
c.push(5);
console.log(a);        // [1, 2, 3, 4] — a is unaffected

Spread and destructuring

// Spread (...) — expand an array into individual items
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined);  // [1, 2, 3, 4, 5, 6]

// Destructuring — unpack values into variables
const [first, second, ...rest] = [10, 20, 30, 40, 50];
console.log(first);  // 10
console.log(second); // 20
console.log(rest);   // [30, 40, 50]

// Swap two variables cleanly:
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y);   // 2 1
Try It Yourself

Official Sources

The Codex links only to official documentation and the ECMAScript specification. No third-party tutorials.