Ordered Collections of Anything
JavaScript Arrays
Arrays hold a list of values in order. Add, read, change, and count them — the building block of every list-shaped task.
What you'll learn
- Create arrays with literals
- Access items by index, including from the end
- Use `length` and understand mutation
An array is an ordered list of values. The items can be any type — strings, numbers, objects, even other arrays.
const fruits = ["apple", "banana", "grape"];
const numbers = [1, 2, 3, 4, 5];
const mixed = ["Ada", 36, true, null, [1, 2]];
console.log(fruits);
console.log(numbers);
console.log(mixed); Reading an Item
Arrays are zero-indexed — the first item is at position 0.
const fruits = ["apple", "banana", "grape"];
console.log(fruits[0]); // "apple"
console.log(fruits[1]); // "banana"
console.log(fruits[2]); // "grape"
console.log(fruits[5]); // undefined ← out of bounds, no error Reading From the End: .at()
at() works like [index] but accepts negative numbers to count from
the end.
const fruits = ["apple", "banana", "grape"];
console.log(fruits.at(-1)); // "grape" ← last
console.log(fruits.at(-2)); // "banana"
console.log(fruits.at(0)); // "apple" How Many: .length
const fruits = ["apple", "banana", "grape"];
console.log(fruits.length); // 3
const empty = [];
console.log(empty.length); // 0 Changing Items
You can assign to a position to overwrite an item.
const fruits = ["apple", "banana", "grape"];
fruits[1] = "blueberry";
console.log(fruits); // ["apple", "blueberry", "grape"] This works even when the array was declared with const — remember,
const makes the binding constant, not the contents.
Adding and Removing — Briefly
Three of the most common methods. Full coverage in the next lesson.
const stack = [];
stack.push("a"); // add to end
stack.push("b");
stack.push("c");
console.log(stack); // ["a", "b", "c"]
const last = stack.pop(); // remove from end
console.log(last); // "c"
console.log(stack); // ["a", "b"] Mutating vs Returning New
Some array methods mutate (change) the original array. Others return a new array and leave the original alone.
const a = [3, 1, 2];
// MUTATES — changes a in place:
a.sort();
console.log(a); // [1, 2, 3]
// DOESN'T MUTATE — returns a new array:
const upper = ["hi", "bye"].map((s) => s.toUpperCase());
console.log(upper); // ["HI", "BYE"]
console.log(["hi", "bye"]); // ["hi", "bye"] (unchanged) Iterating
The simplest loop:
const fruits = ["apple", "banana", "grape"];
for (const fruit of fruits) {
console.log(fruit);
} We’ll cover map, filter, reduce, and forEach in a few lessons.
Up Next
The most useful array methods — push, pop, shift, concat, and
friends.