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.
1// Array literal notation (most common)2let fruits = ["apple", "banana", "orange"];34// Using the Array constructor5let numbers = new Array(1, 2, 3, 4, 5);67// Empty array8let emptyArray = [];910// Array with mixed data types11let mixedArray = [42, "hello", true, null, { name: "John" }, [1, 2, 3]];1213// Creating an array with a specific length but no elements14let newArray = new Array(5); // Creates an array with 5 empty slots15console.log(newArray.length); // 51617// Creating an array from an iterable18let characters = Array.from("hello"); // ["h", "e", "l", "l", "o"]1920// 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.
1// Accessing elements by index2let colors = ["red", "green", "blue"];34console.log(colors[0]); // "red"5console.log(colors[1]); // "green"6console.log(colors[2]); // "blue"78// Trying to access an index that doesn't exist9console.log(colors[3]); // undefined1011// Getting the last element12let lastColor = colors[colors.length - 1]; // "blue"1314// Using at() method (ES2022) - supports negative indices15console.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.
1// Changing an element2let pets = ["cat", "dog", "rabbit"];3pets[1] = "hamster";4console.log(pets); // ["cat", "hamster", "rabbit"]56// Adding elements to the end7pets[3] = "fish";8console.log(pets); // ["cat", "hamster", "rabbit", "fish"]910// Creating sparse arrays (not recommended)11pets[6] = "bird";12console.log(pets); // ["cat", "hamster", "rabbit", "fish", empty × 2, "bird"]13console.log(pets.length); // 71415// Changing the length16pets.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 undefined
for 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
1// push() - adds elements to the end of an array2let stack = ["book1", "book2"];3stack.push("book3");4console.log(stack); // ["book1", "book2", "book3"]56// pop() - removes and returns the last element7let lastBook = stack.pop();8console.log(lastBook); // "book3"9console.log(stack); // ["book1", "book2"]1011// unshift() - adds elements to the beginning12let queue = ["person1", "person2"];13queue.unshift("person0");14console.log(queue); // ["person0", "person1", "person2"]1516// shift() - removes and returns the first element17let firstPerson = queue.shift();18console.log(firstPerson); // "person0"19console.log(queue); // ["person1", "person2"]2021// splice() - adds/removes elements from any position22let months = ["Jan", "March", "April", "June"];23months.splice(1, 0, "Feb"); // Insert at index 1, delete 0 elements24console.log(months); // ["Jan", "Feb", "March", "April", "June"]2526months.splice(4, 1, "May"); // Replace 1 element at index 427console.log(months); // ["Jan", "Feb", "March", "April", "May"]2829let removed = months.splice(2, 2); // Remove 2 elements starting at index 230console.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:
// Stack operationslet stack = [];stack.push("A"); // Add to topstack.push("B"); // Add to topstack.push("C"); // Add to topconsole.log(stack); // ["A", "B", "C"]let top = stack.pop(); // Remove from topconsole.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:
// Queue operationslet queue = [];queue.push("A"); // Add to endqueue.push("B"); // Add to endqueue.push("C"); // Add to endconsole.log(queue); // ["A", "B", "C"]let first = queue.shift(); // Remove from frontconsole.log(first); // "A"console.log(queue); // ["B", "C"]
Finding and Searching
1// indexOf() - finds the first index of an element2let fruits = ["apple", "banana", "orange", "apple", "mango"];3console.log(fruits.indexOf("apple")); // 04console.log(fruits.indexOf("apple", 1)); // 3 (start searching from index 1)5console.log(fruits.indexOf("pineapple")); // -1 (not found)67// lastIndexOf() - finds the last index of an element8console.log(fruits.lastIndexOf("apple")); // 3910// includes() - checks if an array contains an element11console.log(fruits.includes("banana")); // true12console.log(fruits.includes("grape")); // false1314// find() - returns the first element that satisfies a condition15let numbers = [5, 12, 8, 130, 44];16let found = numbers.find(num => num > 10);17console.log(found); // 121819// findIndex() - returns the index of the first element that satisfies a condition20let foundIndex = numbers.findIndex(num => num > 10);21console.log(foundIndex); // 12223// findLast() and findLastIndex() (ES2023)24let lastLarge = numbers.findLast(num => num > 10);25console.log(lastLarge); // 442627let lastLargeIndex = numbers.findLastIndex(num => num > 10);28console.log(lastLargeIndex); // 4
Transforming Arrays
1// slice() - returns a shallow copy of a portion of an array2let 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 unchanged78// concat() - merges two or more arrays9let moreAnimals = ["fox", "giraffe"];10let allAnimals = animals.concat(moreAnimals);11console.log(allAnimals); // ["ant", "bison", "camel", "duck", "elephant", "fox", "giraffe"]1213// reverse() - reverses an array in place14let letters = ["a", "b", "c"];15letters.reverse();16console.log(letters); // ["c", "b", "a"]1718// join() - joins all elements into a string19let joined = letters.join("-");20console.log(joined); // "c-b-a"2122// flat() - flattens nested arrays23let 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.
1// Using for loop2let colors = ["red", "green", "blue"];34for (let i = 0; i < colors.length; i++) {5 console.log(`Color at index ${i} is ${colors[i]}`);6}78// Using for...of loop (ES6)9for (let color of colors) {10 console.log(`Color: ${color}`);11}1213// Using forEach method14colors.forEach((color, index) => {15 console.log(`Color at index ${index} is ${color}`);16});1718// Using map to create a new array19let uppercaseColors = colors.map(color => color.toUpperCase());20console.log(uppercaseColors); // ["RED", "GREEN", "BLUE"]2122// Using filter to create a subset23let longColors = colors.filter(color => color.length > 3);24console.log(longColors); // ["green", "blue"]2526// Using reduce to calculate a single value27let totalLength = colors.reduce((sum, color) => sum + color.length, 0);28console.log(totalLength); // 11 (3 + 5 + 4)2930// Using every to check if all elements satisfy a condition31let allLongerThan2 = colors.every(color => color.length > 2);32console.log(allLongerThan2); // true3334// Using some to check if at least one element satisfies a condition35let 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.
1// Basic destructuring2let [first, second, third] = ["red", "green", "blue"];3console.log(first); // "red"4console.log(second); // "green"5console.log(third); // "blue"67// Skipping elements8let [primary, , tertiary] = ["red", "green", "blue"];9console.log(primary); // "red"10console.log(tertiary); // "blue"1112// Rest pattern13let [head, ...tail] = [1, 2, 3, 4, 5];14console.log(head); // 115console.log(tail); // [2, 3, 4, 5]1617// Default values18let [a, b, c = "default"] = [10, 20];19console.log(a); // 1020console.log(b); // 2021console.log(c); // "default"2223// Swapping variables24let x = 1;25let y = 2;26[x, y] = [y, x];27console.log(x); // 228console.log(y); // 12930// Nested destructuring31let nested = [1, [2, 3], 4];32let [first2, [second2, third2], fourth] = nested;33console.log(second2); // 234console.log(third2); // 3
Spread Operator
The spread operator (...
) allows you to expand an array into individual elements.
1// Copying an array2let original = [1, 2, 3];3let copy = [...original];4console.log(copy); // [1, 2, 3]56// Merging arrays7let arr1 = [1, 2, 3];8let arr2 = [4, 5, 6];9let merged = [...arr1, ...arr2];10console.log(merged); // [1, 2, 3, 4, 5, 6]1112// Using spread with push13let numbers = [1, 2];14numbers.push(...[3, 4, 5]);15console.log(numbers); // [1, 2, 3, 4, 5]1617// Creating a new array with additional elements18let baseColors = ["red", "green", "blue"];19let extendedColors = ["yellow", ...baseColors, "purple"];20console.log(extendedColors); // ["yellow", "red", "green", "blue", "purple"]2122// Converting string to array of characters23let chars = [..."hello"];24console.log(chars); // ["h", "e", "l", "l", "o"]2526// Finding min/max value27let values = [23, 5, 97, 42, 8];28console.log(Math.min(...values)); // 529console.log(Math.max(...values)); // 97
Multi-dimensional Arrays
Arrays can contain other arrays, creating multi-dimensional arrays.
1// Creating a 2D array (matrix)2let matrix = [3 [1, 2, 3],4 [4, 5, 6],5 [7, 8, 9]6];78// Accessing elements9console.log(matrix[0][0]); // 1 (first row, first column)10console.log(matrix[1][2]); // 6 (second row, third column)1112// Iterating over a 2D array13for (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}1819// Using forEach with 2D arrays20matrix.forEach((row, i) => {21 row.forEach((value, j) => {22 console.log(`Element at position [${i}][${j}] is ${value}`);23 });24});2526// Flattening a 2D array27let 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.
1// Example: Processing a list of products2let 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];910// Find available products, sort by price, and get their names11let availableProductNames = products12 .filter(product => product.inStock)13 .sort((a, b) => a.price - b.price)14 .map(product => product.name);1516console.log(availableProductNames); // ["Headphones", "Phone", "Laptop"]1718// Calculate total value of in-stock inventory19let totalInventoryValue = products20 .filter(product => product.inStock)21 .reduce((total, product) => total + product.price, 0);2223console.log(totalInventoryValue); // 2150
Practice Exercises
Try these exercises to reinforce your understanding of JavaScript arrays:
// 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 moreLearn about string manipulation in JavaScript.
Learn moreLearn about objects and how to work with key-value pairs.
Learn more