60 Mins intermediate
8. Arrays & Array Methods
Data Structures
Arrays
An array is an ordered list of items stored in a single variable. Arrays in JavaScript are incredibly powerful because they come with built-in "methods" that allow you to transform and filter data instantly.
๐ Basic Array Access
Arrays are zero-indexed, meaning the first item is at position 0.
const servers = ["Web", "Database", "Cache"];
console.log(servers[0]);
console.log(servers.length);
// Add to the end
servers.push("Proxy");
// Remove from the end
const removed = servers.pop();
console.log(servers);
OutputWeb
3
[ 'Web', 'Database', 'Cache' ]
3
[ 'Web', 'Database', 'Cache' ]
๐ Array.forEach()
The modern way to loop through an array instead of using a clunky for loop.
const users = ["Alice", "Bob", "Charlie"];
users.forEach(user => {
console.log("Deploying update to:", user);
});
OutputDeploying update to: Alice
Deploying update to: Bob
Deploying update to: Charlie
Deploying update to: Bob
Deploying update to: Charlie
๐ The Holy Trinity: Map, Filter, Reduce
These three methods are the foundation of modern JavaScript engineering (especially in frameworks like React).
map(): Transforms every item and returns a new array.filter(): Returns a new array containing only items that pass a test.reduce(): Boils the entire array down into a single value.
const prices = [10, 15, 20, 25];
// Map: Add 5 to every price
const inflated = prices.map(p => p + 5);
// Filter: Keep only prices greater than 15
const expensive = prices.filter(p => p > 15);
// Reduce: Sum them all together
const total = prices.reduce((sum, p) => sum + p, 0);
console.log("Map:", inflated);
console.log("Filter:", expensive);
console.log("Reduce:", total);
OutputMap: [ 15, 20, 25, 30 ]
Filter: [ 20, 25 ]
Reduce: 70
Filter: [ 20, 25 ]
Reduce: 70
Knowledge Check
Ready to test your understanding of 8. Arrays & Array Methods?