Skip to main content

Command Palette

Search for a command to run...

Day 3: Arrays & Loops (JavaScript Basics)

Understand arrays, their methods, and how to loop through them efficiently.

Published
10 min read
A

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.

ActionMethodMemory Trick
Add at endpush()Push into the cupboard
Remove lastpop()Pop it out to eat
Add at startunshift()Shove to the front
Remove firstshift()Slide the first out
Find if existsincludes("Mango")Check if fruit is inside
Find positionindexOf("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 basketLike slicing a piece of cake you take some but the rest stays❌ No
Remove or replacesplice(start, count, ...newItems)Removes or replaces fruits inside the basketLike doing surgery on your basket✅ Yes
Join two basketsconcat(array2)Combines two or more baskets into oneLike pouring fruits into a bigger basket❌ No
Spread everything[...array1, ...array2]Copies fruits from multiple baskets using spread syntaxLike 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 loopfor (let i = 0; i < fruits.length; i++)Runs from start to end using an index counterClassic shop assistant counting shelf by shelf
for...offor (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 fruitModern intern following your instructions
whilewhile (condition)Keeps looping while the condition is trueAssistant who works until you say “stop”
do...whiledo {...} while (condition)Runs at least once, then checks conditionAssistant 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

KeywordWhat It DoesExample Idea
breakStops the loop completelyStop selling once you reach “Mango”
continueSkips current item, continues nextSkip 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

GoalBest Loop
Fixed number of timesfor
Go through list directlyfor...of
Cleaner one-line operationforEach()
Repeat based on conditionwhile
Run at least oncedo...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.

ActionMethodWhat It DoesExample Result
Transform allmap()Create new array with changed items["Apple Juice", "Banana Juice"]
Filter somefilter()Keep only items that match["Mango"]
Combine allreduce()Return a single total value100
Find onefind()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

DetailExplanation
PurposeSorts 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

DetailExplanation
PurposeReverses 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

DetailExplanation
PurposeCombines 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

DetailExplanation
PurposeSplits 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

  1. Print every fruit in the array using a loop.

  2. Print only fruits that start with the letter M.

  3. Count how many fruits are in the basket (without using .length).

  4. Reverse the array manually (don’t use .reverse()).

  5. Combine two fruit baskets into one new array.

  6. Find the fruit with the longest name.

  7. Find the fruit with the shortest name.

  8. Check if "Kiwi" exists in the basket.

  9. Remove the first and last fruit using array methods.

  10. Add "Pineapple" at the beginning and "Papaya" at the end.

  11. Copy only the middle two fruits using slice().

  12. Replace "Banana" with "Guava" using splice().

  13. Create a string of all fruits separated by commas using join().

  14. Split "Apple, Banana, Mango" back into an array.

  15. Sort fruits alphabetically and then reverse the order.

  16. Create a new array of fruits with " Juice" added to each name.

  17. Create a new array of fruits that start with A or B.

  18. Count total number of letters in all fruit names combined.

  19. Find the first fruit that starts with "O".

  20. 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 🚀