Arrays Basics
An array is JavaScript's most fundamental data structure — an ordered, zero-indexed list that can hold any mix of values. From storing a shopping cart to rendering a feed of posts, arrays are at the heart of almost every JavaScript application. This chapter covers everything you need to create, read, modify, and iterate arrays with confidence.
length property and how it works
What is an Array?
An array is an ordered collection of values
stored in a single variable. Each value has a numeric
index starting at 0.
JavaScript arrays are dynamic (they grow and shrink automatically),
heterogeneous (they can hold mixed types), and are actually
objects under the hood — giving them powerful built-in methods.
Array constructor. Passing a
single number creates a sparse array of that length.new Array(10)).// ↑ index 0 ↑ index 1 ↑ index 2
fruits[0] → "apple"
fruits[2] → "cherry"
fruits.length → 3 // always = highest index + 1
undefined, not an error
Creating Arrays
There are three main ways to create an array in JavaScript. The array literal is almost always the right choice — it's shorter, clearer, and less surprising than the constructor:
// ── 1. Array literal (preferred) ─────────────────────────────
const empty = []; // empty array
const nums = [1, 2, 3, 4, 5]; // numbers
const fruits = ["apple", "banana", "cherry"]; // strings
const mixed = [1, "hello", true, null, { id: 1 }]; // mixed types ✓
// ── 2. new Array() constructor ───────────────────────────────
const arr1 = new Array(3); // [empty × 3] — sparse, NOT [3]
const arr2 = new Array(1, 2, 3); // [1, 2, 3]
// ── 3. Array.from() — from iterables / with fill ─────────────
Array.from("hello"); // ["h","e","l","l","o"]
Array.from(new Set([1,2,2,3])); // [1,2,3] — deduped
Array.from({ length: 5 }, (_, i) => i + 1); // [1,2,3,4,5]
Array.from({ length: 3 }, () => 0); // [0,0,0]
// ── Array.of() — consistent from arguments ───────────────────
Array.of(3); // [3] — unlike new Array(3) which creates 3 empty slots
Array.of(1, 2, 3); // [1, 2, 3]
new Array(3) does not create [3] —
it creates a sparse array with 3 empty slots ([empty × 3]).
This trips up beginners constantly. Stick to the array literal
[3] or use Array.of(3) when you want
an array containing the number 3.
Indexing — Reading & Writing Elements
Array elements are accessed using bracket notation with a zero-based index. You can also use bracket notation to update an element, or to write beyond the current end (which automatically grows the array).
arr[0]
arr[n]
arr[arr.length - 1] or arr.at(-1)
undefined, not an error
arr[0] = "new"
arr[arr.length] = val
arr[10] = x creates
sparse holes
const colors = ["red", "green", "blue"];
// ── Reading ──────────────────────────────────────────────────
colors[0]; // "red" — first element
colors[2]; // "blue" — last element (index 2)
colors[colors.length - 1]; // "blue" — last element (dynamic)
colors.at(-1); // "blue" — at() with negative index (ES2022)
colors.at(-2); // "green" — second from last
colors[99]; // undefined — no error, just undefined
// ── Writing ──────────────────────────────────────────────────
colors[0] = "crimson"; // update: ["crimson", "green", "blue"]
colors[3] = "purple"; // append: ["crimson","green","blue","purple"]
// ── length ───────────────────────────────────────────────────
colors.length; // 4
colors.length = 2; // truncates! → ["crimson", "green"]
// ── Nested arrays (2D) ───────────────────────────────────────
const matrix = [[1,2],[3,4],[5,6]];
matrix[1][0]; // 3 — row 1, column 0
matrix[2][1]; // 6 — row 2, column 1Adding & Removing Elements
JavaScript arrays are mutable — their contents
can be changed in place. The most common mutation methods are
push, pop,
shift, unshift,
and splice. Know which end each operates on:
| Method | Action | Mutates? | Returns |
|---|---|---|---|
| push(val) | Add to end | Yes | New length |
| pop() | Remove from end | Yes | Removed element |
| unshift(val) | Add to front | Yes | New length |
| shift() | Remove from front | Yes | Removed element |
| splice(i, n, ...vals) | Remove/insert at any position | Yes | Array of removed items |
| concat(arr) | Merge arrays | No | New merged array |
| slice(start, end) | Copy a portion | No | New sub-array |
const arr = ["b", "c"];
// ── push / pop (end) ─────────────────────────────────────────
arr.push("d"); // ["b","c","d"] → returns 3 (new length)
arr.push("e", "f"); // ["b","c","d","e","f"]
arr.pop(); // ["b","c","d","e"] → returns "f"
// ── unshift / shift (front) ──────────────────────────────────
arr.unshift("a"); // ["a","b","c","d","e"] → returns 5
arr.shift(); // ["b","c","d","e"] → returns "a"
// ── splice — swiss-army knife ────────────────────────────────
const items = ["a", "b", "c", "d"];
items.splice(1, 0, "X"); // insert "X" at index 1 → ["a","X","b","c","d"]
items.splice(2, 1); // remove 1 at index 2 → ["a","X","c","d"]
items.splice(1, 2, "Y", "Z"); // replace 2 items with "Y","Z" → ["a","Y","Z","d"]
// ── slice — non-mutating copy ────────────────────────────────
const letters = ["a", "b", "c", "d", "e"];
letters.slice(1, 3); // ["b","c"] — indices 1 up to (not including) 3
letters.slice(-2); // ["d","e"] — last two elements
letters.slice(); // ["a","b","c","d","e"] — shallow copySearching & Checking
JavaScript provides several methods for finding elements and checking membership. Choose based on whether you need the index, the value, or just a boolean answer:
val is found using
strict equality, or -1 if not found. Use lastIndexOf to search
from the end.true or false. Cleaner than
comparing indexOf() to -1. Also handles NaN
correctly (indexOf does not).true, or undefined if none match. Use
findIndex to get the index instead.
some returns true if at least one
element passes the test. every returns true only if all
elements pass.const nums = [10, 20, 30, 20, 40];
// ── indexOf / lastIndexOf ─────────────────────────────────────
nums.indexOf(20); // 1 (first occurrence)
nums.lastIndexOf(20); // 3 (last occurrence)
nums.indexOf(99); // -1 (not found)
// ── includes ─────────────────────────────────────────────────
nums.includes(30); // true
nums.includes(99); // false
[1, NaN].includes(NaN); // true ← indexOf(NaN) returns -1, includes handles it ✓
// ── find / findIndex ─────────────────────────────────────────
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Carol" }
];
users.find(u => u.id === 2); // { id:2, name:"Bob" }
users.findIndex(u => u.id === 2); // 1
users.find(u => u.id === 99); // undefined
// ── some / every ─────────────────────────────────────────────
nums.some(n => n > 35); // true — 40 > 35
nums.every(n => n > 0); // true — all positive
nums.every(n => n > 15); // false — 10 is not > 15Iterating Arrays
There are four main ways to loop over an array. Each has different strengths — pick based on whether you need the index, want to break early, or prefer a functional style:
break and continue. Best for reverse loops or custom step
sizes.
break and
continue. Use .entries() to get both index and value.
(value, index, array). Cannot break. Good for side effects but
not for early exit.
const fruits = ["apple", "banana", "cherry"];
// ── 1. Classic for loop ───────────────────────────────────────
for (let i = 0; i < fruits.length; i++) {
console.log(i, fruits[i]); // 0 "apple" 1 "banana" 2 "cherry"
}
// ── 2. for...of (values only) ─────────────────────────────────
for (const fruit of fruits) {
console.log(fruit); // apple banana cherry
}
// ── 3. for...of with entries() — index + value ───────────────
for (const [i, fruit] of fruits.entries()) {
console.log(`${i}: ${fruit}`); // 0: apple 1: banana 2: cherry
}
// ── 4. forEach ───────────────────────────────────────────────
fruits.forEach((fruit, i) => {
console.log(`${i}: ${fruit}`);
});
// ── 5. Reverse iteration ──────────────────────────────────────
for (let i = fruits.length - 1; i >= 0; i--) {
console.log(fruits[i]); // cherry banana apple
}for...of when you need to
break early — forEach cannot be
exited before it visits every element.
Use forEach for pure side-effect loops
(logging, updating DOM) where you know you'll process every item.
Both are cleaner than a classic for loop when you
don't need the index.
Real-World Use Cases
Arrays are everywhere in JavaScript. Here are the practical patterns you'll use them for every day:
push, remove with filter or
splice, calculate total with reduce.
push,
toggle with map, remove completed with filter.forEach or map to render, search with find.
reduce for totals, Math.max(...arr) for peaks.
filter +
includes. Re-run on every keystroke for live results.
push/pop for a stack (LIFO). Use
push/shift for a queue (FIFO). Arrays are both!
Try It — Live Editor
Experiment with arrays below. Try modifying elements, calling mutation methods, and iterating — all without leaving this page.
Common Patterns & Recipes
These are the everyday array utilities you'll write constantly in real JavaScript projects — from cloning to deduplication to flattening:
// ── Shallow clone (never mutate the original) ─────────────────
const original = [1, 2, 3];
const copy1 = [...original]; // spread (preferred)
const copy2 = original.slice(); // slice with no args
const copy3 = Array.from(original); // Array.from
// ── Remove duplicates ─────────────────────────────────────────
const dupes = [1, 2, 2, 3, 3, 3, 4];
const unique = [...new Set(dupes)]; // [1, 2, 3, 4]
// ── Flatten nested arrays ─────────────────────────────────────
[1, [2, 3], [4, [5]]].flat(); // [1, 2, 3, 4, [5]] — 1 level
[1, [2, 3], [4, [5]]].flat(Infinity); // [1, 2, 3, 4, 5] — all levels
// ── Merge arrays ─────────────────────────────────────────────
const merged = [...[1,2], ...[3,4]]; // [1, 2, 3, 4]
const merged2 = [1,2].concat([3,4]); // [1, 2, 3, 4]
// ── Shuffle an array (Fisher-Yates) ──────────────────────────
function shuffle(arr) {
const a = [...arr];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]]; // swap via destructuring
}
return a;
}
// ── Group by property ─────────────────────────────────────────
const people = [
{ name: "Alice", dept: "Eng" },
{ name: "Bob", dept: "HR" },
{ name: "Carol", dept: "Eng" }
];
const byDept = people.reduce((acc, p) => {
(acc[p.dept] = acc[p.dept] || []).push(p.name);
return acc;
}, {});
// { Eng: ["Alice","Carol"], HR: ["Bob"] }["a","b","c"].indexOf("b") return?new Array(3) create?- An array is a zero-indexed, ordered, dynamic list. Prefer the array literal
[]— it's shorter and less surprising thannew Array(). - Elements are accessed by index (
arr[0]). Out-of-bounds access returnsundefined, not an error. Usearr.at(-1)to access from the end cleanly. - The
lengthproperty always equals the highest index plus one. Setting it to a smaller number truncates the array. - push / pop operate on the end. unshift / shift operate on the front. splice handles insertion and removal at any position.
indexOfandlastIndexOffind positions.includesreturns a boolean (and handles NaN correctly).findandfindIndexaccept a predicate for object searches.- Use
for...offor clean iteration with early-exit support. UseforEachfor side effects when you'll process every element. Usefor...of arr.entries()for both index and value. - Clone with
[...arr], deduplicate with[...new Set(arr)], flatten with.flat(), and merge with the spread operator for clean immutable patterns.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.