JavaScript Arrays 101
When writing programs in JavaScript, we often need to store multiple values together.
For example:
A list of favorite movies
A list of student marks
A list of tasks
Instead of creating many variables, JavaScript provides arrays to store collections of values efficiently.
What Are Arrays?
An array is a collection of values stored in a specific order.
Example:
let fruits = ["Apple", "Banana", "Orange"];
Here the array contains three elements:
| Index | Value |
|---|---|
| 0 | Apple |
| 1 | Banana |
| 2 | Orange |
Important point:
⚠️ Array indexing starts from 0.
Why We Need Arrays
Imagine storing fruit names using separate variables.
let fruit1 = "Apple";
let fruit2 = "Banana";
let fruit3 = "Orange";
This works, but managing many variables becomes difficult.
Using an array is much easier:
let fruits = ["Apple", "Banana", "Orange"];
Now all values are stored in one structure.
How to Create an Array
Arrays are created using square brackets [ ].
Example:
let numbers = [10, 20, 30, 40];
You can store different types of values:
let data = ["Viral", 22, true];
But usually arrays store similar types of data.
Accessing Elements Using Index
Each array element has an index position.
Example:
let fruits = ["Apple", "Banana", "Orange"];
console.log(fruits[0]);
Output:
Apple
Access second element:
console.log(fruits[1]);
Output:
Banana
Updating Array Elements
Array values can be changed using their index.
Example:
let fruits = ["Apple", "Banana", "Orange"];
fruits[1] = "Mango";
console.log(fruits);
Output:
["Apple", "Mango", "Orange"]
Here Banana was replaced by Mango.
Array Length Property
The .length property tells us how many elements are in the array.
Example:
let fruits = ["Apple", "Banana", "Orange"];
console.log(fruits.length);
Output:
3
This is very useful when working with loops.
Looping Over Arrays
To access all elements, we usually use a loop.
Example using a for loop:
let fruits = ["Apple", "Banana", "Orange"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Output:
Apple
Banana
Orange
The loop runs once for each element in the array.
Visual Representation of an Array
Example array:
let fruits = ["Apple", "Banana", "Orange"];
Visual structure:
Index → 0 1 2
-------------------------
Value → Apple Banana Orange
Each value is stored at a specific index position.
Assignment Practice
1️⃣ Create an Array of Favorite Movies
let movies = [
"Inception",
"Interstellar",
"Avengers",
"Batman",
"Joker"
];
2️⃣ Print First and Last Element
console.log(movies[0]);
console.log(movies[movies.length - 1]);
3️⃣ Change One Value
movies[2] = "Spider-Man";
console.log(movies);
4️⃣ Loop Through the Array
for (let i = 0; i < movies.length; i++) {
console.log(movies[i]);
}