An array is a special variable used to store multiple values in a single place.
const colors = ["red", "green", "blue"];Think of it like a list or collection of items — each with an index starting from 0.
const fruits = ["apple", "banana", "cherry"];
const numbers = [10, 20, 30, 40];
const mixed = ["text", 100, true, null];You can also create an array using the Array() constructor:
const cars = new Array("Toyota", "Honda", "BMW");console.log(fruits[0]); // apple
console.log(fruits[2]); // cherryfruits[1] = "mango";
console.log(fruits); // ["apple", "mango", "cherry"]console.log(fruits.length); // 3fruits.push("grape");fruits.pop();fruits.unshift("orange");fruits.shift();for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}for (let fruit of fruits) {
console.log(fruit);
}fruits.forEach(function(fruit) {
console.log(fruit);
});| Method | Description | Example |
|---|---|---|
push() | Add item to end | arr.push("new") |
pop() | Remove last item | arr.pop() |
shift() | Remove first item | arr.shift() |
unshift() | Add item to start | arr.unshift("start") |
indexOf() | Find index of an item | arr.indexOf("banana") |
includes() | Check if item exists | arr.includes("apple") |
join() | Join array to string | arr.join(", ") |
slice() | Extract portion of array | arr.slice(1, 3) |
splice() | Add/remove items | arr.splice(1, 2, "new") |
concat() | Merge arrays | arr1.concat(arr2) |
reverse() | Reverse the array | arr.reverse() |
sort() | Sort the array | arr.sort() |
const pets = ["cat", "dog", "rabbit"];
console.log(pets.includes("dog")); // true
console.log(pets.indexOf("rabbit")); // 2const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 }
];
console.log(users[0].name); // Aliceconst nums = [1, 2, 3];
const squared = nums.map(n => n * n); // [1, 4, 9]const ages = [12, 18, 22, 15];
const adults = ages.filter(age => age >= 18); // [18, 22]const found = ages.find(age => age > 18); // 22Extract values into variables easily:
const cities = ["Delhi", "Mumbai", "Chennai"];
const [first, second] = cities;
console.log(first); // Delhi
console.log(second); // Mumbaipush() and pop().map() to double each number.splice() to replace an item in the array.