So far, we've stored individual values in variables:
let name = "John";
let age = 20;
let city = "Delhi";But what if we want to store many related values?
Creating a separate variable for every value would quickly become inconvenient.
That's where arrays come in.
What is an Array?
An array is a data structure used to store multiple values in a single variable.
For example:
let fruits = ["Apple", "Banana", "Mango", "Orange"];Instead of creating four separate variables, we can keep all the fruits inside one array.
Creating an Array
We create an array using square brackets [].
let fruits = ["Apple", "Banana", "Mango"];An array can contain numbers too:
let numbers = [10, 20, 30, 40, 50];It can even contain different types of values:
let data = ["John", 20, true, null];Although JavaScript allows this, in real programs it's usually better to keep related data together.
Array Index
Each value inside an array has a position called an index.
The important thing to remember is:
Array indexing starts from
0, not1.
For example:
let fruits = ["Apple", "Banana", "Mango"];The positions are:
Index | Value |
|---|---|
| Apple |
| Banana |
| Mango |
So to access "Apple":
console.log(fruits[0]);Output:
AppleAnd:
console.log(fruits[2]);Output:
MangoChanging Array Elements
Arrays are mutable, which means we can change their elements.
let fruits = ["Apple", "Banana", "Mango"];
fruits[1] = "Orange";
console.log(fruits);Output:
["Apple", "Orange", "Mango"]Here, "Banana" was replaced with "Orange".
Finding the Array Length
The .length property tells us how many elements an array contains.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.length);Output:
3This becomes particularly useful when working with loops:
let fruits = ["Apple", "Banana", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}Output:
Apple
Banana
MangoAdding Elements to an Array
JavaScript provides several methods for adding elements.
push()
The push() method adds an element to the end of an array.
let fruits = ["Apple", "Banana"];
fruits.push("Mango");
console.log(fruits);Output:
["Apple", "Banana", "Mango"]You can add multiple elements too:
fruits.push("Orange", "Grapes");unshift()
The unshift() method adds an element to the beginning.
let fruits = ["Banana", "Mango"];
fruits.unshift("Apple");
console.log(fruits);Output:
["Apple", "Banana", "Mango"]Removing Elements from an Array
pop()
The pop() method removes the last element.
let fruits = ["Apple", "Banana", "Mango"];
fruits.pop();
console.log(fruits);Output:
["Apple", "Banana"]shift()
The shift() method removes the first element.
let fruits = ["Apple", "Banana", "Mango"];
fruits.shift();
console.log(fruits);Output:
["Banana", "Mango"]So it's easy to remember:
Method | Action |
|---|---|
| Add to end |
| Remove from end |
| Add to beginning |
| Remove from beginning |
Finding Elements
JavaScript provides useful methods for searching arrays.
includes()
includes() checks whether an array contains a particular value.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.includes("Banana"));Output:
trueIf the value doesn't exist:
console.log(fruits.includes("Orange"));Output:
falseindexOf()
indexOf() returns the index of an element.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.indexOf("Mango"));Output:
2If the element isn't found, it returns -1.
console.log(fruits.indexOf("Orange"));Output:
-1Looping Through an Array
We can use a normal for loop:
let fruits = ["Apple", "Banana", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}We can also use for...of, which is often cleaner when we only need the values:
for (let fruit of fruits) {
console.log(fruit);
}Output:
Apple
Banana
MangoUseful Array Methods
JavaScript has many built-in array methods.
Some important ones are:
Method | Purpose |
|---|---|
| Adds elements to the end |
| Removes the last element |
| Removes the first element |
| Adds elements to the beginning |
| Checks whether a value exists |
| Finds the index of a value |
| Creates a portion of an array |
| Adds, removes, or replaces elements |
| Creates a new array by transforming elements |
| Creates a new array containing matching elements |
| Combines array elements into a single value |
We'll explore the more advanced methods separately.
Arrays Can Store Objects
Arrays become much more powerful when combined with objects.
For example:
let students = [
{
name: "John",
age: 20
},
{
name: "Alex",
age: 21
}
];Now we have an array containing multiple student objects.
We can access the first student's name like this:
console.log(students[0].name);Output:
JohnThis kind of structure is extremely common in real-world applications.
A Practical Example
Suppose we're building a shopping application:
let cart = ["Laptop", "Mouse", "Keyboard"];
cart.push("Headphones");
console.log("Items in cart:");
for (let item of cart) {
console.log(item);
}Output:
Items in cart:
Laptop
Mouse
Keyboard
HeadphonesHere, an array makes it easy to store and manage all the products in the shopping cart.
Conclusion
Arrays are used whenever we need to store multiple values together.
The basic syntax is:
let fruits = ["Apple", "Banana", "Mango"];Remember these important points:
Array indexes start at
0.Use
array[index]to access an element.Use
.lengthto find the number of elements.Arrays can be modified after creation.
push(),pop(),shift(), andunshift()are commonly used to add and remove elements.Arrays can contain objects and other arrays.
Arrays are one of the most commonly used data structures in JavaScript, and understanding them is essential before moving into array methods such as map(), filter(), and reduce().