An array is a unique variable capable of containing multiple values simultaneously.
const cars = [“Saab”, “Volvo”, “BMW”]; |
If you possess a list of items (such as a list of car names), storing the cars in individual variables might appear like this:
let car1 = “Saab”; let car2 = “Volvo”; let car3 = “BMW”; |
Yet, what if you aim to iterate through the cars to locate a particular one? Furthermore, what if your car count extends beyond just three to, say, 300?
The remedy lies in an array!
An array empowers you to store numerous values under a solitary name, and you can retrieve these values by referencing an index number.
The simplest method to create a JavaScript Array is by using an array literal.
Syntax:
const array_name = [item1, item2, ...]; |
It’s customary to declare arrays using the const keyword. Explore further about using const with arrays in the chapter titled “JS Array Const.” |
Example
const cars = [“Saab”, “Volvo”, “BMW”]; |
Spaces and line breaks hold no significance. A declaration can extend across multiple lines.
Example
const cars = [ “Saab”, “Volvo”, “BMW” ]; |
Another approach is to create an array and subsequently furnish its elements.
Example
const cars = []; cars[0]= “Saab”; cars[1]= “Volvo”; cars[2]= “BMW”; |
In the following example, an Array is created and values are assigned to it.
Example
const cars = new Array(“Saab”, “Volvo”, “BMW”); |
|
To access an element within an array, you refer to its index number.
const cars = [“Saab”, “Volvo”, “BMW”]; let car = cars[0]; |
Remember: Array indexes commence at 0. [0] denotes the initial element. [1] signifies the subsequent element. |
This statement modifies the value of the initial element in the “cars” array.
cars[0] = “Opel”; |
Example
const cars = [“Saab”, “Volvo”, “BMW”]; cars[0] = “Opel”; |
The toString() method in JavaScript transforms an array into a string comprising its array values, separated by commas.
Example
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; document.getElementById(“demo”).innerHTML = fruits.toString(); |
Result:
Banana,Orange,Apple,Mango |