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)
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.