JavaScript Array

🔢 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

MethodDescriptionExample
push()Adds to the endfruits.push("Orange")
pop()Removes from endfruits.pop()
shift()Removes from startfruits.shift()
unshift()Adds to startfruits.unshift("Pineapple")
lengthReturns sizefruits.length
indexOf()Finds indexfruits.indexOf("Mango")
includes()Checks valuefruits.includes("Banana")
join()Converts to stringfruits.join(", ")
slice()Copies partfruits.slice(1, 3)
splice()Add/remove at indexfruits.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

Abhay Ganesh Bhagat
Abhay Ganesh Bhagat