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 frequently used data structures in JavaScript, and the language provides a rich set of built-in methods for working with them.
// Array literal (preferred)
const fruits = ["apple", "banana", "cherry"];
// Array constructor
const numbers = new Array(1, 2, 3);
// Empty array
const empty = [];
// Array.of() — creates an array from arguments
const single = Array.of(5); // [5] (not an empty array of length 5)
// Array.from() — creates an array from an iterable or array-like object
const letters = Array.from("hello"); // ["h", "e", "l", "l", "o"]
const colours = ["red", "green", "blue"];
// Access by index (zero-based)
console.log(colours[0]); // "red"
console.log(colours[2]); // "blue"
// Modify an element
colours[1] = "yellow";
console.log(colours); // ["red", "yellow", "blue"]
// Array length
console.log(colours.length); // 3
// Access the last element
console.log(colours[colours.length - 1]); // "blue"
console.log(colours.at(-1)); // "blue" (ES2022)
| Method | Action | Returns |
|---|---|---|
push(item) | Add to the end | New length |
pop() | Remove from the end | Removed element |
unshift(item) | Add to the start | New length |
shift() | Remove from the start | Removed element |
splice(start, deleteCount, ...items) | Add/remove anywhere | Array of removed elements |
const arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3] returns 4
arr.unshift(0); // [0, 1, 2, 3]
arr.shift(); // [1, 2, 3] returns 0
// splice: remove 1 element at index 1, insert "a" and "b"
arr.splice(1, 1, "a", "b"); // [1, "a", "b", 3] returns [2]
| Method | Description | Returns |
|---|---|---|
indexOf(value) | First index of value, or -1 | Number |
lastIndexOf(value) | Last index of value, or -1 | Number |
includes(value) | Whether the array contains value | Boolean |
find(fn) | First element matching the condition | Element or undefined |
findIndex(fn) | Index of first match, or -1 | Number |
const nums = [10, 20, 30, 20, 40];
nums.indexOf(20); // 1
nums.lastIndexOf(20); // 3
nums.includes(30); // true
nums.find(n => n > 25); // 30
nums.findIndex(n => n > 25); // 2
Executes a function for each element (does not return a new array):
const names = ["Alice", "Bob", "Charlie"];
names.forEach((name, index) => {
console.log(index + ": " + name);
});
// 0: Alice
// 1: Bob
// 2: Charlie
Creates a new array by transforming each element:
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
Creates a new array with only elements that pass a test:
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6]
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.