To understand what arrays are in JavaScript, why we use them, and how to define and access their elements.
An array is a special variable that can hold multiple values at once. Instead of creating separate variables for each item, you can store them all in a single array.
Think of an array like a shopping list — a single container holding several related items:
let shoppingList = ["milk", "bread", "eggs", "butter"];
let fruits = ["apple", "banana", "cherry"];
[]
define the arrayEach element in an array has a position number, called an index, starting from 0
.
Index | Value |
---|---|
0 | “apple” |
1 | “banana” |
2 | “cherry” |
You can access array items like this:
console.log(fruits[0]); // Output: apple
console.log(fruits[2]); // Output: cherry
Arrays can hold mixed data types, although it’s better to keep elements consistent:
let mixed = ["hello", 42, true, null];
let colors = ["red", "green", "blue"];
console.log("First color:", colors[0]);
console.log("Third color:", colors[2]);