⚡ Phase 1 · Foundations 🟡 Intermediate MODULE 08

JavaScript Arrays

⏱️ 35 min read
📖 Theory + Code
🧩 5 Quiz Questions
🏗️ 1 Challenge
Your progress in Phase 162%
🎯 What you'll learn: How to create and manipulate arrays in JavaScript — from basics like push/pop to powerful functional methods like map, filter, and reduce. You'll also cover destructuring, spread, sorting, and build real examples like a shopping cart.

Creating Arrays

An array is an ordered list of values. Each value is called an element, and each element has a numeric index starting at 0.

Creating Arrays — 3 Ways
JS
// 1. Array literal (most common)
const fruits = ['apple', 'banana', 'cherry'];

// 2. Array constructor
const nums = new Array(1, 2, 3, 4, 5);

// 3. Array.from() — convert iterable to array
const letters = Array.from('hello');   // ['h','e','l','l','o']
const range = Array.from({length:5}, (_,i) => i+1); // [1,2,3,4,5]

// Mixed types (JavaScript allows this)
const mixed = [1, 'hello', true, null, {name:'Ali'}];

Accessing Elements

Accessing & Negative Index Workaround
JS
const colors = ['red', 'green', 'blue', 'yellow'];

// Access by index (0-based)
colors[0];           // 'red'
colors[2];           // 'blue'
colors[colors.length - 1]; // 'yellow' — last element

// Modern: .at() method — supports negative indexing!
colors.at(-1);         // 'yellow' — last
colors.at(-2);         // 'blue' — second to last

// length property
colors.length;          // 4

Mutating Methods

These methods modify the original array. Use them when you intentionally want to change the array in place.

push, pop, shift, unshift, splice
JS
const arr = [1, 2, 3];

// push — add to END, returns new length
arr.push(4, 5);        // arr = [1,2,3,4,5]

// pop — remove from END, returns removed item
const last = arr.pop(); // last=5, arr=[1,2,3,4]

// unshift — add to BEGINNING
arr.unshift(0);         // arr = [0,1,2,3,4]

// shift — remove from BEGINNING
const first = arr.shift(); // first=0, arr=[1,2,3,4]

// splice(start, deleteCount, ...itemsToAdd)
arr.splice(1, 2);        // remove 2 from index 1 → arr=[1,4]
arr.splice(1, 0, 99);   // insert 99 at index 1 → arr=[1,99,4]

// slice — returns NEW array (non-mutating)
const sub = arr.slice(0, 2);  // [1,99] — doesn't change arr

Iteration Methods

These are the most powerful array tools in JavaScript. They let you transform, filter, and reduce data without writing manual loops.

forEach, map, filter, reduce
JS
const students = [
  {name: 'Ali', score: 85},
  {name: 'Sara', score: 72},
  {name: 'Bilal', score: 91},
  {name: 'Hina', score: 63}
];

// forEach — iterate, no return value
students.forEach(s => console.log(s.name));

// map — transform each element, returns NEW array
const names = students.map(s => s.name);
// ['Ali', 'Sara', 'Bilal', 'Hina']

// filter — keep elements matching condition
const passing = students.filter(s => s.score >= 70);
// [{Ali,85}, {Sara,72}, {Bilal,91}]

// reduce — accumulate to single value
const total = students.reduce((sum, s) => sum + s.score, 0);
// 311

const avg = total / students.length;  // 77.75
find, findIndex, some, every
JS
const products = [
  {id:1, name:'Laptop', price:1200},
  {id:2, name:'Phone', price:800},
  {id:3, name:'Tablet', price:450}
];

// find — returns FIRST matching element
const phone = products.find(p => p.id === 2);
// {id:2, name:'Phone', price:800}

// findIndex — returns INDEX of first match
const idx = products.findIndex(p => p.price > 1000);
// 0 (Laptop is at index 0)

// some — true if ANY element matches
const hasExpensive = products.some(p => p.price > 1000);
// true

// every — true if ALL elements match
const allAffordable = products.every(p => p.price < 2000);
// true

Spread & Destructuring

Spread Operator & Destructuring
JS
// Spread — expand array into individual elements
const a = [1, 2, 3];
const b = [4, 5];
const merged = [...a, ...b];     // [1,2,3,4,5]
const copy = [...a];             // shallow copy
Math.max(...a);                  // 3 — spread as args

// Array Destructuring
const colors = ['red', 'green', 'blue'];
const [first, second, third] = colors;
// first='red', second='green', third='blue'

// Skip elements with commas
const [,, last] = colors;   // last='blue'

// Rest operator in destructuring
const [head, ...tail] = [1, 2, 3, 4];
// head=1, tail=[2,3,4]

// Swap variables elegantly
let x = 10, y = 20;
[x, y] = [y, x];  // x=20, y=10

Sorting, Flat & FlatMap

sort, flat, flatMap
JS
// sort() — MUTATES array! Use compare function for numbers
const nums = [10, 3, 25, 1, 8];
nums.sort((a, b) => a - b);     // ascending: [1,3,8,10,25]
nums.sort((a, b) => b - a);     // descending: [25,10,8,3,1]

// Sort strings
const words = ['banana', 'apple', 'cherry'];
words.sort();                    // ['apple','banana','cherry']

// Sort objects by property
const items = [{price:30},{price:10},{price:20}];
items.sort((a,b) => a.price - b.price); // by price asc

// flat — flatten nested arrays
[1, [2, [3, [4]]]].flat();      // [1,2,[3,[4]]] — depth 1
[1, [2, [3]]].flat(Infinity); // [1,2,3] — fully flatten

// flatMap — map then flatten 1 level
const sentences = ['hello world', 'foo bar'];
sentences.flatMap(s => s.split(' '));
// ['hello','world','foo','bar']
💡
Immutable sort with spread
Since sort() mutates the original array, always sort a copy: [...arr].sort((a,b) => a-b). This is a best practice in functional programming.

Real-World Example: Product Filter

Filter & Map Products
JS
const catalog = [
  {id:1, name:'Laptop', price:1200, inStock:true},
  {id:2, name:'Mouse', price:25, inStock:true},
  {id:3, name:'Monitor', price:350, inStock:false},
  {id:4, name:'Keyboard', price:75, inStock:true},
  {id:5, name:'Headphones', price:150, inStock:true}
];

// Get in-stock items under $200
const affordable = catalog
  .filter(p => p.inStock && p.price <= 200)
  .map(p => ({name: p.name, price: `$${p.price}`}))
  .sort((a,b) => a.name.localeCompare(b.name));

// Total value of in-stock items
const totalValue = catalog
  .filter(p => p.inStock)
  .reduce((sum, p) => sum + p.price, 0);
// $1450

// Group by price range
const budget = catalog.filter(p => p.price < 100);
const premium = catalog.filter(p => p.price >= 100);
🧩 Knowledge Check — Arrays
5 questions to test your array knowledge. Instant feedback.
1. Which array method returns a NEW array without modifying the original?
2. What does arr.at(-1) return?
3. Which method would you use to add up all prices in an array of objects?
4. What is the output of [1,2,3].map(x => x * 2)?
5. Which destructuring syntax correctly extracts the first two elements?
🛒
Challenge — Shopping Cart System
Apply array methods to build a functional cart · Intermediate
Build a Shopping Cart using Array Methods

Create a cart.js file with this functionality:

1. Start with an array of products (id, name, price, qty)
2. addItem(cart, item) — adds item or increases qty if exists
3. removeItem(cart, id) — removes item by id
4. getTotal(cart) — returns total price using reduce
5. getItemCount(cart) — returns total items count
6. applyDiscount(cart, percent) — maps cart with discounted prices
7. getExpensiveItems(cart, minPrice) — filters items above price
💡 Show hints
  • Use find() to check if item exists before adding
  • Use filter(item => item.id !== id) for removing
  • Use reduce((total, item) => total + item.price * item.qty, 0) for total
  • Use map(item => ({...item, price: item.price * (1 - percent/100)})) for discount
Finished this lesson?
Mark it complete to track your progress.
🎉

Lesson 8 Complete!

You've mastered JavaScript arrays — one of the most important tools in the language. Next up: Objects!

Module 08 of 13Phase 1 — JS Foundations