learn2code

Back to Blog

JavaScript

15 min read

The 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.

code.js
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:

code.js
1// Array literal (most common)
2const colors = ['red', 'green', 'blue'];
3 
4// Empty array
5const empty = [];
6 
7// Array with mixed types
8const mixed = [1, 'hello', true, null];
9 
10// Array constructor (less common)
11const numbers = new Array(1, 2, 3);
12 
13// Array.from() - create from iterable
14const chars = Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
15 
16// Array.of() - create from arguments
17const 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

code.js
1const stack = [];
2 
3// Add to end
4stack.push('first');
5stack.push('second');
6console.log(stack); // ['first', 'second']
7 
8// Remove from end
9const last = stack.pop();
10console.log(last); // 'second'
11console.log(stack); // ['first']
12 
13// Add to beginning
14stack.unshift('zero');
15console.log(stack); // ['zero', 'first']
16 
17// Remove from beginning
18const first = stack.shift();
19console.log(first); // 'zero'

Slice vs Splice

This is a common source of confusion. Here is the difference:

slice() - Safe

code.js
1// slice() - NON-DESTRUCTIVE
2// Returns a new array, original unchanged
3const 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

code.js
1// splice() - DESTRUCTIVE
2// Modifies the original array
3const 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:

1

map() - Transform each element

Creates a new array by applying a function to every element.

2

filter() - Keep matching elements

Creates a new array with only elements that pass a test.

3

reduce() - Combine into single value

Reduces an array to a single value by accumulating results.

map() - Transform Data

code.js
1const numbers = [1, 2, 3, 4, 5];
2 
3// Double each number
4const doubled = numbers.map(num => num * 2);
5console.log(doubled); // [2, 4, 6, 8, 10]
6 
7// Extract property from objects
8const 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

code.js
1const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2 
3// Keep only even numbers
4const evens = numbers.filter(num => num % 2 === 0);
5console.log(evens); // [2, 4, 6, 8, 10]
6 
7// Filter objects by property
8const 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

code.js
1const numbers = [1, 2, 3, 4, 5];
2 
3// Sum all numbers
4const sum = numbers.reduce((total, num) => total + num, 0);
5console.log(sum); // 15
6 
7// Find maximum
8const max = numbers.reduce((max, num) => num > max ? num : max, numbers[0]);
9console.log(max); // 5
10 
11// Group by property
12const 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

code.js
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 = transactions
11.filter(t => t.type === 'sale') // Keep only sales
12.map(t => t.amount) // Extract amounts
13.reduce((sum, amt) => sum + amt, 0); // Sum them up
14 
15console.log(totalSales); // 350

What does the following code return? [1, 2, 3, 4].filter(n => n % 2 === 0)

A[2, 4]
B[1, 2, 3, 4]
C[4, 8]
D[2, 4, 6, 8]
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

  1. Use const for arrays - you can still modify contents
  2. Prefer non-mutating methods like map, filter, slice
  3. Chain methods for complex transformations
  4. Use find for single items, filter for multiple
  5. Use reduce for aggregations and complex transformations

Practice Array Methods

Master map, filter, and reduce with interactive exercises