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:
Starts from index 0
Continues until length
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

