Day 3: Arrays & Loops (JavaScript Basics)
Understand arrays, their methods, and how to loop through them efficiently.
Here’s a clean non-bullet, blog-friendly “About Me” for your Hashnode page: I’m a Frontend Developer based in Pune with experience in Angular, TypeScript, JavaScript, HTML, and CSS. I enjoy building clean, scalable interfaces and working on products like dashboards, ERP systems, and B2B platforms. My focus is on writing maintainable code, improving performance, and creating user-friendly experiences. I also explore concepts around UI architecture, component patterns, and frontend best practices, which I document and share through my blogs. My goal is to create helpful, practical content for developers who are learning and building real-world projects.
Arrays :
An array stores multiple values in a single variable.
Imagine you have a cupboard with numbered shelves.
Each shelf holds one thing an apple, a banana, or even your favourite bug report.
const cupboard = ["Apple", "Banana", "Mango"];
Here:
The cupboard’s name is
cupboard.The shelves start at
0(JavaScript likes counting like a toddler: “zero, one, two…”).cupboard[0]opens the first shelf →"Apple".
Your array is basically a queue of items waiting for your commands.
| Action | Method | Memory Trick |
| Add at end | push() | Push into the cupboard |
| Remove last | pop() | Pop it out to eat |
| Add at start | unshift() | Shove to the front |
| Remove first | shift() | Slide the first out |
| Find if exists | includes("Mango") | Check if fruit is inside |
| Find position | indexOf("Banana") | “Which shelf is Banana on?” |
let fruits = ["Apple", "Banana", "Mango"];
fruits.push("Orange"); // Add at end
fruits.pop(); // Remove last
fruits.unshift("Pineapple"); // Add at start
fruits.shift(); // Remove first
console.log(fruits); // ["Apple", "Banana", "Mango"]
console.log(fruits.includes("Mango")); // true
console.log(fruits.indexOf("Banana")); // 1
🍓 Array Slice, Splice, Concat & Spread — Cutting and Mixing Fruits
You’ve got multiple baskets in your fruit shop sometimes you take a few fruits out, sometimes you mix baskets together.
That’s exactly what these methods help you do.
| 🍉 Action | 🧰 Method | 💬 What It Does | 🧠 Memory Trick | ⚙️ Changes Original Array? |
| Take a portion (copy) | slice(start, end) | Copies a section of the basket into a new basket | Like slicing a piece of cake you take some but the rest stays | ❌ No |
| Remove or replace | splice(start, count, ...newItems) | Removes or replaces fruits inside the basket | Like doing surgery on your basket | ✅ Yes |
| Join two baskets | concat(array2) | Combines two or more baskets into one | Like pouring fruits into a bigger basket | ❌ No |
| Spread everything | [...array1, ...array2] | Copies fruits from multiple baskets using spread syntax | Like spilling both baskets into a new one | ❌ No |
🍍 Code Example
// 🍎 Original baskets
let basket1 = ["Apple", "Banana", "Mango"];
let basket2 = ["Orange", "Kiwi"];
// 🍰 slice() — take a copy portion
let fewFruits = basket1.slice(1, 3);
console.log("Sliced Portion:", fewFruits);
// ["Banana", "Mango"]
console.log("After slice:", basket1);
// ["Apple", "Banana", "Mango"]
// 🔪 splice() — remove or replace inside
basket1.splice(1, 1, "Pineapple");
console.log("After splice:", basket1);
// ["Apple", "Pineapple", "Mango"]
// 🧺 concat() — merge baskets
let combined = basket1.concat(basket2);
console.log("After concat:", combined);
// ["Apple", "Pineapple", "Mango", "Orange", "Kiwi"]
// ✨ spread (...) — merge the modern way
let spreadCombined = [...basket1, ...basket2, "Strawberry"];
console.log("After spread:", spreadCombined);
// ["Apple", "Pineapple", "Mango", "Orange", "Kiwi", "Strawberry"]
Loops :
A loop is a repeater.
It lets you run the same block of code multiple times automatically until a condition tells it to stop.
Think of a loop as your fruit shop assistant 🍊
who checks every shelf in your cupboard so you don’t have to repeat the same work manually.
🧺 Example Basket
let fruits = ["Apple", "Banana", "Mango", "Orange"];
Without a loop, you’d have to do:
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
console.log(fruits[3]);
Boring, right?
So let’s automate it!
🧠 Types of Loops in JavaScript
| 🔢 Loop Type | 💻 Syntax Example | 💬 What It Does | 🪄 Memory Trick |
| for loop | for (let i = 0; i < fruits.length; i++) | Runs from start to end using an index counter | Classic shop assistant counting shelf by shelf |
| for...of | for (let fruit of fruits) | Goes through each fruit directly (no index needed) | Polite assistant who handles every fruit by name |
| forEach() | fruits.forEach(fruit => {...}) | Executes a function once for every fruit | Modern intern following your instructions |
| while | while (condition) | Keeps looping while the condition is true | Assistant who works until you say “stop” |
| do...while | do {...} while (condition) | Runs at least once, then checks condition | Assistant who acts first, thinks later 😄 |
🍏 1️⃣ for loop
Your assistant counts every shelf manually.
let fruits = ["Apple", "Banana", "Mango", "Orange"];
for (let i = 0; i < fruits.length; i++) {
console.log("Fruit on shelf", i, "is", fruits[i]);
}
// Output:
// Fruit on shelf 0 is Apple
// Fruit on shelf 1 is Banana
// Fruit on shelf 2 is Mango
// Fruit on shelf 3 is Orange
🍌 2️⃣ for...of loop
The polite version — ignores shelf numbers, just handles fruits directly.
let fruits = ["Apple", "Banana", "Mango", "Orange"];
for (let fruit of fruits) {
console.log("Selling:", fruit);
}
// Output:
// Selling: Apple
// Selling: Banana
// Selling: Mango
// Selling: Orange
🍓 3️⃣ forEach() loop
The modern way — give one rule, and it runs for each fruit automatically.
let fruits = ["Apple", "Banana", "Mango", "Orange"];
fruits.forEach(fruit => console.log("Packing:", fruit));
// Output:
// Packing: Apple
// Packing: Banana
// Packing: Mango
// Packing: Orange
🍍 4️⃣ while loop
Keeps going as long as a condition stays true.
let fruits = ["Apple", "Banana", "Mango", "Orange"];
let i = 0;
while (i < fruits.length) {
console.log("Checking:", fruits[i]);
i++;
}
//Output:
//Checking: Apple
//Checking: Banana
//Checking: Mango
//Checking: Orange
🍇 5️⃣ do...while loop
Runs at least once, even if the condition is false.
let fruits = ["Apple", "Banana", "Mango", "Orange"];
let j = 0;
do {
console.log("Fruit:", fruits[j]);
j++;
} while (j < fruits.length);
// Output:
// Fruit: Apple
// Fruit: Banana
// Fruit: Mango
// Fruit: Orange
✋ Special Keywords: break & continue
| Keyword | What It Does | Example Idea |
break | Stops the loop completely | Stop selling once you reach “Mango” |
continue | Skips current item, continues next | Skip spoiled “Banana” but keep looping |
Example:
let fruits = ["Apple", "Banana", "Mango", "Orange"];
for (let fruit of fruits) {
if (fruit === "Banana") continue; // skip banana
if (fruit === "Mango") break; // stop at mango
console.log(fruit);
}
// Output:
// Apple
🍒 When to Use Which
| Goal | Best Loop |
| Fixed number of times | for |
| Go through list directly | for...of |
| Cleaner one-line operation | forEach() |
| Repeat based on condition | while |
| Run at least once | do...while |
🤖 Smart Loops — map(), filter(), reduce(), find()
These are built-in array methods that act like loops but with shorter, cleaner, and smarter syntax.
They help you transform, filter, or summarise data all without writing manual loops.
| Action | Method | What It Does | Example Result |
| Transform all | map() | Create new array with changed items | ["Apple Juice", "Banana Juice"] |
| Filter some | filter() | Keep only items that match | ["Mango"] |
| Combine all | reduce() | Return a single total value | 100 |
| Find one | find() | Return first matching item | "Mango" |
🍏 1️⃣ map() — Transform Every Fruit
Creates a new array by applying a function to every item.
let juices = fruits.map(fruit => fruit + " Juice");
console.log(juices);
// ["Apple Juice", "Banana Juice", "Mango Juice", "Orange Juice"]
🍌 2️⃣ filter() — Keep Only the Good Ones
Creates a new array with only elements that pass a test.
let selected = fruits.filter(fruit => fruit.startsWith("M"));
console.log(selected);
// ["Mango"]
🍓 3️⃣ reduce() — Combine Everything into One
Reduces the array to a single value (like sum, total, etc.)
let numbers = [10, 20, 30, 40];
let total = numbers.reduce((sum, num) => sum + num, 0);
console.log(total);
// 100
🍍 4️⃣ find() — Find the First Match
Returns the first element that passes a condition.
let found = fruits.find(fruit => fruit === "Mango");
console.log(found);
// "Mango"
🍇 Sorting & Rearranging Arrays
Let’s keep our fruit basket theme going 🍎
let fruits = ["Mango", "Apple", "Banana", "Orange"];
🍏 1️⃣ sort() — Arrange in Order
| Detail | Explanation |
| Purpose | Sorts array items alphabetically or numerically (ascending by default). |
| Changes original array? | ✅ Yes |
| Memory Trick | “Arrange fruits neatly on the shelf A → Z.” |
fruits.sort();
console.log(fruits);
// ["Apple", "Banana", "Mango", "Orange"]
🍊 2️⃣ reverse() — Flip the Order
| Detail | Explanation |
| Purpose | Reverses the order of elements in the array. |
| Changes original array? | ✅ Yes |
| Memory Trick | “Flip the basket upside down.” 😄 |
fruits.reverse();
console.log(fruits);
// ["Orange", "Mango", "Banana", "Apple"]
🍓 3️⃣ join() — Turn into a String
| Detail | Explanation |
| Purpose | Combines all array items into one string. |
| Changes original array? | ❌ No |
| Memory Trick | “Join all fruit names to print the fruit list.” 🧾 |
let fruitString = fruits.join(", ");
console.log(fruitString);
// "Orange, Mango, Banana, Apple"
🍍 4️⃣ split() — Turn String into Array
| Detail | Explanation |
| Purpose | Splits a string into an array (opposite of join). |
| Changes original array? | ❌ No |
| Memory Trick | “Cut a fruit list string back into individual fruits.” ✂️ |
let newBasket = fruitString.split(", ");
console.log(newBasket);
// ["Orange", "Mango", "Banana", "Apple"]
🍇 5️⃣ sort() with Numbers (Custom Function)
sort() doesn’t sort numbers correctly by default (it treats them as text).
To sort numbers properly, use a custom function:
let prices = [50, 5, 20, 100];
prices.sort((a, b) => a - b);
console.log(prices);
// [5, 20, 50, 100]
🧠 Array & Loop Practice Questions
Print every fruit in the array using a loop.
Print only fruits that start with the letter M.
Count how many fruits are in the basket (without using
.length).Reverse the array manually (don’t use
.reverse()).Combine two fruit baskets into one new array.
Find the fruit with the longest name.
Find the fruit with the shortest name.
Check if
"Kiwi"exists in the basket.Remove the first and last fruit using array methods.
Add
"Pineapple"at the beginning and"Papaya"at the end.Copy only the middle two fruits using
slice().Replace
"Banana"with"Guava"usingsplice().Create a string of all fruits separated by commas using
join().Split
"Apple, Banana, Mango"back into an array.Sort fruits alphabetically and then reverse the order.
Create a new array of fruits with
" Juice"added to each name.Create a new array of fruits that start with A or B.
Count total number of letters in all fruit names combined.
Find the first fruit that starts with
"O".Stop looping once you find
"Mango"and print only fruits before it.
🍎 Closing Note
And that wraps up Day 3 — Arrays & Loops!
You’ve learned how to store, organize, and move through data effortlessly — from stacking fruits in baskets to looping through them like a pro. These are the real building blocks of logic in JavaScript.
Every time you push, pop, or loop through an array, you’re training your brain to think like a developer step by step, pattern by pattern. Keep practising these challenges until they feel natural, because tomorrow’s JavaScript magic will build right on top of this foundation.
“Next stop: Smart Loops and Advanced Array Methods 🚀”