You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Arrays are ordered collections of values. They are one of the most commonly used data structures in JavaScript, and the language provides a rich set of built-in methods for working with them.
const fruits = ["apple", "banana", "cherry"];
const numbers = [1, 2, 3, 4, 5];
const mixed = [42, "hello", true, null];
const empty = [];
Arrays use zero-based indexing:
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "cherry"
console.log(fruits[fruits.length - 1]); // "cherry" (last element)
const arr = ["a", "b", "c"];
arr.push("d"); // add to end => ["a", "b", "c", "d"]
arr.pop(); // remove from end => ["a", "b", "c"]
arr.unshift("z"); // add to start => ["z", "a", "b", "c"]
arr.shift(); // remove from start => ["a", "b", "c"]
arr.splice(1, 1); // remove 1 element at index 1 => ["a", "c"]
arr.splice(1, 0, "x"); // insert "x" at index 1 => ["a", "x", "c"]
const colors = ["red", "green", "blue", "red"];
colors.indexOf("green"); // 1
colors.lastIndexOf("red"); // 3
colors.includes("blue"); // true
colors.includes("purple"); // false
// find — returns the first matching element
const nums = [5, 12, 8, 130, 44];
const found = nums.find(n => n > 10); // 12
// findIndex — returns the index of the first match
const index = nums.findIndex(n => n > 10); // 1
const numbers = [1, 2, 3, 4, 5];
// map — create a new array by transforming each element
const squares = numbers.map(n => n ** 2);
// [1, 4, 9, 16, 25]
// filter — create a new array with only elements that pass the test
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4]
// reduce — fold the array into a single value
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 15
// sort — sorts in place (mutates the array)
const words = ["banana", "apple", "cherry"];
words.sort(); // ["apple", "banana", "cherry"]
// sort numbers (default sort is alphabetical!)
const nums2 = [10, 2, 30, 4];
nums2.sort((a, b) => a - b); // [2, 4, 10, 30]
const a = [1, 2];
const b = [3, 4];
const combined = a.concat(b); // [1, 2, 3, 4]
const spread = [...a, ...b]; // [1, 2, 3, 4] (spread operator)
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.