Skip to main content

Command Palette

Search for a command to run...

JavaScript Arrays 101

Updated
β€’3 min read
JavaScript Arrays 101

πŸ“Œ What Are Arrays and Why Do We Need Them?

Imagine you want to store:

🍎 Apple
🍌 Banana
πŸ₯­ Mango
πŸ‡ Grapes

If you store them separately:

let fruit1 = "Apple";
let fruit2 = "Banana";
let fruit3 = "Mango";
let fruit4 = "Grapes";

This becomes messy.

Instead, we use an array:

let fruits = ["Apple", "Banana", "Mango", "Grapes"];

πŸ‘‰ An array is a collection of values stored in order.


πŸ“¦ Why Arrays Are Needed

βœ” Store multiple values in one variable

βœ” Easy to manage lists

βœ” Easy to loop through

βœ” Used everywhere (APIs, databases, projects)


πŸ“Œ How to Create an Array

let numbers = [10, 20, 30, 40];

Structure:

let arrayName = [value1, value2, value3];

πŸ”’ Accessing Elements Using Index

Arrays use index numbers.

⚠ Important: Index starts from 0

let fruits = ["Apple", "Banana", "Mango"];
Index Value
0 Apple
1 Banana
2 Mango

Example

console.log(fruits[0]);  // Apple
console.log(fruits[2]);  // Mango

πŸ”„ Updating Elements

You can change values using index.

fruits[1] = "Orange";
console.log(fruits);

Before:

["Apple", "Banana", "Mango"]

After:

["Apple", "Orange", "Mango"]

πŸ“ Array Length Property

To check how many elements:

console.log(fruits.length);

Output:

3

Length is very useful in loops.


πŸ” Basic Looping Over Arrays

Using for loop

let fruits = ["Apple", "Banana", "Mango"];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

Output:

Apple
Banana
Mango

This loop:

  1. Starts from index 0

  2. Continues until length

  3. Prints each value


πŸ†š Individual Variables vs Array

❌ Without Array

let mark1 = 80;
let mark2 = 75;
let mark3 = 90;

Hard to manage.


βœ… With Array

let marks = [80, 75, 90];

Clean and organized.


πŸŽ“ Assignment Practice

1️⃣ Create an Array of 5 Favorite Movies

let movies = ["Inception", "Interstellar", "KGF", "3 Idiots", "Avengers"];

2️⃣ Print First and Last Element

console.log(movies[0]);  // First
console.log(movies[movies.length - 1]);  // Last

3️⃣ Change One Value

movies[2] = "Bahubali";
console.log(movies);

4️⃣ Loop Through the Array

for (let i = 0; i < movies.length; i++) {
  console.log(movies[i]);
}

πŸ“Š Diagram Ideas

πŸ”Ή Visual Representation of Array Index

Index:   0        1        2        3
         --------------------------------
Value: | Apple | Banana | Mango | Grapes |
         --------------------------------

πŸ”Ή Memory-Style Block Diagram

fruits
   ↓
[0] β†’ Apple
[1] β†’ Banana
[2] β†’ Mango
[3] β†’ Grapes

🌟 Final Understanding

  • Array = ordered collection of values

  • Index starts from 0

  • Access using array[index]

  • Can update values

  • length gives total elements

  • Use loops to print all elements