Lesson 6: Arrays - Working with Lists

What You'll Learn

  • What arrays are and when to use them
  • How to create and access arrays
  • How to add, remove, and modify array elements
  • Common array methods
  • How to loop through arrays

Why This Matters

Arrays let you store multiple values in a single variable. Instead of creating student1, student2, student3, etc., you can store all students in one array. This makes your code cleaner and easier to work with when dealing with collections of data.

---

Part 1: What is an Array?

An array is an ordered list of values. Think of it like:

  • A shopping list with numbered items
  • A playlist of songs
  • A row of mailboxes, each with a number

Each item in an array has:

  • A value: The actual data
  • An index: Its position (starting from 0!)

---

Part 2: Creating Arrays

Create a new file: lesson-06/arrays.js

Basic Array Creation

// Array of numbers
const ages = [25, 30, 18, 42, 35];

// Array of strings
const names = ["Alice", "Bob", "Charlie"];

// Array of booleans
const flags = [true, false, true, true];

// Empty array
const emptyArray = [];

console.log(ages);   // [25, 30, 18, 42, 35]
console.log(names);  // ["Alice", "Bob", "Charlie"]

Arrays Can Hold Any Type

// Numbers
const numbers = [1, 2, 3];

// Strings
const colors = ["red", "blue", "green"];

// It's best to keep arrays with consistent types

Mixed Arrays (Not Recommended)

// You CAN have different types, but it's usually not a good idea
const mixed = ["Alice", 25, "Bob", 30];

// Better: Use consistent types or separate arrays
const names = ["Alice", "Bob"];
const ages = [25, 30];

---

Part 3: Accessing Array Elements

Arrays use zero-based indexing - the first element is at index 0.

const fruits = ["Apple", "Banana", "Orange", "Mango"];

// Access by index
console.log(fruits[0]);  // Apple (first element)
console.log(fruits[1]);  // Banana (second element)
console.log(fruits[2]);  // Orange
console.log(fruits[3]);  // Mango (last element)

// What about index 4?
console.log(fruits[4]);  // undefined (doesn't exist)

Why Start at 0?

Index:    0        1         2        3

Value: ["Apple", "Banana", "Orange", "Mango"]

This comes from how computers store data in memory. It's a universal convention in most programming languages.

Array Length

const fruits = ["Apple", "Banana", "Orange"];

console.log(fruits.length);  // 3 (number of elements)

// Get the last element (length - 1)
const lastFruit = fruits[fruits.length - 1];
console.log(lastFruit);  // Orange

---

Part 4: Modifying Arrays

Changing Elements

const scores = [85, 90, 78];

console.log(scores);  // [85, 90, 78]

// Change the second element (index 1)
scores[1] = 95;

console.log(scores);  // [85, 95, 78]

Adding Elements

const colors = ["red", "blue"];

// push() - Add to the end
colors.push("green");
console.log(colors);  // ["red", "blue", "green"]

colors.push("yellow");
console.log(colors);  // ["red", "blue", "green", "yellow"]

// unshift() - Add to the beginning
colors.unshift("purple");
console.log(colors);  // ["purple", "red", "blue", "green", "yellow"]

Removing Elements

const numbers = [1, 2, 3, 4, 5];

// pop() - Remove from the end
const lastNumber | undefined = numbers.pop();
console.log(lastNumber);  // 5
console.log(numbers);     // [1, 2, 3, 4]

// shift() - Remove from the beginning
const firstNumber | undefined = numbers.shift();
console.log(firstNumber);  // 1
console.log(numbers);      // [2, 3, 4]
Note: pop() and shift() return the removed element (or undefined if array is empty).

Removing by Index

const fruits = ["Apple", "Banana", "Orange", "Mango"];

// splice(startIndex, deleteCount)
fruits.splice(1, 1);  // Remove 1 element at index 1
console.log(fruits);  // ["Apple", "Orange", "Mango"]

// Remove multiple elements
const numbers = [1, 2, 3, 4, 5];
numbers.splice(1, 3);  // Remove 3 elements starting at index 1
console.log(numbers);  // [1, 5]

Inserting Elements

const letters = ["A", "B", "E"];

// splice(index, 0, newElements...) - 0 means don't delete anything
letters.splice(2, 0, "C", "D");
console.log(letters);  // ["A", "B", "C", "D", "E"]

---

Part 5: Array Methods

Finding Elements

const numbers = [10, 20, 30, 40, 50];

// indexOf() - Find the index of an element
const index = numbers.indexOf(30);
console.log(index);  // 2

// If element doesn't exist, returns -1
const notFound = numbers.indexOf(100);
console.log(notFound);  // -1

// includes() - Check if element exists
console.log(numbers.includes(30));   // true
console.log(numbers.includes(100));  // false

Joining and Splitting

// join() - Convert array to string
const words = ["Hello", "World", "from", "JavaScript"];
const sentence = words.join(" ");
console.log(sentence);  // "Hello World from JavaScript"

const numbers = [1, 2, 3, 4];
const csv = numbers.join(",");
console.log(csv);  // "1,2,3,4"

// split() - Convert string to array
const text = "Apple,Banana,Orange";
const fruits = text.split(",");
console.log(fruits);  // ["Apple", "Banana", "Orange"]

Reversing and Sorting

// reverse() - Reverse the array (modifies original!)
const numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers);  // [5, 4, 3, 2, 1]

// sort() - Sort the array (modifies original!)
const names = ["Charlie", "Alice", "Bob"];
names.sort();
console.log(names);  // ["Alice", "Bob", "Charlie"]

// Sorting numbers (needs special handling)
const scores = [100, 50, 75, 25];
scores.sort((a, b) => a - b);  // Ascending order
console.log(scores);  // [25, 50, 75, 100]

scores.sort((a, b) => b - a);  // Descending order
console.log(scores);  // [100, 75, 50, 25]

Slicing Arrays

const fruits = ["Apple", "Banana", "Orange", "Mango", "Grape"];

// slice(start, end) - Get a portion (doesn't modify original)
const someFruits = fruits.slice(1, 3);
console.log(someFruits);  // ["Banana", "Orange"]
console.log(fruits);      // Original unchanged

// slice(start) - From start to end
const lastTwo = fruits.slice(3);
console.log(lastTwo);  // ["Mango", "Grape"]

Concatenating Arrays

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

// concat() - Combine arrays
const combined = arr1.concat(arr2);
console.log(combined);  // [1, 2, 3, 4, 5, 6]

// Spread operator (modern way)
const combined2 = [...arr1, ...arr2];
console.log(combined2);  // [1, 2, 3, 4, 5, 6]

---

Part 6: Looping Through Arrays

For Loop (Traditional)

const numbers = [10, 20, 30, 40, 50];

for (let i = 0; i < numbers.length; i++) {
  console.log(`Index ${i}: ${numbers[i]}`);
}
// Output:
// Index 0: 10
// Index 1: 20
// Index 2: 30
// Index 3: 40
// Index 4: 50

For...of Loop (Modern)

const fruits = ["Apple", "Banana", "Orange"];

for (const fruit of fruits) {
  console.log(fruit);
}
// Output:
// Apple
// Banana
// Orange

forEach Method

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

names.forEach((name, index) => {
  console.log(`${index}: ${name}`);
});
// Output:
// 0: Alice
// 1: Bob
// 2: Charlie

We'll learn more about loops in the next lesson!

---

Part 7: Practical Examples

Example 1: Shopping Cart

const cart = [];

// Add items
cart.push("Laptop");
cart.push("Mouse");
cart.push("Keyboard");

console.log(`Cart has ${cart.length} items`);
console.log(cart);

// Remove last item
cart.pop();
console.log(`Cart now has ${cart.length} items`);

Example 2: Grade Calculator

function calculateAverage(grades[]) {
  let sum = 0;
  for (const grade of grades) {
    sum += grade;
  }
  return sum / grades.length;
}

const myGrades = [85, 90, 78, 92, 88];
const average = calculateAverage(myGrades);
console.log(`Average grade: ${average}`);  // 86.6

Example 3: Find Maximum

function findMax(numbers[]) {
  let max = numbers[0];
  
  for (const num of numbers) {
    if (num > max) {
      max = num;
    }
  }
  
  return max;
}

const scores = [45, 78, 92, 65, 88];
console.log(`Highest score: ${findMax(scores)}`);  // 92

---

Practice Exercises

Exercise 1: Sum of Array

Create a function that returns the sum of all numbers in an array.

Exercise 2: Remove Duplicates

Create a function that removes duplicate values from an array.

Exercise 3: Find Element

Create a function that finds if a name exists in an array of names.

Exercise 4: Reverse Without reverse()

Create a function that reverses an array without using the reverse() method.

Exercise 5: Filter Even Numbers

Create a function that returns a new array with only even numbers.

Exercise 6: Todo List

Create a simple todo list:

  • Add tasks
  • Remove tasks
  • Show all tasks
  • Count tasks

---

Common Mistakes

Mistake 1: Off-by-One Error

const arr = [1, 2, 3];

// ❌ WRONG - goes beyond array
for (let i = 0; i <= arr.length; i++) {
  console.log(arr[i]);  // Last iteration: undefined
}

// ✅ CORRECT
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

Mistake 2: Modifying While Looping

const numbers = [1, 2, 3, 4, 5];

// ❌ WRONG - Don't modify array while looping over it
for (let i = 0; i < numbers.length; i++) {
  numbers.pop();  // Changes length while looping!
}

// ✅ CORRECT - Loop backwards or use a copy
for (let i = numbers.length - 1; i >= 0; i--) {
  numbers.pop();
}

Mistake 3: Confusing push/pop with shift/unshift

const arr = [1, 2, 3];

arr.push(4);     // Adds to END → [1, 2, 3, 4]
arr.pop();       // Removes from END → [1, 2, 3]
arr.unshift(0);  // Adds to BEGINNING → [0, 1, 2, 3]
arr.shift();     // Removes from BEGINNING → [1, 2, 3]

---

Key Concepts Summary

Method What It Does Modifies Original?
push(item) Add to end Yes
pop() Remove from end Yes
unshift(item) Add to beginning Yes
shift() Remove from beginning Yes
splice() Add/remove at index Yes
slice() Get portion No
concat() Combine arrays No
indexOf() Find index No
includes() Check if exists No
join() Array to string No
reverse() Reverse order Yes
sort() Sort elements Yes

What You Learned

  • ✅ How to create and initialize arrays
  • ✅ How to access elements using indexes (starting at 0)
  • ✅ How to add and remove elements
  • ✅ Common array methods (push, pop, slice, etc.)
  • ✅ How to loop through arrays
  • ✅ How to work with array length
  • ✅ The difference between methods that modify the array and those that don't

What's Next?

In the next lesson, you'll learn about loops - how to repeat code efficiently using for, while, and other loop types!