JavaScript Arrays 101

What Are Arrays and Why Do We Need Them?
Imagine you want to store your 5 favorite movies.
Without arrays, you might do something like this:
const movie1 = "Inception";
const movie2 = "Interstellar";
const movie3 = "Avatar";
const movie4 = "Titanic";
const movie5 = "Joker";
This works, but it quickly becomes messy and hard to manage.
Instead, JavaScript gives us arrays, which allow us to store multiple values inside a single variable. In Js, you can create any type of value: string, boolean, number unli
const movies = ["Inception", "Interstellar", "Avatar", "Titanic", "Joker"];
Now all the values are organized in one place.
An array is a collection of values stored in order.
How to Create an Array
Arrays are created using square brackets [].
const movies = ["Inception", "Interstellar", "Avatar"];
You can store any type of value inside arrays.
const mixedArray = ["Rahul", 25, true];
Accessing Elements Using Index
Each item in an array has a position number called an index.
Important rule:
Array indexing starts from 0
const movies = ["Inception", "Interstellar", "Avatar", "Titanic", "Joker"];
console.log(movies[0]); // Inception
console.log(movies[4]); // Joker
So the structure looks like this:
Index → 0 1 2 3 4
Value → Inception Interstellar Avatar Titanic Joker
Updating Elements in an Array
We can update any value using its index.
Suppose you want to change Avatar to The Dark Knight.
const movies = ["Inception", "Interstellar", "Avatar", "Titanic", "Joker"];
movies[2] = "The Dark Knight";
console.log(movies);
Output:
["Inception", "Interstellar", "The Dark Knight", "Titanic", "Joker"]
Array Length Property
Arrays have a built-in property called length that tells us how many elements are inside the array.
const movies = ["Inception", "Interstellar", "Avatar", "Titanic", "Joker"];
console.log(movies.length);
Output:
5
This is useful when we want to access the last element.
console.log(movies[movies.length - 1]);
Output:
Joker
Looping Through an Array
Instead of printing each movie manually, we can use a loop to go through all values.
const movies = ["Inception", "Interstellar", "Avatar", "Titanic", "Joker"];
for (let i = 0; i < movies.length; i++) {
console.log(movies[i]);
}
Output:
Inception
Interstellar
Avatar
Titanic
Joker
This loop runs through the entire array and prints every element.




