An Array in JavaScript is a special variable that can store multiple values in a single place.
Think of an array like a list:
Without arrays:
let student1 = "John";
let student2 = "Emma";
let student3 = "Ryan";
With an array (clean & easier to manage):
let students = ["John", "Emma", "Ryan"];
let colors = ["red", "green", "blue"];
let numbers = new Array(10, 20, 30);
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // Apple
console.log(fruits[1]); // Banana
console.log(fruits[2]); // Mango
let fruits = ["Apple", "Banana", "Mango"];
fruits[1] = "Orange";
console.log(fruits);
// ["Apple", "Orange", "Mango"]
The .length property shows how many items are in the array:
let items = ["Pen", "Book", "Bag"];
console.log(items.length); // 3
JavaScript gives many built-in methods:
fruits.push("Kiwi");
fruits.unshift("Papaya");
fruits.pop();
fruits.shift();
let cars = ["BMW", "Audi", "Tesla"];
for (let i = 0; i < cars.length; i++) {
console.log(cars[i]);
}
for (let car of cars) {
console.log(car);
}
let colors = ["red", "blue", "green"];
console.log(colors.indexOf("blue")); // 1
colors.includes("green"); // true
let sliced = colors.slice(0, 2);
// ["red", "blue"]
colors.splice(1, 1);
// Removes 1 item at index 1
colors.join(", ");
// "red, blue, green"
colors.reverse();
colors.sort();
| Method | Purpose | Example |
|---|---|---|
push() |
Adds item at end | arr.push("x") |
pop() |
Removes last item | arr.pop() |
shift() |
Removes first item | arr.shift() |
unshift() |
Adds item at beginning | arr.unshift("x") |
slice() |
Copy elements | arr.slice(1,3) |
splice() |
Add/Remove items | arr.splice(1,1) |
includes() |
Checks value exists | arr.includes("x") |
indexOf() |
Find index | arr.indexOf("x") |