JavaScript Arrays
8 April 2025 | Category: JavaScript
An Array is a special variable in JavaScript that can store multiple values in a single variable.
Instead of creating separate variables for each value:
let item1 = "Apple";
let item2 = "Banana";
let item3 = "Mango";
You can use an array:
let fruits = ["Apple", "Banana", "Mango"];
✅ How to Create an Array
1. Using Square Brackets []
(Recommended)
let cars = ["BMW", "Audi", "Mercedes"];
2. Using new Array()
(Not recommended)
let bikes = new Array("Yamaha", "Suzuki", "Kawasaki");
✅ Accessing Array Elements
Array elements are accessed using their index (starts from 0):
let colors = ["Red", "Green", "Blue"];
console.log(colors[0]); // Red
console.log(colors[1]); // Green
console.log(colors[2]); // Blue
✅ Array Length
Use .length
to get the total number of items in the array:
let items = ["Pen", "Pencil", "Eraser"];
console.log(items.length); // 3
✅ Modifying Arrays
Change a value:
let fruits = ["Apple", "Banana", "Mango"];
fruits[1] = "Orange";
console.log(fruits); // ["Apple", "Orange", "Mango"]
Add new item:
fruits[3] = "Grapes";
✅ Common Array Methods
Method | Description | Example |
---|---|---|
push() | Adds element to the end | arr.push("item") |
pop() | Removes last element | arr.pop() |
shift() | Removes first element | arr.shift() |
unshift() | Adds element to the beginning | arr.unshift("item") |
length | Returns the number of elements | arr.length |
indexOf() | Finds index of an item | arr.indexOf("Apple") |
includes() | Checks if array contains a value | arr.includes("Mango") |
join() | Converts array to string | arr.join(", ") |
slice() | Extracts part of the array | arr.slice(1, 3) |
splice() | Add/remove elements | arr.splice(2, 0, "item") |
reverse() | Reverses array order | arr.reverse() |
sort() | Sorts array alphabetically (or numerically) | arr.sort() |
✅ Looping Through an Array
Using for
loop:
let fruits = ["Apple", "Banana", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Using forEach()
:
fruits.forEach(function(item) {
console.log(item);
});
✅ Arrays Can Store Different Types
JavaScript arrays can store strings, numbers, objects, even other arrays.
let mix = ["Hello", 42, true, { name: "John" }, [1, 2, 3]];
⚠️ Note: JavaScript Arrays are Objects
Arrays in JavaScript are technically objects, but they have special methods and behavior.
typeof ["Apple", "Banana"]; // "object"
✅ Summary
- Arrays store multiple values in a single variable.
- Array elements are accessed by index.
- JavaScript provides many built-in methods to work with arrays.
- Arrays can store different data types.