JavaScript — Arrays
What are Arrays?
Arrays store multiple values in a single variable, indexed starting from 0:
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "cherry"
console.log(fruits.length); // 3
Creating Arrays
// Array literal (recommended)
const colors = ["red", "green", "blue"];
// Empty array
const empty = [];
// Array constructor (not recommended)
const numbers = new Array(1, 2, 3);
// From a string
const letters = Array.from("hello"); // ["h", "e", "l", "l", "o"]
Accessing Elements
const items = ["a", "b", "c", "d"];
items[0]; // "a" — first element
items[2]; // "c" — third element
items[-1]; // undefined — no negative indexing
items[10]; // undefined — out of bounds
Modifying Arrays
const fruits = ["apple", "banana"];
// Change an element
fruits[0] = "mango";
// Add to end
fruits.push("grape");
// Add to beginning
fruits.unshift("orange");
// Remove from end
fruits.pop();
// Remove from beginning
fruits.shift();
// Insert at index
fruits.splice(1, 0, "kiwi"); // insert at index 1
// Remove elements
fruits.splice(1, 2); // remove 2 elements starting at index 1
Array Methods
Iteration
const nums = [1, 2, 3, 4, 5];
// forEach — loop through each element
nums.forEach((num, index) => {
console.log(`${index}: ${num}`);
});
// map — transform each element
const doubled = nums.map(n => n * 2); // [2, 4, 6, 8, 10]
// filter — keep elements that pass a test
const evens = nums.filter(n => n % 2 === 0); // [2, 4]
// find — get first match
const first = nums.find(n => n > 3); // 4
// some — does any element pass?
nums.some(n => n > 4); // true
// every — do all elements pass?
nums.every(n => n > 0); // true
Searching
const fruits = ["apple", "banana", "cherry"];
fruits.includes("banana"); // true
fruits.indexOf("cherry"); // 2
fruits.lastIndexOf("apple"); // 0
fruits.find(f => f.length > 6); // "banana"
Sorting
const nums = [3, 1, 4, 1, 5, 9];
// Sort alphabetically (default)
["b", "a", "c"].sort(); // ["a", "b", "c"]
// Sort numbers (tricky!)
nums.sort(); // [1, 1, 3, 4, 5, 9] — works for small numbers
[10, 1, 21].sort(); // [1, 10, 21] — wrong! Lexicographic sort
// Correct number sort
nums.sort((a, b) => a - b); // ascending
nums.sort((a, b) => b - a); // descending
Transforming
const nums = [1, 2, 3, 4, 5];
// reduce — accumulate into single value
const sum = nums.reduce((total, n) => total + n, 0); // 15
// flat — flatten nested arrays
[[1, 2], [3, 4]].flat(); // [1, 2, 3, 4]
// join — combine into string
["a", "b", "c"].join("-"); // "a-b-c"
// slice — extract portion (doesn't modify original)
nums.slice(1, 3); // [2, 3]
// concat — merge arrays
[1, 2].concat([3, 4]); // [1, 2, 3, 4]
Destructuring
const fruits = ["apple", "banana", "cherry"];
const [first, second, third] = fruits;
// first = "apple", second = "banana", third = "cherry"
// Skip elements
const [a, , c] = fruits; // a = "apple", c = "cherry"
// Rest operator
const [head, ...rest] = fruits;
// head = "apple", rest = ["banana", "cherry"]
Spread Operator
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
// Merge
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
// Copy
const copy = [...arr1];
// Add elements
const withNew = [...arr1, 4, 5];
Multidimensional Arrays
// 2D array (matrix)
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
matrix[0][0]; // 1
matrix[1][2]; // 6
// Loop through 2D array
matrix.forEach(row => {
row.forEach(cell => console.log(cell));
});
Common Patterns
// Check if array is empty
if (arr.length === 0) { /* ... */ }
// Remove duplicates
const unique = [...new Set([1, 1, 2, 3, 3])]; // [1, 2, 3]
// Chunk array into groups of N
function chunk(arr, size) {
const chunks = [];
for (let i = 0; i < arr.length; i += size) {
chunks.push(arr.slice(i, i + size));
}
return chunks;
}
// Flatten without .flat()
const deep = [[1, 2], [3, [4, 5]]];
const flat = JSON.parse(JSON.stringify(deep)).flat(Infinity);
Mini Practice
- Create an array of your 5 favorite movies
- Use
mapto create an array of their titles in uppercase - Use
filterto find movies with long titles - Use
reduceto calculate the total length of all titles - Merge two arrays using the spread operator
Up Next
Next: Strings →
Related Topics
Frequently Asked Questions about Arrays
What is Arrays in JavaScript?
Arrays is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Arrays?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Arrays.
Why is Arrays important in JavaScript?
Arrays is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.