Episode 27 of 46

JavaScript Arrays & How They Work

Learn how to create, access, and manipulate arrays in JavaScript.

An array is an ordered list of values. Arrays are one of the most important data structures in JavaScript.

Creating Arrays

let fruits = ["apple", "banana", "cherry"];
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, "hello", true, null];
let empty = [];

Accessing Elements

let colors = ["red", "green", "blue"];

colors[0];          // "red" (first element)
colors[1];          // "green"
colors[2];          // "blue"
colors.length;      // 3
colors[colors.length - 1];  // "blue" (last element)

Modifying Arrays

let arr = ["a", "b", "c"];

// Change an element
arr[1] = "B";       // ["a", "B", "c"]

// Add to end
arr.push("d");      // ["a", "B", "c", "d"]

// Remove from end
arr.pop();          // ["a", "B", "c"]

// Add to beginning
arr.unshift("z");   // ["z", "a", "B", "c"]

// Remove from beginning
arr.shift();        // ["a", "B", "c"]

Useful Array Methods

let nums = [3, 1, 4, 1, 5, 9, 2, 6];

nums.sort();                // [1, 1, 2, 3, 4, 5, 6, 9]
nums.reverse();             // [9, 6, 5, 4, 3, 2, 1, 1]
nums.includes(5);           // true
nums.indexOf(4);            // 3
nums.splice(2, 1);          // Remove 1 item at index 2
nums.slice(1, 4);           // Extract elements 1-3

let joined = nums.join(", "); // "9, 6, 4, 3, 2, 1, 1"

Looping Through Arrays

let fruits = ["apple", "banana", "cherry"];

// forEach
fruits.forEach(function(fruit, index) {
    console.log(`${index}: ${fruit}`);
});

// for...of
for (let fruit of fruits) {
    console.log(fruit);
}