Tutorials JavaScript Arrays Basics
Ch 30 / 78
Chapter 30 Beginner 8 min read JavaScript

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.

What you'll learn
Three ways to create an array
Indexing — reading and writing elements
The length property and how it works
Adding & removing elements — push, pop, shift, unshift, splice
Searching & checking — indexOf, includes, find
Iterating arrays — for, for...of, forEach

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 Literal
The standard and preferred way to create an array. Values are listed inside square brackets, separated by commas.
Use when: you know the initial values — covers 99% of real-world cases.
new Array()
Array Constructor
Creates an array using the Array constructor. Passing a single number creates a sparse array of that length.
Use when: pre-allocating an array of known size (e.g. new Array(10)).
Array.from()
From Iterable / Map
Creates an array from any iterable — string, Set, NodeList — or from a length with a map function to fill values.
Use when: converting iterables, generating ranges, or filling with computed values.
const fruits = ["apple", "banana", "cherry"];
// ↑ index 0 ↑ index 1 ↑ index 2
fruits[0] → "apple"
fruits[2] → "cherry"
fruits.length → 3  // always = highest index + 1
Index — zero-based position of each element Element — the value stored at that index length — total number of elements (last index + 1) Out-of-bounds access returns 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:

JavaScript — Creating Arrays
// ── 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]
Constructor Gotcha
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).

Reading elements
0 First element — arr[0]
n Any element — arr[n]
-1 Last element — arr[arr.length - 1] or arr.at(-1)
! Out of bounds — returns undefined, not an error
Writing elements
✓ Update existing — arr[0] = "new"
✓ Add at end — arr[arr.length] = val
⚠ Gap write — arr[10] = x creates sparse holes
✓ Prefer push() for appending — cleaner and more expressive
JavaScript — Reading & Writing Array Elements
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 1

Adding & 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:

Adding elements
➕ push(val) — add to the end, returns new length
➕ unshift(val) — add to the front, shifts all indices up
➕ splice(i, 0, val) — insert at any index
➕ concat(arr) — return new merged array (non-mutating)
Removing elements
➖ pop() — remove from the end, returns removed item
➖ shift() — remove from the front, returns removed item
➖ splice(i, n) — remove n items starting at index i
➖ filter(fn) — return new array without matching items
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
JavaScript — push, pop, shift, unshift, splice
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 copy

Searching & 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:

indexOf(val)
Returns the first index where val is found using strict equality, or -1 if not found. Use lastIndexOf to search from the end.
includes(val)
Returns true or false. Cleaner than comparing indexOf() to -1. Also handles NaN correctly (indexOf does not).
find(fn)
Returns the first element for which the callback returns true, or undefined if none match. Use findIndex to get the index instead.
some(fn) / every(fn)
some returns true if at least one element passes the test. every returns true only if all elements pass.
JavaScript — Searching Arrays
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 > 15

Iterating 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:

for (classic)
Full control — access index and value. Works with break and continue. Best for reverse loops or custom step sizes.
for...of
Cleaner syntax, values only. Supports break and continue. Use .entries() to get both index and value.
forEach(fn)
Functional style — callback receives (value, index, array). Cannot break. Good for side effects but not for early exit.
map / filter / reduce
Transform, filter, or accumulate — these return new values. The core of functional array programming. Covered in depth in the next chapter.
JavaScript — Four Ways to Iterate Arrays
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
}
forEach vs for...of
Use 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:

Shopping Cart
Add items with push, remove with filter or splice, calculate total with reduce.
mutating
Todo / Task List
Store tasks as objects in an array. Add with push, toggle with map, remove completed with filter.
mutating
API Response Data
Most REST APIs return arrays of objects. Loop with forEach or map to render, search with find.
iterating
Data / Charts
Store numeric data points, labels, or series. Use reduce for totals, Math.max(...arr) for peaks.
reading
Search / Filter UI
Filter a master list by a search query using filter + includes. Re-run on every keystroke for live results.
reading
Stack & Queue
Use push/pop for a stack (LIFO). Use push/shift for a queue (FIFO). Arrays are both!
mutating
⚡
Free Resource
Download our JavaScript Cheat Sheet
Arrays, methods, iteration patterns & ES6 features — all on one printable page.
Get Sheet

Try It — Live Editor

Experiment with arrays below. Try modifying elements, calling mutation methods, and iterating — all without leaving this page.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These are the everyday array utilities you'll write constantly in real JavaScript projects — from cloning to deduplication to flattening:

JavaScript — Array Recipes
// ── 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"] }
Quick Check
What does ["a","b","c"].indexOf("b") return?
Quick Check
What does new Array(3) create?
Quick Check
Which method removes an item from the front of an array?
Chapter Summary
  • An array is a zero-indexed, ordered, dynamic list. Prefer the array literal [] — it's shorter and less surprising than new Array().
  • Elements are accessed by index (arr[0]). Out-of-bounds access returns undefined, not an error. Use arr.at(-1) to access from the end cleanly.
  • The length property 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.
  • indexOf and lastIndexOf find positions. includes returns a boolean (and handles NaN correctly). find and findIndex accept a predicate for object searches.
  • Use for...of for clean iteration with early-exit support. Use forEach for side effects when you'll process every element. Use for...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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel