JavaScript
15 min readThe Complete Guide to JavaScript Arrays
Master JavaScript arrays with this comprehensive guide. Learn array methods, iteration patterns, and best practices.
What is an Array?
An array is an ordered collection of values. Think of it like a numbered list where each item has a position (index) starting from 0.
1const fruits = ['apple', 'banana', 'orange'];2 3console.log(fruits[0]); // 'apple' (first item)4console.log(fruits[1]); // 'banana' (second item)5console.log(fruits.length); // 3 (total items)Zero-Based Indexing
Arrays in JavaScript (and most programming languages) start counting from 0, not 1. The first element is at index 0, the second at index 1, and so on.
Creating Arrays
There are several ways to create arrays in JavaScript:
1// Array literal (most common)2const colors = ['red', 'green', 'blue'];3 4// Empty array5const empty = [];6 7// Array with mixed types8const mixed = [1, 'hello', true, null];9 10// Array constructor (less common)11const numbers = new Array(1, 2, 3);12 13// Array.from() - create from iterable14const chars = Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']15 16// Array.of() - create from arguments17const items = Array.of(1, 2, 3); // [1, 2, 3]Best Practice
Always use array literals [] instead of new Array(). It is cleaner, faster, and avoids potential confusion with single numeric arguments.
Essential Array Methods
push() / pop()
Add or remove items from the end of an array
unshift() / shift()
Add or remove items from the beginning
slice() / splice()
Extract portions or modify array contents
concat()
Combine multiple arrays into one
indexOf() / includes()
Search for items in an array
reverse() / sort()
Change the order of elements
Adding and Removing Elements
1const stack = [];2 3// Add to end4stack.push('first');5stack.push('second');6console.log(stack); // ['first', 'second']7 8// Remove from end9const last = stack.pop();10console.log(last); // 'second'11console.log(stack); // ['first']12 13// Add to beginning14stack.unshift('zero');15console.log(stack); // ['zero', 'first']16 17// Remove from beginning18const first = stack.shift();19console.log(first); // 'zero'Slice vs Splice
This is a common source of confusion. Here is the difference:
slice() - Safe
1// slice() - NON-DESTRUCTIVE2// Returns a new array, original unchanged3const arr = [1, 2, 3, 4, 5];4const sliced = arr.slice(1, 4);5 6console.log(sliced); // [2, 3, 4]7console.log(arr); // [1, 2, 3, 4, 5]splice() - Mutates
1// splice() - DESTRUCTIVE2// Modifies the original array3const arr = [1, 2, 3, 4, 5];4const removed = arr.splice(1, 2);5 6console.log(removed); // [2, 3]7console.log(arr); // [1, 4, 5]Mutation Warning
splice() modifies the original array! If you need to keep the original intact, use slice() or the spread operator instead.
Iteration Methods
The "Big Three" array methods you will use constantly:
map() - Transform each element
Creates a new array by applying a function to every element.
filter() - Keep matching elements
Creates a new array with only elements that pass a test.
reduce() - Combine into single value
Reduces an array to a single value by accumulating results.
map() - Transform Data
1const numbers = [1, 2, 3, 4, 5];2 3// Double each number4const doubled = numbers.map(num => num * 2);5console.log(doubled); // [2, 4, 6, 8, 10]6 7// Extract property from objects8const users = [9{ name: 'Alice', age: 25 },10{ name: 'Bob', age: 30 },11];12const names = users.map(user => user.name);13console.log(names); // ['Alice', 'Bob']filter() - Select Data
1const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];2 3// Keep only even numbers4const evens = numbers.filter(num => num % 2 === 0);5console.log(evens); // [2, 4, 6, 8, 10]6 7// Filter objects by property8const products = [9{ name: 'Laptop', price: 999, inStock: true },10{ name: 'Phone', price: 699, inStock: false },11{ name: 'Tablet', price: 499, inStock: true },12];13 14const available = products.filter(p => p.inStock);15// [{ name: 'Laptop', ... }, { name: 'Tablet', ... }]reduce() - Aggregate Data
1const numbers = [1, 2, 3, 4, 5];2 3// Sum all numbers4const sum = numbers.reduce((total, num) => total + num, 0);5console.log(sum); // 156 7// Find maximum8const max = numbers.reduce((max, num) => num > max ? num : max, numbers[0]);9console.log(max); // 510 11// Group by property12const items = [13{ type: 'fruit', name: 'apple' },14{ type: 'vegetable', name: 'carrot' },15{ type: 'fruit', name: 'banana' },16];17 18const grouped = items.reduce((acc, item) => {19acc[item.type] = acc[item.type] || [];20acc[item.type].push(item.name);21return acc;22}, {});23// { fruit: ['apple', 'banana'], vegetable: ['carrot'] }Common Patterns
Chaining Methods
1const transactions = [2{ type: 'sale', amount: 100 },3{ type: 'refund', amount: -30 },4{ type: 'sale', amount: 200 },5{ type: 'sale', amount: 50 },6{ type: 'refund', amount: -20 },7];8 9// Get total of all sales (not refunds)10const totalSales = transactions11.filter(t => t.type === 'sale') // Keep only sales12.map(t => t.amount) // Extract amounts13.reduce((sum, amt) => sum + amt, 0); // Sum them up14 15console.log(totalSales); // 350What does the following code return? [1, 2, 3, 4].filter(n => n % 2 === 0)
Show Answer
Answer: A
filter() keeps only elements where the callback returns true. Only 2 and 4 are even numbers (divisible by 2 with no remainder).
Key Takeaways
- Use
constfor arrays - you can still modify contents - Prefer non-mutating methods like
map,filter,slice - Chain methods for complex transformations
- Use
findfor single items,filterfor multiple - Use
reducefor aggregations and complex transformations
Practice Array Methods
Master map, filter, and reduce with interactive exercises