A JavaScript Array is a special type of variable that can hold more than one value at a time. If you have a list of items (like a list of car names or a list of numbers), storing the items in single variables could look like this:
let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";
This is cumbersome and not scalable. Arrays solve this problem by allowing you to store multiple values in a single reference.
An array is an ordered collection of values. Each value is called an element, and each element has a numeric position in the array, known as its index.
0, the second is at index 1, and so on.The simplest way to create an array is by using an array literal.
The array literal syntax uses square brackets [] to wrap a comma-separated list of elements.
const cars = ["Saab", "Volvo", "BMW"]; console.log(cars);
You can access an individual element in an array by referring to its index number inside square brackets.
const cars = ["Saab", "Volvo", "BMW"];// Access the first element (index 0) let firstCar = cars[0];
console.log(firstCar); // Outputs: Saab
You can change the value of an element by accessing it via its index and assigning a new value.
const cars = ["Saab", "Volvo", "BMW"];// Change the first element cars[0] = "Opel";
console.log(cars); // Outputs: ["Opel", "Volvo", "BMW"]
length PropertyThe length property of an array returns the number of elements it contains.
const fruits = ["Banana", "Orange", "Apple", "Mango"]; let length = fruits.length;console.log(length); // Outputs: 4
If you have an array `const colors = ["Red", "Green", "Blue"]`, how do you access the element "Green"?