Nine days into this 30-day JavaScript sprint and the momentum is real. Yesterday's dive into objects made me appreciate how flexible the language can be. Today I’m keeping that curiosity going and turning the spotlight on arrays—a data structure you’ll touch in almost every front-end or back-end task. Let’s break them down with a practical, developer-first mindset.
📚 Today's Learning Objectives
- Explore the different ways to create arrays and how they behave
- Practice adding, removing, and updating array elements
- Get comfortable with the most useful iteration and transformation methods
- Embrace modern ES6+ array features that show up in everyday code
🧱 Array Fundamentals
An array is an ordered list of elements indexed from zero. Because JavaScript is dynamically typed, those elements can be of mixed types without any complaints.
let mixedArray = ["JavaScript", 30, true, { framework: "React" }];
console.log(mixedArray[0]); // "JavaScript"
console.log(mixedArray.length); // 4
Common Ways to Create Arrays
// 1. Literal syntax (most common)
let fruits = ["Apple", "Banana", "Orange"];
// 2. Array constructor
let numbers = new Array(10); // Creates an array with length 10, full of empty slots
let colors = new Array("Red", "Green", "Blue");
// 3. Array.of and Array.from
let scores = Array.of(90, 85, 88);
let chars = Array.from("JavaScript"); // ["J", "a", "v", ...]
Tip: Stick with literals unless you have a specific reason not to. The syntax is clearer and avoids the “single argument turns into empty array” trap.
✏️ Adding, Removing, and Updating Items
Adding Elements
let todoList = ["Write code", "Read docs"];
// push: add to the end, returns new length
todoList.push("Practice algorithms"); // ["Write code", "Read docs", "Practice algorithms"]
// unshift: add to the beginning
todoList.unshift("Check email"); // ["Check email", "Write code", "Read docs", "Practice algorithms"]
// splice: insert at a specific position
todoList.splice(2, 0, "Make coffee");
// ["Check email", "Write code", "Make coffee", "Read docs", "Practice algorithms"]
Removing Elements
// pop: remove from the end
let lastTask = todoList.pop(); // "Practice algorithms"
// shift: remove from the beginning
let firstTask = todoList.shift(); // "Check email"
// splice: remove at a specific position
todoList.splice(1, 1); // Removes the element at index 1
Updating & Querying
todoList[0] = "Keep coding"; // Direct assignment
console.log(todoList.indexOf("Read docs")); // Returns the index
console.log(todoList.includes("Make coffee")); // true/false
🔁 Ways to Iterate
Classic Loops
let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
for (let item of numbers) {
console.log(item);
}
forEach: Straightforward Iteration
numbers.forEach((number, index) => {
console.log(`Index ${index}: Value ${number}`);
});
Heads-up:
forEachalways runs the entire loop and doesn’t return a new array. If you want to transform values, reach formap.
🔍 Core Transformation Methods
map: Turn One Array into Another
let prices = [99, 199, 299];
let withTax = prices.map((price) => (price * 1.1).toFixed(2));
// ["108.90", "218.90", "328.90"]
filter: Keep What You Need
let students = [
{ name: "Mia", score: 95 },
{ name: "Noah", score: 82 },
{ name: "Liam", score: 68 },
];
let highScores = students.filter((student) => student.score >= 85);
// [{ name: "Mia", score: 95 }]
reduce: Roll Everything Up
let totalScore = students.reduce((sum, student) => sum + student.score, 0);
console.log(totalScore); // 245
let grouped = students.reduce(
(acc, student) => {
if (student.score >= 90) acc.A.push(student);
else if (student.score >= 80) acc.B.push(student);
else acc.C.push(student);
return acc;
},
{ A: [], B: [], C: [] }
);
console.log(grouped);
find / findIndex / some / every
let target = students.find((student) => student.name === "Noah");
let targetIndex = students.findIndex((student) => student.score < 70);
let hasTop = students.some((student) => student.score >= 90); // true
let allPass = students.every((student) => student.score >= 60); // true
🔄 Copying and Merging Arrays
Spread Operator
let frontend = ["HTML", "CSS"];
let backend = ["Node.js", "Express"];
let fullStack = [...frontend, "JavaScript", ...backend];
console.log(fullStack);
// ["HTML", "CSS", "JavaScript", "Node.js", "Express"]
let clonedStack = [...fullStack]; // Shallow copy
concat: Reliable Classic
let combined = frontend.concat(backend);
console.log(combined);
Spread reads nicer most of the time, but
concatshines when chaining or when you want to avoid accidentally mutating the original arrays.
✂️ Slicing, Splicing, Filling
let numbers = [1, 2, 3, 4, 5];
// slice: non-destructive, great for copying segments
let part = numbers.slice(1, 4); // [2, 3, 4]
// splice: destructive
let removed = numbers.splice(2, 2, 30, 40); // removed => [3, 4]
console.log(numbers); // [1, 2, 30, 40, 5]
// fill: quick initialization
let grid = new Array(5).fill(0); // [0, 0, 0, 0, 0]
grid.fill(1, 1, 4); // [0, 1, 1, 1, 0]
🧩 Multidimensional Arrays and Flattening
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
console.log(matrix[1][2]); // 6
// flat: flatten nested arrays
let nested = [1, [2, [3, [4]]]];
console.log(nested.flat(1)); // [1, 2, [3, [4]]]
console.log(nested.flat(2)); // [1, 2, 3, [4]]
console.log(nested.flat(Infinity)); // [1, 2, 3, 4]
🧠 Destructuring and Rest Parameters
let colors = ["Red", "Green", "Blue", "Purple"];
let [primary, secondary, ...others] = colors;
console.log(primary); // "Red"
console.log(others); // ["Blue", "Purple"]
function logTopTwo([first, second]) {
console.log(`Winner: ${first}, Runner-up: ${second}`);
}
logTopTwo(["Alice", "Bob", "Charlie"]);
⚠️ Things to Watch Out For
- Sparse arrays: Avoid skipping indexes—iteration becomes unpredictable.
- Reference behavior: Arrays are objects; copying them usually creates shallow references.
- Performance: Frequent insertions/removals at the front can be costly; consider rearranging logic if speed matters.
- Immutability: In frameworks like React, prefer methods that return new arrays rather than mutating existing ones.
📝 Practice Time
Exercise 1: Shopping Cart Discount
let cart = [
{ id: 1, name: "Keyboard", price: 299, quantity: 1 },
{ id: 2, name: "Mouse", price: 129, quantity: 2 },
{ id: 3, name: "Headset", price: 399, quantity: 1 },
];
function getCartSummary(items, discountPercent = 0) {
let subtotal = items.reduce(
(total, item) => total + item.price * item.quantity,
0
);
let discount = subtotal * (discountPercent / 100);
return {
itemCount: items.reduce((count, item) => count + item.quantity, 0),
subtotal,
discount,
total: subtotal - discount,
};
}
console.log(getCartSummary(cart, 10));
Exercise 2: Student Leaderboard
let students = [
{ name: "Mia", score: 92 },
{ name: "Noah", score: 85 },
{ name: "Liam", score: 78 },
{ name: "Ava", score: 96 },
];
function getRankedList(list) {
return [...list]
.sort((a, b) => b.score - a.score)
.map((student, index) => ({
rank: index + 1,
...student,
}));
}
console.log(getRankedList(students));
Exercise 3: Data Cleanup Helper
let rawData = [
" JavaScript ",
"",
"Vue.js",
null,
"React ",
undefined,
" ",
"Node.js",
];
function cleanData(data) {
return data
.filter((item) => typeof item === "string")
.map((item) => item.trim())
.filter((item) => item.length > 0);
}
console.log(cleanData(rawData)); // ["JavaScript", "Vue.js", "React", "Node.js"]
🔍 Key Takeaways
-
Creation: Literals are the default;
Array.of/Array.fromoffer flexible conversions. -
Core operations:
push,pop,shift,unshift,spliceshould feel automatic. -
Iteration & transformation: Know when to use
forEach,map,filter,reduce,find. -
Structural helpers:
spread,slice,concat,flatkeep data flows tidy. - Modern patterns: Destructuring and rest parameters make array handling more expressive.
📚 Tomorrow's Preview
Tomorrow I’ll zoom in on advanced array patterns and real-world techniques, including:
- Immutable update strategies that play nicely with modern frameworks
- Several ways to squeeze power out of
reduce - Designing data pipelines with method chaining
- Combining objects and arrays to build practical data models
💡 Learning Tips
- Practice aggressively: Try every add/remove method yourself—feel the difference between mutating and returning new arrays.
- Keep MDN open: The official docs are gold for method signatures and browser support.
- Apply to real projects: Extend these exercises into your side projects—shopping carts, todo apps, dashboards.
- Think before mutating: Make a habit of asking “Do I need to mutate or return a new array?” before touching the data.
That wraps Day 9. Thanks for sticking with the grind—see you tomorrow for more array wizardry.
Top comments (0)