Welcome back! 👋 In the previous lesson, you mastered template literals. Now let's dive into one of the most important and most-used data structures in all of JavaScript — Arrays!
Arrays are everywhere — a list of products, a set of user scores, a collection of API results, a queue of notifications. Once you know how to create, read, and manipulate arrays with JavaScript's powerful built-in methods, you'll be able to handle real data like a professional developer.
Let's master arrays completely!
What is an Array?
An array is an ordered collection of values stored in a single variable. Each value is called an element, and each element has a numbered position called an index — starting at 0.
let fruits = ["Apple", "Banana", "Mango", "Orange"];
// index: 0 1 2 3Why Arrays?
Without arrays, storing multiple related values is messy:
// ❌ Without arrays — individual variables for each item
let student1 = "Mihir";
let student2 = "Priya";
let student3 = "Rahul";
// ✅ With an array — one variable, all values
let students = ["Mihir", "Priya", "Rahul"];Creating Arrays
Array Literal (Most Common)
let numbers = [1, 2, 3, 4, 5];
let names = ["Mihir", "Priya", "Rahul"];
let mixed = [42, "hello", true, null]; // mixed types allowed
let empty = []; // empty arrayArray Constructor
let arr = new Array(3); // [empty × 3] — 3 empty slots
let arr = new Array(1, 2, 3); // [1, 2, 3]
// ✅ Prefer array literals — they're cleanerArray of Objects
let students = [
{ name: "Mihir", marks: 92 },
{ name: "Priya", marks: 85 },
{ name: "Rahul", marks: 78 },
];Accessing Array Elements
let fruits = ["Apple", "Banana", "Mango", "Orange"];
console.log(fruits[0]); // "Apple" (first)
console.log(fruits[2]); // "Mango"
console.log(fruits[fruits.length - 1]); // "Orange" (last)
console.log(fruits[10]); // undefined (out of bounds)Array Length
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.length); // 3Updating Elements
let colors = ["Red", "Green", "Blue"];
colors[1] = "Yellow"; // Update index 1
console.log(colors); // ["Red", "Yellow", "Blue"]Adding and Removing Elements
push() — Add to End
let fruits = ["Apple", "Banana"];
fruits.push("Mango");
fruits.push("Orange", "Grapes"); // multiple at once
console.log(fruits); // ["Apple", "Banana", "Mango", "Orange", "Grapes"]pop() — Remove from End
let fruits = ["Apple", "Banana", "Mango"];
let removed = fruits.pop();
console.log(removed); // "Mango"
console.log(fruits); // ["Apple", "Banana"]unshift() — Add to Beginning
let fruits = ["Banana", "Mango"];
fruits.unshift("Apple");
console.log(fruits); // ["Apple", "Banana", "Mango"]shift() — Remove from Beginning
let fruits = ["Apple", "Banana", "Mango"];
let removed = fruits.shift();
console.log(removed); // "Apple"
console.log(fruits); // ["Banana", "Mango"]Quick Reference
| Method | Action | Returns |
|---|---|---|
push(item) | Add to end | New length |
pop() | Remove from end | Removed item |
unshift(item) | Add to beginning | New length |
shift() | Remove from beginning | Removed item |
splice() — Add/Remove Anywhere
splice() is the most versatile method — it can add, remove, or replace elements at any position.
Syntax
array.splice(startIndex, deleteCount, ...itemsToAdd)Remove Elements
let fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"];
// Remove 2 elements starting at index 1
let removed = fruits.splice(1, 2);
console.log(removed); // ["Banana", "Mango"]
console.log(fruits); // ["Apple", "Orange", "Grapes"]Insert Elements
let fruits = ["Apple", "Orange", "Grapes"];
// At index 1, remove 0 items, insert "Banana" and "Mango"
fruits.splice(1, 0, "Banana", "Mango");
console.log(fruits); // ["Apple", "Banana", "Mango", "Orange", "Grapes"]Replace Elements
let fruits = ["Apple", "Banana", "Mango"];
// At index 1, remove 1 item, insert "Grapes"
fruits.splice(1, 1, "Grapes");
console.log(fruits); // ["Apple", "Grapes", "Mango"]slice() — Extract a Portion (Non-Destructive)
slice() returns a new array — it does not modify the original.
let fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"];
console.log(fruits.slice(1, 3)); // ["Banana", "Mango"] (index 1 up to 3)
console.log(fruits.slice(2)); // ["Mango", "Orange", "Grapes"] (from 2 to end)
console.log(fruits.slice(-2)); // ["Orange", "Grapes"] (last 2)
console.log(fruits); // Original unchanged ✅splice vs slice
splice() | slice() | |
|---|---|---|
| Modifies original | ✅ Yes | ❌ No |
| Returns | Removed items | New array copy |
| Use for | Adding/removing | Extracting a portion |
Searching Methods
indexOf() — Find index of a value
let fruits = ["Apple", "Banana", "Mango", "Banana"];
console.log(fruits.indexOf("Banana")); // 1 (first occurrence)
console.log(fruits.lastIndexOf("Banana")); // 3 (last occurrence)
console.log(fruits.indexOf("Grapes")); // -1 (not found)includes() — Check if value exists
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.includes("Banana")); // true
console.log(fruits.includes("Grapes")); // falsefind() — Find first matching element
let students = [
{ name: "Mihir", marks: 92 },
{ name: "Priya", marks: 85 },
{ name: "Rahul", marks: 78 },
];
let topStudent = students.find(s => s.marks > 90);
console.log(topStudent); // { name: "Mihir", marks: 92 }findIndex() — Find index of first match
let scores = [45, 82, 60, 91, 73];
let firstPassIndex = scores.findIndex(s => s >= 75);
console.log(firstPassIndex); // 1 (index of 82)Transformation Methods
map() — Transform Every Element
Creates a new array by applying a function to every element.
let prices = [100, 200, 300, 400];
// Add 18% tax to every price
let withTax = prices.map(price => price * 1.18);
console.log(withTax); // [118, 236, 354, 472]
// Original unchanged ✅
console.log(prices); // [100, 200, 300, 400]let students = [
{ name: "Mihir", marks: 92 },
{ name: "Priya", marks: 85 },
];
// Extract just the names
let names = students.map(s => s.name);
console.log(names); // ["Mihir", "Priya"]filter() — Keep Matching Elements
Creates a new array with only elements that pass a condition.
let scores = [45, 82, 60, 91, 73, 55, 88];
let passing = scores.filter(score => score >= 75);
console.log(passing); // [82, 91, 88]let products = [
{ name: "Laptop", price: 55000, inStock: true },
{ name: "Mouse", price: 800, inStock: false },
{ name: "Monitor", price: 18000, inStock: true },
];
let available = products.filter(p => p.inStock);
console.log(available.map(p => p.name)); // ["Laptop", "Monitor"]reduce() — Reduce to a Single Value
Processes every element and accumulates a result.
let numbers = [1, 2, 3, 4, 5];
let total = numbers.reduce((accumulator, current) => accumulator + current, 0);
console.log(total); // 15let cart = [
{ name: "Laptop", price: 55000, qty: 1 },
{ name: "Mouse", price: 800, qty: 2 },
{ name: "Bag", price: 1200, qty: 1 },
];
let grandTotal = cart.reduce((total, item) => total + item.price * item.qty, 0);
console.log(`Total: ₹${grandTotal.toLocaleString()}`);
// Output: Total: ₹57,800forEach() — Loop Over Elements
Runs a function for each element. Does not return a new array.
let fruits = ["Apple", "Banana", "Mango"];
fruits.forEach((fruit, index) => {
console.log(`${index + 1}. ${fruit}`);
});
// Output:
// 1. Apple
// 2. Banana
// 3. MangoSorting Methods
sort() — Sort In Place
// Strings — alphabetically
let fruits = ["Mango", "Apple", "Orange", "Banana"];
fruits.sort();
console.log(fruits); // ["Apple", "Banana", "Mango", "Orange"]
// ⚠️ Numbers — sort() converts to strings by default!
let nums = [10, 1, 100, 5, 25];
nums.sort();
console.log(nums); // [1, 10, 100, 25, 5] ← Wrong!
// ✅ Numbers — use a compare function
nums.sort((a, b) => a - b); // Ascending
console.log(nums); // [1, 5, 10, 25, 100] ✅
nums.sort((a, b) => b - a); // Descending
console.log(nums); // [100, 25, 10, 5, 1] ✅Sort Array of Objects
let students = [
{ name: "Sara", marks: 95 },
{ name: "Mihir", marks: 82 },
{ name: "Priya", marks: 91 },
{ name: "Rahul", marks: 78 },
];
// Sort by marks descending
students.sort((a, b) => b.marks - a.marks);
students.forEach((s, i) => {
console.log(`${i + 1}. ${s.name} — ${s.marks}`);
});
// Output:
// 1. Sara — 95
// 2. Priya — 91
// 3. Mihir — 82
// 4. Rahul — 78reverse() — Reverse In Place
let nums = [1, 2, 3, 4, 5];
nums.reverse();
console.log(nums); // [5, 4, 3, 2, 1]Combining Arrays
concat() — Merge Arrays
let a = [1, 2, 3];
let b = [4, 5, 6];
let c = a.concat(b);
console.log(c); // [1, 2, 3, 4, 5, 6]
// Original arrays unchanged ✅Spread Operator ... (Modern Way)
let a = [1, 2, 3];
let b = [4, 5, 6];
let c = [...a, ...b];
console.log(c); // [1, 2, 3, 4, 5, 6]
// Insert in the middle
let d = [...a, 99, ...b];
console.log(d); // [1, 2, 3, 99, 4, 5, 6]flat() — Flatten Nested Arrays
let nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]] — one level
console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6] — two levels
console.log(nested.flat(Infinity)); // [1, 2, 3, 4, 5, 6] — all levelsChecking Arrays
Array.isArray() — Is it an array?
console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray("hello")); // false
console.log(Array.isArray({ a: 1 })); // falseevery() — Do ALL elements pass?
let scores = [75, 82, 90, 88];
console.log(scores.every(s => s >= 70)); // true — all pass
console.log(scores.every(s => s >= 85)); // false — not all passsome() — Does ANY element pass?
let scores = [45, 55, 82, 38];
console.log(scores.some(s => s >= 75)); // true — at least one passes
console.log(scores.some(s => s >= 90)); // false — none passesConverting Arrays
join() — Array to String
let words = ["JavaScript", "is", "awesome"];
console.log(words.join(" ")); // "JavaScript is awesome"
console.log(words.join("-")); // "JavaScript-is-awesome"
console.log(words.join("")); // "JavaScriptisawesome"Array.from() — Create Array from Iterable
// From a string
console.log(Array.from("Hello")); // ["H", "e", "l", "l", "o"]
// From a Set (removes duplicates)
console.log(Array.from(new Set([1, 2, 2, 3, 3]))); // [1, 2, 3]
// With a mapping function — generate ranges
console.log(Array.from({ length: 5 }, (_, i) => i + 1)); // [1, 2, 3, 4, 5]Real-World Examples
Example 1: Student Leaderboard
let students = [
{ name: "Mihir", marks: 92 },
{ name: "Priya", marks: 85 },
{ name: "Rahul", marks: 78 },
{ name: "Sara", marks: 95 },
{ name: "Arjun", marks: 60 },
];
let leaderboard = students
.filter(s => s.marks >= 75)
.sort((a, b) => b.marks - a.marks)
.map((s, i) => `${i + 1}. ${s.name.padEnd(8)} — ${s.marks} marks`);
console.log("=== 🏆 Leaderboard ===");
leaderboard.forEach(row => console.log(row));
// Output:
// 1. Sara — 95 marks
// 2. Mihir — 92 marks
// 3. Priya — 85 marks
// 4. Rahul — 78 marksExample 2: Inventory Manager
let inventory = [
{ id: 1, name: "Laptop", qty: 5, price: 55000 },
{ id: 2, name: "Mouse", qty: 0, price: 800 },
{ id: 3, name: "Monitor", qty: 3, price: 18000 },
{ id: 4, name: "Keyboard", qty: 12, price: 1500 },
];
let inStock = inventory.filter(i => i.qty > 0);
let outOfStock = inventory.filter(i => i.qty === 0);
let totalValue = inventory.reduce((sum, i) => sum + i.price * i.qty, 0);
let mostExpensive = inventory.reduce((max, i) => i.price > max.price ? i : max);
console.log(`In Stock: ${inStock.map(i => i.name).join(", ")}`);
console.log(`Out of Stock: ${outOfStock.map(i => i.name).join(", ")}`);
console.log(`Total Value: ₹${totalValue.toLocaleString()}`);
console.log(`Most Expensive: ${mostExpensive.name} @ ₹${mostExpensive.price.toLocaleString()}`);
// Output:
// In Stock: Laptop, Monitor, Keyboard
// Out of Stock: Mouse
// Total Value: ₹3,11,000
// Most Expensive: Laptop @ ₹55,000Example 3: Remove Duplicates
let tags = ["javascript", "css", "html", "javascript", "css", "react"];
// Method 1: Using Set
let uniqueTags = [...new Set(tags)];
console.log(uniqueTags); // ["javascript", "css", "html", "react"]
// Method 2: Using filter + indexOf
let uniqueTags2 = tags.filter((tag, index) => tags.indexOf(tag) === index);
console.log(uniqueTags2); // ["javascript", "css", "html", "react"]Example 4: Group Items by Category
let products = [
{ name: "Laptop", category: "Electronics" },
{ name: "T-Shirt", category: "Clothing" },
{ name: "Phone", category: "Electronics" },
{ name: "Jeans", category: "Clothing" },
{ name: "Earbuds", category: "Electronics" },
];
let grouped = products.reduce((groups, product) => {
let key = product.category;
if (!groups[key]) groups[key] = [];
groups[key].push(product.name);
return groups;
}, {});
for (let category in grouped) {
console.log(`${category}: ${grouped[category].join(", ")}`);
}
// Output:
// Electronics: Laptop, Phone, Earbuds
// Clothing: T-Shirt, JeansExample 5: Paginate an Array
function paginate(array, pageSize, pageNumber) {
let start = (pageNumber - 1) * pageSize;
return array.slice(start, start + pageSize);
}
let products = Array.from({ length: 20 }, (_, i) => `Product ${i + 1}`);
console.log("Page 1:", paginate(products, 5, 1)); // Product 1–5
console.log("Page 2:", paginate(products, 5, 2)); // Product 6–10
console.log("Page 3:", paginate(products, 5, 3)); // Product 11–15Array Methods Cheat Sheet
| Method | What it does | Mutates? |
|---|---|---|
push(item) | Add to end | ✅ Yes |
pop() | Remove from end | ✅ Yes |
unshift(item) | Add to beginning | ✅ Yes |
shift() | Remove from beginning | ✅ Yes |
splice(i, n) | Add/remove anywhere | ✅ Yes |
sort() | Sort in place | ✅ Yes |
reverse() | Reverse in place | ✅ Yes |
slice(s, e) | Extract a copy | ❌ No |
concat(arr) | Merge arrays | ❌ No |
map(fn) | Transform elements | ❌ No |
filter(fn) | Keep matching | ❌ No |
reduce(fn) | Reduce to value | ❌ No |
forEach(fn) | Loop over elements | ❌ No |
find(fn) | First match | ❌ No |
findIndex(fn) | Index of first match | ❌ No |
includes(val) | Contains value? | ❌ No |
indexOf(val) | Index of value | ❌ No |
every(fn) | All pass? | ❌ No |
some(fn) | Any pass? | ❌ No |
flat(depth) | Flatten nested | ❌ No |
join(sep) | Array to string | ❌ No |
Common Mistakes
Mistake 1: Sorting Numbers Without a Compare Function
let nums = [10, 1, 100, 5, 25];
// ❌ Default sort converts to strings — wrong order!
nums.sort();
console.log(nums); // [1, 10, 100, 25, 5] ← Wrong!
// ✅ Always use a compare function for numbers
nums.sort((a, b) => a - b);
console.log(nums); // [1, 5, 10, 25, 100] ✅Mistake 2: forEach Doesn't Return a New Array
let numbers = [1, 2, 3, 4, 5];
// ❌ forEach always returns undefined — can't capture result
let doubled = numbers.forEach(n => n * 2);
console.log(doubled); // undefined ❌
// ✅ Use map() when you need a new array
let doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10] ✅Mistake 3: Mutating the Original with splice When You Wanted slice
let fruits = ["Apple", "Banana", "Mango", "Orange"];
// ❌ splice changes the original!
let result = fruits.splice(1, 2);
console.log(result); // ["Banana", "Mango"]
console.log(fruits); // ["Apple", "Orange"] ← Original modified!
// ✅ Use slice to extract without modifying
let result = fruits.slice(1, 3);
console.log(result); // ["Banana", "Mango"]
console.log(fruits); // ["Apple", "Banana", "Mango", "Orange"] ✅Mistake 4: Using find When You Need All Matches
let scores = [82, 91, 78, 88, 95];
// ❌ find only returns the FIRST match
let highScorer = scores.find(s => s >= 85);
console.log(highScorer); // 91 (first only!) ❌
// ✅ Use filter to get ALL matches
let highScorers = scores.filter(s => s >= 85);
console.log(highScorers); // [91, 88, 95] ✅Practical Exercise
Create a file called arrays.js:
// 🎯 Arrays Practice
// 1. Build and manipulate an array
console.log("=== 🛒 Shopping Cart ===");
let cart = [];
// Add items
cart.push({ name: "Laptop", price: 55000, qty: 1 });
cart.push({ name: "Mouse", price: 800, qty: 2 });
cart.push({ name: "Keyboard", price: 1500, qty: 1 });
cart.push({ name: "Monitor", price: 18000, qty: 1 });
console.log(`Items in cart: ${cart.length}`);
// Remove last item
let removed = cart.pop();
console.log(`Removed: ${removed.name}`);
// Total
let total = cart.reduce((sum, item) => sum + item.price * item.qty, 0);
console.log(`Cart Total: ₹${total.toLocaleString()}`);
// 2. Student analysis
console.log("\n=== 📊 Student Analysis ===");
let students = [
{ name: "Mihir", marks: 92, dept: "CS" },
{ name: "Priya", marks: 85, dept: "IT" },
{ name: "Rahul", marks: 55, dept: "CS" },
{ name: "Sara", marks: 95, dept: "IT" },
{ name: "Arjun", marks: 72, dept: "CS" },
{ name: "Neha", marks: 38, dept: "IT" },
];
let passed = students.filter(s => s.marks >= 60);
let failed = students.filter(s => s.marks < 60);
let csStudents = students.filter(s => s.dept === "CS");
let avgMarks = (students.reduce((s, st) => s + st.marks, 0) / students.length).toFixed(1);
let topper = students.reduce((max, s) => s.marks > max.marks ? s : max);
console.log(`Total: ${students.length} students`);
console.log(`Passed: ${passed.length} (${passed.map(s => s.name).join(", ")})`);
console.log(`Failed: ${failed.length} (${failed.map(s => s.name).join(", ")})`);
console.log(`CS Dept: ${csStudents.map(s => s.name).join(", ")}`);
console.log(`Average: ${avgMarks} marks`);
console.log(`Topper: ${topper.name} with ${topper.marks} marks 🏆`);
// 3. Array utilities
console.log("\n=== 🛠️ Array Utilities ===");
let numbers = [5, 3, 8, 1, 9, 2, 7, 4, 6, 10];
console.log(`Original: ${numbers.join(", ")}`);
console.log(`Sorted ↑: ${[...numbers].sort((a, b) => a - b).join(", ")}`);
console.log(`Sorted ↓: ${[...numbers].sort((a, b) => b - a).join(", ")}`);
console.log(`Sum: ${numbers.reduce((s, n) => s + n, 0)}`);
console.log(`Max: ${Math.max(...numbers)}`);
console.log(`Min: ${Math.min(...numbers)}`);
console.log(`Evens: ${numbers.filter(n => n % 2 === 0).join(", ")}`);
console.log(`Odds: ${numbers.filter(n => n % 2 !== 0).join(", ")}`);Run it:
node arrays.jsExpected Output:
=== 🛒 Shopping Cart ===
Items in cart: 4
Removed: Monitor
Cart Total: ₹57,100
=== 📊 Student Analysis ===
Total: 6 students
Passed: 4 (Mihir, Priya, Sara, Arjun)
Failed: 2 (Rahul, Neha)
CS Dept: Mihir, Rahul, Arjun
Average: 72.8 marks
Topper: Sara with 95 marks 🏆
=== 🛠️ Array Utilities ===
Original: 5, 3, 8, 1, 9, 2, 7, 4, 6, 10
Sorted ↑: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Sorted ↓: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
Sum: 55
Max: 10
Min: 1
Evens: 8, 2, 4, 6, 10
Odds: 5, 3, 1, 9, 7Key Takeaways
Congratulations! 🎉 You now have a complete toolkit for working with arrays in JavaScript.
✅ Arrays store ordered collections of values — indexed from 0.
✅ Adding/Removing:
push()/pop()→ end of arrayunshift()/shift()→ beginning of arraysplice()→ anywhere (mutates original)
✅ Extracting: slice() — returns a copy, never mutates original.
✅ Searching: find() → first match. filter() → all matches. includes() → true/false.
✅ Transforming: map() → new array. filter() → new filtered array. reduce() → single value.
✅ Sorting: Always use (a, b) => a - b for numbers — default sort treats them as strings.
✅ Mutating vs Non-Mutating — know which methods change the original and which return a copy.
Best Practices
- ✅ Use
map(),filter(),reduce()over manualforloops for transformations - ✅ Always use a compare function
(a, b) => a - bwhen sorting numbers - ✅ Use
slice()to copy — neversplice()when you don't want to mutate - ✅ Use
[...arr]orarr.slice()to clone before sorting to preserve original - ✅ Use
find()for one match,filter()for all matches - ✅ Use
Array.isArray()to safely check if a value is an array - ✅ Use
Array.from({ length: n }, (_, i) => i)to generate ranges - ✅ Use
includes()instead ofindexOf() !== -1— reads more naturally
What's Next?
Great work! 🎉 You now have a solid foundation with arrays and all their built-in methods.
Next up, let's put arrays and loops together in practice:
Loops with Arrays → — combining loops and arrays to solve real problems like searching, transforming, building, and processing collections of data!
Let's keep going! 💪