JavaScript Arrays 101

Imagine you are building a grocery list app. Without arrays, you’d have to create a new variable for every single item:
let item1 = "Milk";let item2 = "Eggs";let item3 = "Bread";
That works for three items, but what if you have 50? This is where Arrays come to the rescue. An array is a single variable that can hold a collection of values, stored in a specific order.
Topics we are going to cover in this particular blogs are...
How to create an array
Accessing elements using index
Updating elements
Array length property
Basic looping over arrays
How to Create an Array?
Creating an array is as simple as using square brackets [] and separating your items with commas.
// An array of strings
let fruits = ["Apple", "Banana", "Mango", "Orange"];
// An array of numbers
let testMarks = [85, 92, 78, 95];
Accessing Elements (The "Index" Rule)
To get an item out of an array, you use its index (its position number).
Crucial Note: JavaScript uses Zero-based Indexing. This means the computer starts counting from 0, not 1.
The 1st item is at index
0.The 2nd item is at index
1.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // Output: Apple
console.log(fruits[1]); // Output: Banana
Updating Elements
Arrays are not set in stone. You can change any value inside them just by referencing its index.
let tasks = ["Clean Room", "Exercise", "Study"];
// Change "Exercise" to "Go for a Run"
tasks[1] = "Go for a Run";
console.log(tasks); // ["Clean Room", "Go for a Run", "Study"]
The .length Property
How do you know how many items are in your list? You use the .length property. This is incredibly useful when you don't know the size of your data beforehand.
let students = ["Alice", "Bob", "Charlie", "David"];
console.log(students.length); // Output: 4
Looping Over Arrays
The real power of arrays comes when you combine them with the loops we learned in the last blog. You can use a for loop to go through every item in an array automatically.
let colors = ["Red", "Green", "Blue", "Yellow"];
for (let i = 0; i < colors.length; i++) {
console.log("Color " + i + " is " + colors[i]);
}
Conclusion
Arrays are the first real step toward building data-driven applications. Instead of managing a messy room full of individual variables, you’ve now learned how to organize everything into a clean, indexed shelf.




