Progress7 of 20 topics

35% complete

JavaScript Arrays

Arrays are one of the most versatile and commonly used data structures in JavaScript. They allow you to store multiple values in a single variable, making it easier to manage and manipulate collections of data.

Real-World Analogy

Think of an array like a bookshelf:

  • Each shelf position (index) can hold one book (value)
  • Books are arranged in a specific order, starting from the leftmost position (index 0)
  • You can add books, remove books, or rearrange them
  • You can count how many books you have (length property)
  • You can find a specific book by its position on the shelf (index)

Creating Arrays

There are several ways to create arrays in JavaScript.

JavaScript
1// Array literal notation (most common)
2let fruits = ["apple", "banana", "orange"];
3
4// Using the Array constructor
5let numbers = new Array(1, 2, 3, 4, 5);
6
7// Empty array
8let emptyArray = [];
9
10// Array with mixed data types
11let mixedArray = [42, "hello", true, null, { name: "John" }, [1, 2, 3]];
12
13// Creating an array with a specific length but no elements
14let newArray = new Array(5); // Creates an array with 5 empty slots
15console.log(newArray.length); // 5
16
17// Creating an array from an iterable
18let characters = Array.from("hello"); // ["h", "e", "l", "l", "o"]
19
20// Creating an array with Array.of()
21let digits = Array.of(1, 2, 3); // [1, 2, 3]

Accessing Array Elements

You can access individual elements in an array using bracket notation with the index position. Remember that array indices start at 0, not 1.

JavaScript
1// Accessing elements by index
2let colors = ["red", "green", "blue"];
3
4console.log(colors[0]); // "red"
5console.log(colors[1]); // "green"
6console.log(colors[2]); // "blue"
7
8// Trying to access an index that doesn't exist
9console.log(colors[3]); // undefined
10
11// Getting the last element
12let lastColor = colors[colors.length - 1]; // "blue"
13
14// Using at() method (ES2022) - supports negative indices
15console.log(colors.at(0)); // "red"
16console.log(colors.at(-1)); // "blue" (last element)
17console.log(colors.at(-2)); // "green" (second-to-last element)

Modifying Arrays

Unlike strings, arrays are mutable, which means you can change their content after creation.

JavaScript
1// Changing an element
2let pets = ["cat", "dog", "rabbit"];
3pets[1] = "hamster";
4console.log(pets); // ["cat", "hamster", "rabbit"]
5
6// Adding elements to the end
7pets[3] = "fish";
8console.log(pets); // ["cat", "hamster", "rabbit", "fish"]
9
10// Creating sparse arrays (not recommended)
11pets[6] = "bird";
12console.log(pets); // ["cat", "hamster", "rabbit", "fish", empty × 2, "bird"]
13console.log(pets.length); // 7
14
15// Changing the length
16pets.length = 3;
17console.log(pets); // ["cat", "hamster", "rabbit"] (truncated)

Important Note

While you can create "sparse" arrays with empty slots, it's generally not recommended as it can lead to confusing behavior. It's better to use explicit values like null or undefinedfor missing elements.

Basic Array Methods

JavaScript arrays come with many built-in methods that make it easier to work with them.

Adding and Removing Elements

JavaScript
1// push() - adds elements to the end of an array
2let stack = ["book1", "book2"];
3stack.push("book3");
4console.log(stack); // ["book1", "book2", "book3"]
5
6// pop() - removes and returns the last element
7let lastBook = stack.pop();
8console.log(lastBook); // "book3"
9console.log(stack); // ["book1", "book2"]
10
11// unshift() - adds elements to the beginning
12let queue = ["person1", "person2"];
13queue.unshift("person0");
14console.log(queue); // ["person0", "person1", "person2"]
15
16// shift() - removes and returns the first element
17let firstPerson = queue.shift();
18console.log(firstPerson); // "person0"
19console.log(queue); // ["person1", "person2"]
20
21// splice() - adds/removes elements from any position
22let months = ["Jan", "March", "April", "June"];
23months.splice(1, 0, "Feb"); // Insert at index 1, delete 0 elements
24console.log(months); // ["Jan", "Feb", "March", "April", "June"]
25
26months.splice(4, 1, "May"); // Replace 1 element at index 4
27console.log(months); // ["Jan", "Feb", "March", "April", "May"]
28
29let removed = months.splice(2, 2); // Remove 2 elements starting at index 2
30console.log(removed); // ["March", "April"]
31console.log(months); // ["Jan", "Feb", "May"]

Stack Operations

A stack is a Last-In-First-Out (LIFO) data structure. You can implement it using arrays:

JavaScript
// Stack operations
let stack = [];
stack.push("A"); // Add to top
stack.push("B"); // Add to top
stack.push("C"); // Add to top
console.log(stack); // ["A", "B", "C"]
let top = stack.pop(); // Remove from top
console.log(top); // "C"
console.log(stack); // ["A", "B"]

Queue Operations

A queue is a First-In-First-Out (FIFO) data structure. You can implement it using arrays:

JavaScript
// Queue operations
let queue = [];
queue.push("A"); // Add to end
queue.push("B"); // Add to end
queue.push("C"); // Add to end
console.log(queue); // ["A", "B", "C"]
let first = queue.shift(); // Remove from front
console.log(first); // "A"
console.log(queue); // ["B", "C"]

Finding and Searching

JavaScript
1// indexOf() - finds the first index of an element
2let fruits = ["apple", "banana", "orange", "apple", "mango"];
3console.log(fruits.indexOf("apple")); // 0
4console.log(fruits.indexOf("apple", 1)); // 3 (start searching from index 1)
5console.log(fruits.indexOf("pineapple")); // -1 (not found)
6
7// lastIndexOf() - finds the last index of an element
8console.log(fruits.lastIndexOf("apple")); // 3
9
10// includes() - checks if an array contains an element
11console.log(fruits.includes("banana")); // true
12console.log(fruits.includes("grape")); // false
13
14// find() - returns the first element that satisfies a condition
15let numbers = [5, 12, 8, 130, 44];
16let found = numbers.find(num => num > 10);
17console.log(found); // 12
18
19// findIndex() - returns the index of the first element that satisfies a condition
20let foundIndex = numbers.findIndex(num => num > 10);
21console.log(foundIndex); // 1
22
23// findLast() and findLastIndex() (ES2023)
24let lastLarge = numbers.findLast(num => num > 10);
25console.log(lastLarge); // 44
26
27let lastLargeIndex = numbers.findLastIndex(num => num > 10);
28console.log(lastLargeIndex); // 4

Transforming Arrays

JavaScript
1// slice() - returns a shallow copy of a portion of an array
2let animals = ["ant", "bison", "camel", "duck", "elephant"];
3console.log(animals.slice(2)); // ["camel", "duck", "elephant"]
4console.log(animals.slice(2, 4)); // ["camel", "duck"]
5console.log(animals.slice(-2)); // ["duck", "elephant"]
6console.log(animals); // Original array is unchanged
7
8// concat() - merges two or more arrays
9let moreAnimals = ["fox", "giraffe"];
10let allAnimals = animals.concat(moreAnimals);
11console.log(allAnimals); // ["ant", "bison", "camel", "duck", "elephant", "fox", "giraffe"]
12
13// reverse() - reverses an array in place
14let letters = ["a", "b", "c"];
15letters.reverse();
16console.log(letters); // ["c", "b", "a"]
17
18// join() - joins all elements into a string
19let joined = letters.join("-");
20console.log(joined); // "c-b-a"
21
22// flat() - flattens nested arrays
23let nestedArray = [1, 2, [3, 4, [5, 6]]];
24console.log(nestedArray.flat()); // [1, 2, 3, 4, [5, 6]]
25console.log(nestedArray.flat(2)); // [1, 2, 3, 4, 5, 6]
26console.log(nestedArray.flat(Infinity)); // [1, 2, 3, 4, 5, 6]

Iterating Over Arrays

There are multiple ways to loop through arrays in JavaScript.

JavaScript
1// Using for loop
2let colors = ["red", "green", "blue"];
3
4for (let i = 0; i < colors.length; i++) {
5 console.log(`Color at index ${i} is ${colors[i]}`);
6}
7
8// Using for...of loop (ES6)
9for (let color of colors) {
10 console.log(`Color: ${color}`);
11}
12
13// Using forEach method
14colors.forEach((color, index) => {
15 console.log(`Color at index ${index} is ${color}`);
16});
17
18// Using map to create a new array
19let uppercaseColors = colors.map(color => color.toUpperCase());
20console.log(uppercaseColors); // ["RED", "GREEN", "BLUE"]
21
22// Using filter to create a subset
23let longColors = colors.filter(color => color.length > 3);
24console.log(longColors); // ["green", "blue"]
25
26// Using reduce to calculate a single value
27let totalLength = colors.reduce((sum, color) => sum + color.length, 0);
28console.log(totalLength); // 11 (3 + 5 + 4)
29
30// Using every to check if all elements satisfy a condition
31let allLongerThan2 = colors.every(color => color.length > 2);
32console.log(allLongerThan2); // true
33
34// Using some to check if at least one element satisfies a condition
35let anyStartsWithB = colors.some(color => color.startsWith("b"));
36console.log(anyStartsWithB); // true

Array Destructuring

Array destructuring is a convenient way to extract values from arrays and assign them to variables.

JavaScript
1// Basic destructuring
2let [first, second, third] = ["red", "green", "blue"];
3console.log(first); // "red"
4console.log(second); // "green"
5console.log(third); // "blue"
6
7// Skipping elements
8let [primary, , tertiary] = ["red", "green", "blue"];
9console.log(primary); // "red"
10console.log(tertiary); // "blue"
11
12// Rest pattern
13let [head, ...tail] = [1, 2, 3, 4, 5];
14console.log(head); // 1
15console.log(tail); // [2, 3, 4, 5]
16
17// Default values
18let [a, b, c = "default"] = [10, 20];
19console.log(a); // 10
20console.log(b); // 20
21console.log(c); // "default"
22
23// Swapping variables
24let x = 1;
25let y = 2;
26[x, y] = [y, x];
27console.log(x); // 2
28console.log(y); // 1
29
30// Nested destructuring
31let nested = [1, [2, 3], 4];
32let [first2, [second2, third2], fourth] = nested;
33console.log(second2); // 2
34console.log(third2); // 3

Spread Operator

The spread operator (...) allows you to expand an array into individual elements.

JavaScript
1// Copying an array
2let original = [1, 2, 3];
3let copy = [...original];
4console.log(copy); // [1, 2, 3]
5
6// Merging arrays
7let arr1 = [1, 2, 3];
8let arr2 = [4, 5, 6];
9let merged = [...arr1, ...arr2];
10console.log(merged); // [1, 2, 3, 4, 5, 6]
11
12// Using spread with push
13let numbers = [1, 2];
14numbers.push(...[3, 4, 5]);
15console.log(numbers); // [1, 2, 3, 4, 5]
16
17// Creating a new array with additional elements
18let baseColors = ["red", "green", "blue"];
19let extendedColors = ["yellow", ...baseColors, "purple"];
20console.log(extendedColors); // ["yellow", "red", "green", "blue", "purple"]
21
22// Converting string to array of characters
23let chars = [..."hello"];
24console.log(chars); // ["h", "e", "l", "l", "o"]
25
26// Finding min/max value
27let values = [23, 5, 97, 42, 8];
28console.log(Math.min(...values)); // 5
29console.log(Math.max(...values)); // 97

Multi-dimensional Arrays

Arrays can contain other arrays, creating multi-dimensional arrays.

JavaScript
1// Creating a 2D array (matrix)
2let matrix = [
3 [1, 2, 3],
4 [4, 5, 6],
5 [7, 8, 9]
6];
7
8// Accessing elements
9console.log(matrix[0][0]); // 1 (first row, first column)
10console.log(matrix[1][2]); // 6 (second row, third column)
11
12// Iterating over a 2D array
13for (let i = 0; i < matrix.length; i++) {
14 for (let j = 0; j < matrix[i].length; j++) {
15 console.log(`Element at position [${i}][${j}] is ${matrix[i][j]}`);
16 }
17}
18
19// Using forEach with 2D arrays
20matrix.forEach((row, i) => {
21 row.forEach((value, j) => {
22 console.log(`Element at position [${i}][${j}] is ${value}`);
23 });
24});
25
26// Flattening a 2D array
27let flattened = matrix.flat();
28console.log(flattened); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

Array Methods Chaining

Many array methods return arrays, allowing you to chain multiple operations together.

JavaScript
1// Example: Processing a list of products
2let products = [
3 { id: 1, name: "Laptop", price: 1200, inStock: true },
4 { id: 2, name: "Phone", price: 800, inStock: true },
5 { id: 3, name: "Tablet", price: 500, inStock: false },
6 { id: 4, name: "Headphones", price: 150, inStock: true },
7 { id: 5, name: "Keyboard", price: 100, inStock: false }
8];
9
10// Find available products, sort by price, and get their names
11let availableProductNames = products
12 .filter(product => product.inStock)
13 .sort((a, b) => a.price - b.price)
14 .map(product => product.name);
15
16console.log(availableProductNames); // ["Headphones", "Phone", "Laptop"]
17
18// Calculate total value of in-stock inventory
19let totalInventoryValue = products
20 .filter(product => product.inStock)
21 .reduce((total, product) => total + product.price, 0);
22
23console.log(totalInventoryValue); // 2150

Practice Exercises

Try these exercises to reinforce your understanding of JavaScript arrays:

JavaScript
// 1. Create a function that takes an array of numbers and returns the sum of all
// positive numbers in the array
// 2. Create a function that removes all duplicate values from an array
// 3. Create a function that merges two sorted arrays into one sorted array
// 4. Create a function that finds the second largest number in an array
// 5. Create a function that rotates an array by k positions
// Example: rotate([1, 2, 3, 4, 5], 2) → [4, 5, 1, 2, 3]

Summary

In this tutorial, you've learned:

  • How to create and access arrays
  • How to modify arrays by adding, removing, and changing elements
  • How to use common array methods for searching, transforming, and iterating
  • How to use array destructuring and the spread operator
  • How to work with multi-dimensional arrays
  • How to chain array methods for complex data processing

Arrays are a fundamental part of JavaScript programming, and mastering them is essential for effective data manipulation. In the next tutorial, you'll learn about objects, another important data structure in JavaScript.

Related Tutorials

Learn how to create and use functions in JavaScript.

Learn more

Learn about string manipulation in JavaScript.

Learn more

Learn about objects and how to work with key-value pairs.

Learn more