Arrays are a fundamental part of JavaScript, allowing you to store and manipulate collections of data. Whether you’re managing a shopping list, processing API responses, or building complex algorithms, arrays are your go-to tool. Here’s everything you need to know—in just 30 seconds!
What is an Array?
An array is a special variable in JavaScript that can hold more than one value. Each value is called an element, and every element has an index, starting from 0
.
const fruits = ["apple", "banana", "cherry"];
// Indexes: 0 1 2
Creating an Array
You can create arrays using square brackets:
const numbers = [1, 2, 3, 4, 5];
Or the Array
constructor:
const colors = new Array("red", "green", "blue");
Accessing Elements
Use the index to access elements:
console.log(fruits[0]); // Output: apple
Adding and Removing Elements
- Add to the end:
push
- Remove from the end:
pop
- Add to the beginning:
unshift
- Remove from the beginning:
shift
const fruits = ["apple", "banana"];
fruits.push("cherry"); // ["apple", "banana", "cherry"]
fruits.pop(); // ["apple", "banana"]
Common Methods
Here are some useful array methods:
forEach
Loops through each element:
fruits.forEach(fruit => console.log(fruit));
map
Creates a new array by transforming each element:
const upperCaseFruits = fruits.map(fruit => fruit.toUpperCase());
filter
Creates a new array with elements that pass a test:
const longFruits = fruits.filter(fruit => fruit.length > 5);
reduce
Reduces an array to a single value:
const total = [1, 2, 3, 4].reduce((sum, num) => sum + num, 0);
find
Finds the first element that matches a condition:
const cherry = fruits.find(fruit => fruit === "cherry");
includes
Checks if an array contains a specific value:
const hasApple = fruits.includes("apple");
Spread Operator
Easily copy or combine arrays:
const moreFruits = ["mango", ...fruits];
// ["mango", "apple", "banana"]
Conclusion
JavaScript arrays are versatile and powerful. With just a few methods and concepts, you can manage complex data structures with ease. Practice these examples, and you’ll be an array expert in no time!