9. Arrays and Array Methods in JavaScript
What Are Arrays?
Arrays are ordered collections that let you store multiple values in a single variable. They’re great for lists, collections, and sequences of data.
const fruits = ["apple", "banana", "mango"];
console.log(fruits[0]); // "apple"Each item in an array has an index (a position), starting from **0**. In the example above, `fruits[0]` is the first item.
Adding and Removing Items
You can use built-in methods like `push()`, `pop()`, `unshift()`, and `shift()` to modify arrays.
const colors = ["red", "green"];
colors.push("blue"); // Add to end
colors.unshift("yellow"); // Add to start
colors.pop(); // Remove last
colors.shift(); // Remove first
console.log(colors);Looping Through Arrays
You can loop through arrays using `for`, `for...of`, or modern array methods like `.forEach()`.
const scores = [95, 88, 72];
scores.forEach(score => {
console.log("Score:", score);
});The `.map()` Method
`map()` creates a new array by applying a function to every item in the original array.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]The `.filter()` Method
`filter()` returns a new array containing only items that match a certain condition.
const ages = [12, 18, 20, 15, 30];
const adults = ages.filter(age => age >= 18);
console.log(adults); // [18, 20, 30]The `.reduce()` Method
`reduce()` takes all items in an array and combines them into a single value, often for totals or summaries.
const prices = [10, 20, 30];
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total); // 60Combining Methods
You can chain array methods together for powerful data transformations.
const nums = [1, 2, 3, 4, 5, 6];
const result = nums.filter(n => n % 2 === 0).map(n => n * 10);
console.log(result); // [20, 40, 60]Mini Challenge
Create an array of numbers and use `.filter()` to keep only even numbers, then use `.map()` to double them. Log the final array.
// Example:
const numbers = [3, 7, 8, 10, 15, 22];
const evensDoubled = numbers.filter(n => n % 2 === 0).map(n => n * 2);
console.log(evensDoubled); // [16, 20, 44]Key Takeaway
Arrays make it easy to store and process collections of data. With methods like `.map()`, `.filter()`, and `.reduce()`, you can transform data efficiently and write cleaner, modern JavaScript.