Concept Explanation
An Array is a ordered list of items. But in JavaScript, arrays are "Dynamic" — they can shrink, grow, and hold many different types of data at the same time.
Commonly, we use Higher Order Methods like map and filter instead of old-fashioned for loops to transform data elegantly.
Syntax or Core Structure
Modern Array Methods
const nums = [1, 2, 3, 4, 5];
// 1. Map (Transform every item)
const doubled = nums.map(n => n * 2); // [2, 4, 6, 8, 10]
// 2. Filter (Keep only certain items)
const evens = nums.filter(n => n % 2 === 0); // [2, 4]
// 3. Find (Get the first match)
const special = nums.find(n => n > 3); // 4
Real World Example
A Shopping Cart:
items: Array of objects[{name: "Apple", price: 1}, ...]- Use
.filter()to remove an item. - Use
.reduce()to calculate the total price of everything. - Use
.sort()to show the cheapest items first.
Common Mistakes
- Modifying Original: Methods like
.sort()and.reverse()change the original array. If you want to keep the original, copy it first using[...arr]. - Length Confusion: Setting
array.length = 0completely wipes the array. This is a common but dangerous trick. - Sparse Arrays: Deleting an item with
delete arr[1]leaves a "hole" (empty) in the array. Always use.splice()or.filter()instead.
Practice Exercises
- The Filter Lab: Create an array of 20 random numbers. Filter out only the numbers divisible by 5.
- The Object Array: Create an array of "Users" (objects with
nameandage). Use.map()to create an array containing just their names. - The Sorter: Sort an array of words alphabetically, but in reverse (Z to A).