An array in JavaScript is a special type of variable that can store multiple values in a single container. Think of it as a list or collection of items. Each item in an array is called an element, and each element has a position number called an index, starting from 0.
1️⃣ Creating an Array
You can create an array using square brackets [ ]:
let fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits);
fruits is an array containing 3 elements.fruits[0] → "Apple"fruits[1] → "Banana"fruits[2] → "Cherry"2️⃣ Array Length
The length property tells you how many elements are in an array:
let fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits.length); // 3
3️⃣ Accessing Elements
You can access array elements using their index:
let fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits[0]); // Apple console.log(fruits[2]); // Cherry
length - 14️⃣ Modifying Elements
You can change, add, or remove elements:
let fruits = ["Apple", "Banana", "Cherry"];
// Modify element
fruits[1] = "Blueberry"; // Change "Banana" to "Blueberry"
// Add element at end
fruits.push("Mango");
// Remove last element
fruits.pop();
// Add element at beginning
fruits.unshift("Strawberry");
// Remove first element
fruits.shift();
console.log(fruits);
5️⃣ Looping Through an Array
Arrays are often processed using loops.
for loop
let fruits = ["Apple", "Banana", "Cherry"];
for(let i = 0; i < fruits.length; i++) {
console.log("Fruit at index " + i + ": " + fruits[i]);
}
for...of loop (simpler)
for(let fruit of fruits) {
console.log("Fruit: " + fruit);
}
Explanation:
fruitsfor loop<!DOCTYPE html>
<html>
<head>
<title>JavaScript Array Example</title>
<style>
body { font-family: Arial; padding: 20px; }
button { padding: 10px 20px; margin: 5px; cursor: pointer; }
p { font-size: 18px; color: darkblue; }
</style>
</head>
<body>
<h1>JavaScript Arrays Demo</h1>
<p id="demo">Click the button to see array operations</p>
<button onclick="arrayDemo()">Show Array</button>
<script>
function arrayDemo() {
// Create array
let fruits = ["Apple", "Banana", "Cherry"];
// Modify elements
fruits[1] = "Blueberry"; // Replace Banana with Blueberry
fruits.push("Mango"); // Add Mango at end
// Display length
let message = "Array length: " + fruits.length + "<br>";
// Loop through array
message += "Fruits List:<br>";
for(let i = 0; i < fruits.length; i++) {
message += "Index " + i + ": " + fruits[i] + "<br>";
}
document.getElementById("demo").innerHTML = message;
}
</script>
</body>
</html>