JavaScript Arrays

📚 Lesson 9 of 22  •  ⏱ 11 min read  •  Beginner

Creating & Accessing

JavaScript
const fruits = ["apple", "banana", "mango"];

// Access by index (0-based)
fruits[0]  // "apple"
fruits[2]  // "mango"
fruits[fruits.length - 1]  // "mango" — last element
fruits.at(-1)               // "mango" — modern way

// Length
fruits.length  // 3

// Arrays can hold mixed types
const mixed = [1, "hello", true, null, { name: "Ravi" }];

Add & Remove Elements

JavaScript
const arr = [1, 2, 3];

// Add to end
arr.push(4);      // [1, 2, 3, 4]
arr.push(5, 6);  // [1, 2, 3, 4, 5, 6]

// Remove from end
arr.pop();        // removes 6, returns 6

// Add to start
arr.unshift(0);  // [0, 1, 2, 3, 4, 5]

// Remove from start
arr.shift();     // removes 0, returns 0

// splice(start, deleteCount, ...items) — insert or remove anywhere
arr.splice(1, 0, 99);  // insert 99 at index 1: [1, 99, 2, 3, 4, 5]
arr.splice(2, 1);      // remove 1 item at index 2

Searching

JavaScript
const nums = [10, 20, 30, 20, 40];

nums.indexOf(20)     // 1 — first occurrence
nums.lastIndexOf(20) // 3 — last occurrence
nums.indexOf(99)     // -1 — not found
nums.includes(30)    // true
nums.includes(99)    // false

// find — returns first matching element
nums.find(n => n > 15)      // 20
nums.findIndex(n => n > 15) // 1

Joining & Slicing

JavaScript
const words = ["HTML", "CSS", "JS"];

words.join(", ")   // "HTML, CSS, JS"
words.join(" + ")  // "HTML + CSS + JS"

// slice(start, end) — non-destructive copy
words.slice(1)     // ["CSS", "JS"]
words.slice(0, 2) // ["HTML", "CSS"]
words.slice(-1)   // ["JS"] — last element

// concat — merge arrays
const all = ["HTML"].concat(["CSS"], ["JS"]);
// Better with spread: [...a, ...b]

Spread & Destructuring

JavaScript
// Spread — expand array
const a = [1, 2];
const b = [3, 4];
const combined = [...a, ...b];  // [1, 2, 3, 4]

// Copy array (not reference)
const copy = [...a];

// Destructuring — unpack array values
const [first, second, ...rest] = [10, 20, 30, 40];
// first=10, second=20, rest=[30,40]

// Swap values
let x = 1, y = 2;
[x, y] = [y, x];  // x=2, y=1