Skip to content
JavaScript Fundamentals

JavaScript Arrays

Beginner Lesson 6 of 10

Arrays are ordered collections that can hold multiple values.

const arr = [1, 2, 3, 4, 5];
const mixed = [1, "hello", true, null];
const nested = [[1, 2], [3, 4]];
const fruits = ["apple", "banana"];
fruits.push("cherry"); // Add to end
fruits.pop(); // Remove from end
fruits.unshift("mango"); // Add to start
fruits.shift(); // Remove from start
fruits.length; // Get length
const numbers = [1, 2, 3, 4, 5];
// map - transform each element
numbers.map(x => x * 2); // [2, 4, 6, 8, 10]
// filter - keep matching elements
numbers.filter(x => x > 2); // [3, 4, 5]
// reduce - combine into single value
numbers.reduce((acc, x) => acc + x, 0); // 15
const arr = [1, 2, 3, 4, 5];
arr.find(x => x > 3); // 4 (first match)
arr.findIndex(x => x > 3); // 3 (index of first match)
arr.includes(3); // true
arr.indexOf(3); // 2
const arr = ["a", "b", "c"];
arr.forEach((item, index) => {
console.log(`${index}: ${item}`);
});
for (const item of arr) {
console.log(item);
}
const arr = [3, 1, 4, 1, 5];
arr.sort((a, b) => a - b); // [1, 1, 3, 4, 5]
arr.reverse(); // [5, 4, 3, 1, 1]
arr.slice(1, 3); // [4, 3] (copy portion)
arr.splice(1, 2); // Remove 2 items at index 1
arr.join(", "); // "5, 4, 3, 1, 1"
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
// Spread
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
// Destructuring
const [first, second, ...rest] = arr1;
// first = 1, second = 2, rest = [3]

Continue to DOM Manipulation →