Arrays in JavaScript
Creating, indexing, and mutating arrays, plus the core methods you'll use daily.
2 min read
An array is an ordered list of values, indexed from zero. JavaScript arrays can hold any mix of types, including other arrays and objects, and they resize automatically as you add or remove items.
Creating and accessing arrays
const fruits = ["apple", "banana", "cherry"];
fruits[0]; // "apple"
fruits[fruits.length - 1]; // "cherry" -- last item
fruits.length; // 3Indexing past the end doesn't throw — it just returns undefined:
fruits[10]; // undefinedAdding and removing items
fruits.push("date"); // add to the end -- returns new length
fruits.pop(); // remove from the end -- returns removed item
fruits.unshift("apricot"); // add to the start
fruits.shift(); // remove from the startpush/pop operate on the end of the array and are fast; unshift/shift operate on the start and are slower, since every other item has to be re-indexed.
Checking and finding
fruits.includes("banana"); // true
fruits.indexOf("cherry"); // 2 (-1 if not found)
fruits.find(f => f.startsWith("b")); // "banana" -- first matchSlicing vs splicing
These two are easy to confuse and do very different things. slice copies a portion of an array without changing the original; splice mutates the original in place.
const nums = [1, 2, 3, 4, 5];
nums.slice(1, 3); // [2, 3] -- new array, nums unchanged
nums.splice(1, 2); // removes 2 items starting at index 1
console.log(nums); // [1, 4, 5] -- original array mutatedArrays are objects, checked with Array.isArray
typeof []; // "object" -- not helpful for telling arrays apart
Array.isArray([]); // true
Array.isArray({}); // falseSince typeof reports arrays as plain "object", Array.isArray() is the reliable way to check.
Mutating vs non-mutating methods
Some array methods change the array in place (push, pop, splice, sort, reverse); others return a new array and leave the original untouched (slice, map, filter, concat). This distinction matters a lot once you're passing arrays around — mutating an array another part of the program still holds a reference to can cause bugs that are hard to trace. When in doubt, prefer the non-mutating version.
The next lesson covers objects — JavaScript's other core data structure, for storing key-value data instead of an ordered list.