JavaScript Roadmap — Day 14: Arrays — Complete Guide

 

JavaScript · Day 14 of 180 · Beginner Phase

Arrays — Complete Guide

Arrays are the most used data structure in JavaScript. Every app you build will use them constantly — for lists of products, users, messages, and more. Master arrays and you master data manipulation.

Day 14 / 180
Beginner Phase
🕐 15 min read
💻 8 code examples
🎯 3 practice tasks

Think about every app you use daily:

🛒 Amazon: List of products in your cart
📱 WhatsApp: List of your messages
🎵 Spotify: List of songs in your playlist
👥 LinkedIn: List of your connections

Every single one of those lists is an array. Arrays are how JavaScript stores and manages collections of data. Every real application you will ever build uses arrays constantly — from displaying products to processing API responses to managing state in React. This is one of the most important lessons in the entire roadmap.

1. What is an Array?

An array is an ordered list of values. Unlike variables that store one value — arrays store multiple values in a single container. Each value has an index starting from 0:

JavaScript — Array Basics
// Create an array
const fruits = ["apple", "banana", "mango"];
//               index 0    index 1    index 2

// Arrays can hold any type — even mixed
const mixed = [42, "hello", true, null, [1, 2]];

// Array length
console.log(fruits.length); // 3

// Check if something is an array
console.log(Array.isArray(fruits)); // true
console.log(Array.isArray("hello")); // false

// Real world array
const products = [
  { name: "Shirt",  price: 1500, inStock: true  },
  { name: "Pants",  price: 2500, inStock: false },
  { name: "Shoes",  price: 3500, inStock: true  },
  { name: "Watch",  price: 8000, inStock: true  },
];
console.log(products.length); // 4

2. Access & Update Array Items

Access items using their index number in square brackets. Remember — indexes start at 0 not 1. This is one of the most common beginner mistakes:

JavaScript — Accessing & Updating
const skills = ["HTML", "CSS", "JavaScript", "React"];

// Access by index
console.log(skills[0]); // "HTML"
console.log(skills[2]); // "JavaScript"
console.log(skills[9]); // undefined — doesn't exist

// Last item — two ways
console.log(skills[skills.length - 1]); // "React"
console.log(skills.at(-1));               // "React" ← modern way

// Update an item
skills[1] = "CSS3";
console.log(skills); // ["HTML", "CSS3", "JavaScript", "React"]

// Destructuring — extract multiple values
const [first, second, ...rest] = skills;
console.log(first);  // "HTML"
console.log(second); // "CSS3"
console.log(rest);   // ["JavaScript", "React"]

3. Add & Remove Items

JavaScript has built-in methods to add and remove items from arrays. Some mutate the original array — others return a new one. Knowing which is which prevents bugs:

JavaScript — Add & Remove
const cart = ["Shirt", "Pants"];

// Add to end
cart.push("Shoes");
console.log(cart); // ["Shirt", "Pants", "Shoes"]

// Remove from end
const removed = cart.pop();
console.log(removed); // "Shoes"
console.log(cart);    // ["Shirt", "Pants"]

// Add to beginning
cart.unshift("Hat");
console.log(cart); // ["Hat", "Shirt", "Pants"]

// Remove from beginning
cart.shift();
console.log(cart); // ["Shirt", "Pants"]

// Immutable add — spread operator ✅
const newCart = [...cart, "Watch"];
console.log(cart);    // ["Shirt", "Pants"] ← unchanged
console.log(newCart); // ["Shirt", "Pants", "Watch"]

// Remove by value — filter ✅
const withoutShirt = cart.filter(item => item !== "Shirt");
console.log(withoutShirt); // ["Pants"]

4. map, filter, reduce — The Power Trio 🔥

These three methods are used in every real JavaScript application. They transform, filter, and aggregate array data without mutating the original. If you master these three — you can handle 90% of all data manipulation tasks:

JavaScript — map, filter, reduce
const products = [
  { name: "Shirt", price: 1500, inStock: true  },
  { name: "Pants", price: 2500, inStock: false },
  { name: "Shoes", price: 3500, inStock: true  },
  { name: "Watch", price: 8000, inStock: true  },
];

// map() — transform every item → new array same length
const names = products.map(p => p.name);
console.log(names); // ["Shirt","Pants","Shoes","Watch"]

const discounted = products.map(p => ({
  ...p,
  price: p.price * 0.9  // 10% discount
}));

// filter() — keep items matching condition
const inStock    = products.filter(p => p.inStock);
const affordable = products.filter(p => p.price < 3000);
console.log(inStock.length);    // 3
console.log(affordable.length); // 2

// reduce() — combine all items into one value
const total = products.reduce((sum, p) => sum + p.price, 0);
console.log(`Total: Rs${total}`); // Total: Rs15500

// Chain them together — filter then map
const inStockNames = products
  .filter(p => p.inStock)
  .map(p => p.name);
console.log(inStockNames); // ["Shirt","Shoes","Watch"]

5. find, findIndex, some, every, includes

These methods search arrays and return results or booleans. They are essential for checking data and finding specific items:

JavaScript — Search Methods
const users = [
  { id: 1, name: "Waheed", role: "admin"  },
  { id: 2, name: "Ali",    role: "user"   },
  { id: 3, name: "Sara",   role: "user"   },
];

// find() — first item matching condition
const admin = users.find(u => u.role === "admin");
console.log(admin.name); // "Waheed"

// findIndex() — index of first match
const idx = users.findIndex(u => u.id === 2);
console.log(idx); // 1

// some() — at least one matches?
const hasAdmin = users.some(u => u.role === "admin");
console.log(hasAdmin); // true

// every() — do ALL match?
const allUsers = users.every(u => u.role === "user");
console.log(allUsers); // false — admin exists

// includes() — simple value check
const nums = [1, 2, 3, 4, 5];
console.log(nums.includes(3)); // true
console.log(nums.includes(9)); // false
Pro Tip #1 — map always returns same length
map() always returns a new array with the same number of items as the original — just transformed. If you want to reduce the count use filter(). If you want to count or sum use reduce(). Using the wrong one is a very common mistake.
Pro Tip #2 — Chain filter then map
The most powerful pattern in real apps is chaining — .filter() first to reduce the array, then .map() to transform. This is exactly how React components process API data before rendering. Get comfortable with this pattern early.
Pro Tip #3 — Prefer immutable operations
In modern JavaScript — especially React — prefer methods that return new arrays over methods that mutate. Use spread ([...arr, item]) instead of push(). Use filter() instead of splice(). Immutable code prevents a massive category of bugs.

6. sort & reverse — Ordering Arrays

Sorting arrays is a very common operation — sorting products by price, users by name, dates by newest first. JavaScript's sort() has a surprising default behavior you need to know:

JavaScript — sort & reverse
// Default sort — alphabetical (converts to string!)
const nums = [10, 2, 30, 5, 100];
console.log(nums.sort()); // [10, 100, 2, 30, 5] ← WRONG!

// Correct numeric sort
console.log(nums.sort((a, b) => a - b)); // [2, 5, 10, 30, 100] ✅
console.log(nums.sort((a, b) => b - a)); // [100, 30, 10, 5, 2] descending

// Sort strings alphabetically
const names = ["Sara", "Ali", "Waheed", "Bilal"];
names.sort();
console.log(names); // ["Ali","Bilal","Sara","Waheed"]

// Sort objects by property
const products = [
  { name: "Watch", price: 8000 },
  { name: "Shirt", price: 1500 },
  { name: "Shoes", price: 3500 },
];
products.sort((a, b) => a.price - b.price);
console.log(products.map(p => p.name));
// ["Shirt", "Shoes", "Watch"] — cheapest first

// reverse() — flip array order
const arr = [1, 2, 3, 4, 5];
console.log([...arr].reverse()); // [5, 4, 3, 2, 1]

7. Spread, Rest & flat — Modern Array Tools

These modern ES6+ features make working with arrays clean and expressive. You will use spread every day in React:

JavaScript — Spread, Rest & flat
// Spread — copy and combine arrays
const frontend = ["HTML", "CSS", "JavaScript"];
const backend  = ["Node.js", "MongoDB"];

const fullStack = [...frontend, ...backend];
console.log(fullStack);
// ["HTML","CSS","JavaScript","Node.js","MongoDB"]

// Copy array — prevents mutation
const copy = [...frontend];
copy.push("React");
console.log(frontend); // unchanged ✅
console.log(copy);     // ["HTML","CSS","JavaScript","React"]

// flat() — flatten nested arrays
const nested = [[1, 2], [3, 4], [5, 6]];
console.log(nested.flat()); // [1, 2, 3, 4, 5, 6]

// Array.from() — create array from anything
const fromString = Array.from("Waheed");
console.log(fromString); // ["W","a","h","e","e","d"]

const range = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(range); // [1, 2, 3, 4, 5]

8. Try It Yourself

Edit the code and click Run Code. Try chaining methods together and see the power of array manipulation!

✏️ Try it Yourself — Arrays
OUTPUT
// Click Run Code to see output
💡 Edit the code and click Run!

9. Practice Tasks

Task 1 — Easy: Student Grades

Create an array of 5 students with name and marks. Use map() to add a grade property to each (A+ above 90, A above 80, B above 70, else C). Use filter() to get only passing students (marks above 50). Log both results.

Task 2 — Medium: Shopping Cart Manager

Build a cart array with 5 products (name, price, quantity). Use reduce() to calculate total bill. Use filter() to remove out of stock items. Use sort() to order by price. Use find() to locate a specific item by name. Log all results.

Task 3 — Hard: Data Pipeline

You have an API response — array of 10 users with name, age, city, salary, isActive. Write a single chained expression that: filters active users only, filters users with salary above 50000, maps to extract just name and salary, sorts by salary descending, and returns the top 3. This is exactly how real React apps process API data.

Next Lesson
Day 15 — Objects — Complete Guide
View Full Roadmap →
Enjoying this roadmap?
Follow Muhammad Waheed Asghar for daily JavaScript tips and updates!

Popular Posts