Week 4 - Data structures and loops

Arrays

Loops

Objects

Package managers

Tools (IDE code editing)

Style - Autoformatting

Practice

Assignment

Back to core program

What are arrays?

Arrays are ordered collections that store multiple values in a single variable. Think of them as lists where each item has a numbered position (index) starting from 0.

const fruits = ['apple', 'banana', 'orange'];
const scores = [95, 87, 92, 78];
const mixed = ['text', 42, true, null];

Arrays are essential when you need to work with multiple related items: user lists, form inputs, API responses, or any collection of data that needs processing, filtering, or transformation. Unlike individual variables for each piece of data, arrays keep related information together and provide powerful methods to manipulate that data.

https://www.youtube.com/watch?v=oigfaZ5ApsM

<aside> 💡

Array indices start at 0, not 1. So the first item is at position 0, the second at position 1, and so on. This is called "zero-based indexing" and is common in most programming languages.

</aside>

<aside> 😄

A wife asks her programmer husband, "Who comes first in your life: me or your work?" The programmer replies, "You'll always be number one, dear."

</aside>

Creating arrays

There are multiple ways to create arrays in JavaScript:

// Empty array - most common way
const empty = [];

// Array with initial values
const colors = ['red', 'green', 'blue'];

// Array constructor (less common, but valid)
const numbers = new Array(1, 2, 3);

// Create array of specific length (filled with undefined)
const slots = new Array(5); // [undefined, undefined, undefined, undefined, undefined]

// Multi-line for readability
const users = [
  'Alice',
  'Bob',
  'Charlie'
];

Arrays can hold any type of value: numbers, strings, booleans, other arrays, objects, or even functions. You can also mix different types in the same array, though it's often clearer to keep arrays “homogeneous” (same type).

<aside> ⌨️

Open your browser console and create an array of your favorite movies. Try creating both a short single-line array and a longer multi-line array.

</aside>

Accessing elements

Access items using their index in square brackets. Remember that indexing starts at 0:

const languages = ['JavaScript', 'Python', 'Java', 'Ruby', 'Go'];

console.log(languages[0]);  // 'JavaScript' (first item)
console.log(languages[2]);  // 'Java' (third item)
console.log(languages[4]);  // 'Go' (last item)
console.log(languages[5]);  // undefined (doesn't exist)

// Get array length
console.log(languages.length); // 5

// Access last item using length
console.log(languages[languages.length - 1]); // 'Go'

The length property tells you how many items are in the array. Since indices start at 0, the last item is always at array.length - 1.

You can also modify array elements directly:

const cities = ['Paris', 'London', 'Tokyo'];
cities[1] = 'Berlin';
console.log(cities); // ['Paris', 'Berlin', 'Tokyo']

<aside> ⚠️

Accessing an index that doesn't exist returns undefined, not an error. Always check array length or use methods like includes() to verify elements exist.

</aside>

Manipulating arrays

There are a lot of ways to modify arrays, with built-in methods. Some common methods are push, pop, slice, indexOf, includes. With these methods you can already achieve a lot of your array-manipulation goals.

Adding and removing elements

push() - add to the end

The push() method adds one or more elements to the end of an array and returns the new length:

const todos = ['buy milk', 'walk dog'];
const newLength = todos.push('code');
console.log(newLength); // 3
console.log(todos); // ['buy milk', 'walk dog', 'code']

// Add multiple items at once
todos.push('exercise', 'read book');
console.log(todos); // ['buy milk', 'walk dog', 'code', 'exercise', 'read book']

pop() - remove from the end

The pop() method removes and returns the last element. If the array is empty, it returns undefined:

const stack = [1, 2, 3, 4];
const removed = stack.pop();
console.log(removed);  // 4
console.log(stack);    // [1, 2, 3]

// Pop from empty array
const empty = [];
console.log(empty.pop()); // undefined

These methods work like a stack data structure (Last In, First Out). They're commonly used in algorithms, undo/redo functionality, and managing state in applications.

<aside> ⚠️

Both push() and pop() modify the original array. They don't create a new array, instead they change the existing one in place. Be mindful of this when using these methods.

</aside>

Searching in arrays

indexOf() - find position

Returns the first index where an element is found, or -1 if not found. Uses strict equality (===) for comparison:

const pets = ['cat', 'dog', 'rabbit', 'dog'];

console.log(pets.indexOf('dog'));     // 1 (first occurrence)
console.log(pets.indexOf('hamster')); // -1 (not found)
console.log(pets.indexOf('dog', 2));  // 3 (start search from index 2)

// Checking if element exists
if (pets.indexOf('cat') !== -1) {
  console.log('We have a cat!');
}

The optional second parameter specifies where to start searching. This is useful when looking for multiple occurrences.

<aside> 💡

indexOf() uses strict equality, so [1, 2, 3].indexOf('2') returns -1 because the string '2' is not strictly equal to the number 2.

</aside>

includes() - check existence

Returns true if element exists, false otherwise. Also uses strict equality and is more readable when you only need a boolean result:

const cart = ['shoes', 'shirt', 'hat'];

console.log(cart.includes('shoes'));  // true
console.log(cart.includes('pants'));  // false

// Use in conditionals (cleaner than indexOf)
if (cart.includes('shirt')) {
  console.log('Shirt is in cart');
}

// Optional start position
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(3, 3));  // false (starts searching from index 3)

<aside> ⌨️

Create an array of programming languages you want to learn. Use includes() to check if 'JavaScript' is in the list, and indexOf() to find its position.

</aside>

When to use which:

Extracting portions with slice()

The slice() method creates a new array containing a copy of a portion of the original array. It does not modify the original array, making it a "non-mutating" method.

const letters = ['a', 'b', 'c', 'd', 'e'];

// Extract from index 1 up to (but not including) index 3
console.log(letters.slice(1, 3));   // ['b', 'c']

// Extract from index 2 to end
console.log(letters.slice(2));      // ['c', 'd', 'e']

// Extract last 2 items using negative index
console.log(letters.slice(-2));     // ['d', 'e']

// Extract from index 1 to second-to-last
console.log(letters.slice(1, -1));  // ['b', 'c', 'd']

// Original array unchanged
console.log(letters);               // ['a', 'b', 'c', 'd', 'e']

// Create a copy of entire array
const copy = letters.slice();
console.log(copy);                  // ['a', 'b', 'c', 'd', 'e']

The syntax is array.slice(start, end) where:

<aside> 💡

slice() is incredibly useful for pagination, creating "undo" functionality, or working with subsets of data without affecting your original array.

</aside>

Common use cases

// Pagination - show 10 items per page
const allItems = [...Array(100).keys()]; // [0, 1, 2, ..., 99]
const page = 2;
const itemsPerPage = 10;
const pageItems = allItems.slice(page * itemsPerPage, (page + 1) * itemsPerPage);

// Get all items except first and last
const data = [1, 2, 3, 4, 5];
const middle = data.slice(1, -1); // [2, 3, 4]

<aside> ⚠️

Don't confuse slice() with splice(). slice() creates a new array and doesn't modify the original, while splice() modifies the original array by adding or removing elements.

</aside>

Summary

Method Purpose Modifies Original? Returns
push(item) Add to end Yes New length
pop() Remove from end Yes Removed item
indexOf(item) Find position No Index or -1
includes(item) Check existence No true/false
slice(start, end) Extract portion No New array
array[index] Access element No Value at index
array.length Get size/length of total items No Number of items

<aside> 🎉

</aside>

Additional resources

Videos

Reading