Arrays
In real life, we often deal with collections. A shopping cart has multiple items, a class has many students, and a playlist contains many songs.
In JavaScript, an array is used to store multiple values inside a single variable.
What Is an Array?
An array is a list of values stored in a specific order. Each value in the array has a position called an index.
Array indexes start from 0, not 1.
Creating an Array
You can create an array using square brackets.
let colors = ["red", "blue", "green"];
This array stores three color names.
Accessing Array Elements
You can access an array element using its index.
let fruits = ["apple", "banana", "orange"];
console.log(fruits[0]);
console.log(fruits[1]);
Here, fruits[0] gives the first element in the array.
Updating Array Elements
Arrays are mutable, which means you can change their values.
let numbers = [10, 20, 30];
numbers[1] = 25;
The second value in the array is updated.
Array Length
The length property tells you how many elements
are inside an array.
let cities = ["London", "Paris", "Tokyo"];
console.log(cities.length);
This is useful when looping through arrays.
Real-World Example
Imagine storing daily expenses:
let expenses = [50, 30, 20];
let total = 0;
for (let i = 0; i < expenses.length; i++) {
total += expenses[i];
}
Arrays make it easy to process multiple values together.
Common Beginner Mistakes
- Forgetting that array indexing starts at 0
- Accessing indexes that do not exist
- Confusing arrays with objects
Always double-check the index you are using.
Thumb Rules
- Use arrays to store lists of related values
- Remember that indexing starts at 0
- Use
lengthwhen looping through arrays - Keep array data organized and meaningful
More on Arrays Later
In this lesson, we focused on the basics of arrays.
More powerful array operations are covered next.
- Array methods are explained in Lesson 12 (Array Methods)
- Arrays with objects are used extensively in Lesson 13 (Objects)
What Comes Next?
Now that you know how to store data in arrays, the next step is learning how to work with them efficiently.
In the next lesson, we will explore array methods.