Arrays and Array Methods in JavaScript
JavaScript arrays are one of the most powerful and commonly used data structures. They allow you to store and manipulate collections of values in an efficient and flexible way.
What are Arrays in JavaScript?
- An array is an ordered list of values (called elements), which can be of any data type (numbers, strings, objects, even other arrays).
- Arrays in JavaScript are zero-indexed, meaning the first element has an index of 0.
How to Create an Array:
// Method 1: Using Array Literal (Most Common)
const fruits = ["Apple", "Banana", "Cherry"];
// Method 2: Using Array Constructor
const numbers = new Array(1, 2, 3, 4, 5);
// Method 3: Creating an Empty Array
const emptyArray = [];
Accessing and Modifying Array Elements
- Use indexing to access array elements.
- Use assignment to modify elements.
Example:
const colors = ["Red", "Green", "Blue"];
console.log(colors[0]); // Output: Red (Accessing)
colors[1] = "Yellow"; // Modifying
console.log(colors); // Output: ["Red", "Yellow", "Blue"]
Key Points:
- Indexing starts at 0.
- If you access an index that does not exist, you get undefined.
- Arrays are mutable, meaning you can change their contents.
Array Properties
- length: Returns the number of elements in an array.
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.length); // Output: 5
- Sparse Arrays: If you skip indexes, they will be undefined.
const sparseArray = [1, , 3];
console.log(sparseArray); // Output: [1, empty, 3]
console.log(sparseArray.length); // Output: 3
JavaScript Array Methods
JavaScript offers a wide range of built-in methods to work with arrays.
1. Adding Elements
- push() - Adds one or more elements to the end of an array.
- unshift() - Adds one or more elements to the beginning of an array.
const arr = [1, 2, 3];
arr.push(4); // Adds at the end
arr.unshift(0); // Adds at the beginning
console.log(arr); // Output: [0, 1, 2, 3, 4]
2. Removing Elements
- pop() - Removes the last element.
- shift() - Removes the first element.
const arr = [0, 1, 2, 3, 4];
arr.pop(); // Removes last
arr.shift(); // Removes first
console.log(arr); // Output: [1, 2, 3]
3. Accessing a Subsection
- slice(start, end) - Returns a shallow copy of a portion of an array without modifying the original.
- splice(start, deleteCount, items...) - Modifies the array directly.
const arr = [1, 2, 3, 4, 5];
console.log(arr.slice(1, 3)); // Output: [2, 3] (not affecting the original)
arr.splice(1, 2, "A", "B"); // Replaces 2 elements starting at index 1
console.log(arr); // Output: [1, "A", "B", 4, 5]
4. Searching in Arrays
- indexOf(item) - Returns the first index of the item.
- lastIndexOf(item) - Returns the last index of the item.
- includes(item) - Checks if the array contains the item.
const fruits = ["Apple", "Banana", "Cherry", "Apple"];
console.log(fruits.indexOf("Apple")); // Output: 0
console.log(fruits.lastIndexOf("Apple"));// Output: 3
console.log(fruits.includes("Banana")); // Output: true5. Transforming Arrays
- map() - Creates a new array by applying a function to each element.
- filter() - Creates a new array with elements that match a condition.
- reduce() - Reduces the array to a single value using a function.
const numbers = [1, 2, 3, 4, 5];
// Map - Multiplying each number by 2
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]
// Filter - Keeping only even numbers
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // Output: [2, 4]
// Reduce - Summing all numbers
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 15
6. Iterating Over Arrays
- forEach() - Calls a function for each element.
- map() - Creates a new array with the transformed values.
const names = ["Alice", "Bob", "Charlie"];
// Using forEach
names.forEach((name) => console.log(name));
// Using map (transforms each element)
const uppercased = names.map(name => name.toUpperCase());
console.log(uppercased); // Output: ["ALICE", "BOB", "CHARLIE"]
7. Sorting Arrays
- sort() - Sorts elements alphabetically by default (converts to strings).
- reverse() - Reverses the order of elements.
const numbers = [3, 1, 4, 2, 5];
numbers.sort(); // Output: [1, 2, 3, 4, 5]
numbers.reverse(); // Output: [5, 4, 3, 2, 1]
Custom Sorting:
const scores = [40, 100, 30, 80, 60];
scores.sort((a, b) => a - b); // Ascending
console.log(scores); // Output: [30, 40, 60, 80, 100]
Advanced Array Methods
- flat() - Flattens nested arrays.
- flatMap() - Maps and flattens the result.
- find() - Finds the first matching element.
- findIndex() - Finds the index of the first matching element.
- some() and every() - Check if some/all elements match a condition.
Best Practices with Arrays
- Use map(), filter(), and reduce() for clean, functional code.
- Prefer const for arrays that you do not intend to reassign.
- Use splice() carefully, as it modifies the original array.
- Avoid using sparse arrays (missing elements).
- Use Array.isArray() to check if a variable is an array.
Quick Recap
- Arrays are ordered lists of values, starting at index 0.
- JavaScript offers a wide range of methods for adding, removing, and transforming array elements.
- Advanced methods like map(), filter(), and reduce() are crucial for clean, efficient code.