Arrays in JavaScript
Imagine your mother gives you a shopping list. 📝
1. Milk
2. Bread
3. Eggs
4. Tomatoes
It is one piece of paper, but it holds many items, written in order.
Now imagine instead she gave you 4 separate chits of paper, one for each item. You might lose one, mix up the order, or forget how many there were. 😅
In JavaScript, an array is like that single shopping list. It keeps many values together, neatly, in one place.
What Is an Array?
An array is a special variable that stores many values in an ordered list.
Key points:
- The values are written inside square brackets
[ ]. - Each value is separated by a comma
,. - Each value inside an array is called an element (or item).
- The items stay in the same order in which you put them.
Why Use an Array?
Let us say you want to store the marks of 5 students.
❌ Without an array
let marks1 = 78;
let marks2 = 85;
let marks3 = 92;
let marks4 = 66;
let marks5 = 74;
Now think about these problems:
- What if there are 500 students? Will you create 500 variables? 😩
- How will you find the total or the highest marks easily?
- How will you add a new student's marks later?
✅ With an array
One variable, and it works for 5 students or 5,000 students!
Benefits of arrays
| Benefit | Meaning |
|---|---|
| One name, many values | No need for marks1, marks2, marks3... |
| Ordered | Items stay in the order you added them |
| Easy to loop | Go through every item with a loop |
| Easy to grow or shrink | Add or remove items any time |
| Built-in tools | Methods to sort, search, filter, and more |
Creating Arrays
1. Using square brackets [ ] (most common ✅)
2. Using new Array()
⚠️ Be careful: With a single number,
new Array()behaves differently!
That's why developers prefer [ ]. It is shorter and has no surprises.
3. Using Array.from()
Array.from() turns something list-like into a real array.
4. Using Array.of()
Array.of() creates an array from the values you give, even a single number.
Arrays can store any type of value
An array can even hold another array inside it!
Tip: Even though you can mix types, it is better to keep one kind of value per array (all names, or all prices). It makes your code easier to understand.
Accessing Array Items
Every item in an array has a position number called an index.
⚠️ The index starts from 0, not 1!
shoppingList = [ "Milk", "Bread", "Eggs", "Tomatoes" ]
index: 0 1 2 3
Think of it like floors in a building in India 🏢: the first floor you enter is the Ground floor (0), then 1st floor, 2nd floor, and so on.
Reading an item with [index]
Asking for an index that doesn't exist gives undefined, not an error.
Finding the number of items with .length
Remember: The last index is always length - 1.
An easier way: .at()
.at() works like [ ], but it also accepts negative numbers, which count from the end.
trains[-1]givesundefined. Only.at(-1)works for negative positions.
Updating Array Items
To change an item, use its index and give it a new value.
Wait, we used const, but the array changed? 🤔
Yes! const means you cannot give the variable a completely new array. But you can change the items inside it.
Think of const like a tiffin box that is glued to your table. You can change the food inside it, but you can't replace the box itself.
Looping Through an Array
To do something with every item, use a loop.
Checking Items in an Array
Is an item in the array? includes()
Where is the item? indexOf()
Is this value really an array? Array.isArray()
typeof says "object" for arrays, so always use Array.isArray() to check.
Destructuring Arrays
Destructuring means unpacking the items of an array into separate variables, in one line.
Think of opening your tiffin box 🍱 and putting the roti, dal, and sabzi on separate plates.
Without destructuring
With destructuring ✨
The variables are filled by position: the first variable gets the first item, the second gets the second, and so on.
Skipping items
Leave an empty space between commas to skip an item.
Default values
If an item is missing, you can give a default value.
Collecting the rest with ...
The rest operator ... collects all the remaining items into a new array.
The
...restpart must always come last.
Swapping two values 🔄
Destructuring makes swapping super easy, with no extra variable needed.
Destructuring in a loop
Very useful with .entries(), which gives the index and the value together.
Copying and Joining Arrays with Spread ...
The spread operator ... spreads out the items of an array. (It looks the same as rest, but it is used on the right side.)
Joining two arrays
Making a copy
⚠️ Why not just copy = original?
Arrays are shared, like a Google Doc link. If you give the same link to a friend and they edit it, you see the change too. To get your own copy, use [...array].
Common Mistakes to Avoid
| Mistake | Problem | Fix |
|---|---|---|
Starting the index at 1 | You miss the first item | Indexes start at 0 |
Using arr[arr.length] for the last item | Gives undefined | Use arr[arr.length - 1] or arr.at(-1) |
Using arr[-1] | Gives undefined | Use arr.at(-1) |
new Array(5) expecting [5] | Creates 5 empty slots | Use [5] |
Copying with b = a | Both point to the same array | Use b = [...a] |
Checking with typeof | Always says "object" | Use Array.isArray() |
Quick Summary Table
| Task | Code |
|---|---|
| Create an array | const arr = ["a", "b", "c"]; |
| Read the first item | arr[0] |
| Read the last item | arr.at(-1) |
| Count the items | arr.length |
| Change an item | arr[1] = "x"; |
| Add to the end | arr.push("d"); |
| Check if an item exists | arr.includes("a") |
| Destructure | const [first, second] = arr; |
| Copy | const copy = [...arr]; |
| Join | const all = [...arr1, ...arr2]; |
Key Takeaways
- An array stores many values in one ordered list, written inside
[ ]. - We use arrays to avoid creating many separate variables, and to easily loop, add, remove, and search items.
- Items are accessed by their index, which starts from 0. Use
.lengthto count items and.at(-1)for the last item. - Destructuring unpacks items into variables:
const [a, b] = arr. Use...restto collect the remaining items. - Use the spread operator
[...arr]to copy or join arrays safely.