JavaScript Arrays 101
Imagine we are building a simple "To-Do List" application. If we have three tasks, we could create three separate variables: task1, task2, and task3. But what happens when the user has 100 tasks? Managing 100 individual variables becomes impossible.
An array is a "container" that can hold a list of values in a specific order.
What is an Array ?
An array is a collection of values stored in a single variable. Think of it like a train where each carriage holds a specific item. The entire train has one name, but each carriage has a specific position so we can find exactly what is inside.
Creating an Array
In JavaScript, we define an array using square brackets [], with each item separated by a comma.
// Storing values individually (Inefficient)
let fruit1 = "Apple";
let fruit2 = "Banana";
let fruit3 = "Cherry";
// Using an Array (Efficient)
const fruits = ["Apple", "Banana", "Cherry"];
Accessing Elements via Index
JavaScript arrays are zero-indexed. This means the counting starts at 0, not 1.
The 1st element is at index 0.
The 2nd element is at index 1.
The 3rd element is at index 2.
const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Output: Apple
console.log(fruits[1]); // Output: Banana
Updating Elements
Arrays are mutable, meaning we can change their contents even if the array was declared with const. To update a value, simply target its index and assign a new value.
let fruits= ["Apple", "Strawberry", "Mango"];
fruits[1] = "Banana"; // Replaces "John" with "Jane"
console.log(fruits); // Output: ["Apple", "Banana", "Mango"]
The Length Property
To find out how many items are in an array, use the .length property. This is incredibly useful when we don't know the size of the list beforehand.
const colors = ["Red", "Green", "Blue", "Yellow"];
console.log(colors.length); // Output: 4
Basic Looping Over Arrays
The most common way to process every item in an array is by using a for loop. We use the .length property to tell the loop when to stop.
const tasks = ["Email client", "Debug code", "Team meeting"];
for (let i = 0; i < tasks.length; i++) {
console.log("Task " + (i + 1) + ": " + tasks[i]);
}
Output :
Task 1: Email client
Task 2: Debug code
Task 3: Team meeting
Key Takeaways
Arrays store multiple values in a single variable.
Elements are stored in ordered positions called indexes.
Array indexing starts from 0.
We access elements using
array[index].The
lengthproperty tells how many elements exist.Loops allow us to easily process every element in an array.
