JavaScript Array

2 min read

🔢 JavaScript Arrays – A Beginner’s Guide
Arrays in JavaScript are special variables that can hold multiple values at once. Instead of creating separate variables for each value, you can store them all in one array.
✅ How to Create an Array
javascriptCopyEditlet fruits = ["Apple", "Banana", "Mango"];
You can also use the new Array()
constructor:
javascriptCopyEditlet numbers = new Array(1, 2, 3, 4);
📍 Accessing Array Elements
Array elements are accessed using index numbers (starting from 0):
javascriptCopyEditconsole.log(fruits[0]); // Output: Apple
🛠 Common Array Methods
Method | Description | Example |
push() | Adds to the end | fruits.push("Orange") |
pop() | Removes from end | fruits.pop() |
shift() | Removes from start | fruits.shift() |
unshift() | Adds to start | fruits.unshift("Pineapple") |
length | Returns size | fruits.length |
indexOf() | Finds index | fruits.indexOf("Mango") |
includes() | Checks value | fruits.includes("Banana") |
join() | Converts to string | fruits.join(", ") |
slice() | Copies part | fruits.slice(1, 3) |
splice() | Add/remove at index | fruits.splice(1, 1) |
🔁 Looping Through Arrays
javascriptCopyEditfor (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Or use forEach()
:
javascriptCopyEditfruits.forEach(function(fruit) {
console.log(fruit);
});
📌 Array of Objects Example
javascriptCopyEditlet students = [
{ name: "Amit", age: 20 },
{ name: "Riya", age: 22 }
];
console.log(students[0].name); // Output: Amit
🧠 Tip: Arrays are mutable. That means methods like push
, pop
, etc. change the original array.
🧪 Test It Out
javascriptCopyEditlet colors = ["Red", "Green"];
colors.push("Blue");
console.log(colors); // Output: ["Red", "Green", "Blue"]
0
Subscribe to my newsletter
Read articles from Abhay Ganesh Bhagat directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
