An array is a special variable that can hold more than one value at a time. It is used to store a collection of data, which makes it much easier to manage large lists of related information.
Imagine you have a list of cars. Storing them in single variables would look like this:
let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";
However, what if you had 300 cars? Finding a specific one would be a nightmare. An array allows you to store them all under a single name and access them using a number called an index.
The most common way to create a JavaScript array is by using array literals (square
brackets []).
const cars = ["Saab", "Volvo", "BMW"];
const
keyword, as the reference to the array should not change, even if you modify the
elements inside.
You can access an array element by referring to its index number. Remember that JavaScript arrays are zero-based: the first element is [0], the second is [1], and so on.
const fruits = ["Banana", "Orange", "Apple"];
let fruit = fruits[0]; // Result: "Banana"
You can change the value of a specific element by using its index:
const fruits = ["Banana", "Orange", "Apple"];
fruits[0] = "Mango";
// Now the first fruit is "Mango" instead of "Banana"
The length property of an array returns the number of elements it contains.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.length); // 4
length property to access the last element
of any array: fruits[fruits.length - 1].
In JavaScript, arrays use numbered indexes, while objects use named indexes. Arrays are a special type of object used for lists of data where the order matters.
[index] to access or modify specific elementslength property tells you how many items are in the array[] over new Array() for better performance