An array is a data structure that allows you to store multiple values in a single variable. You can think of an array as a list of items, where each item is identified by an index number.
You can create an array in JavaScript by using the Array constructor:
var myArray = new Array();
You can also create an array by using the Array literal notation:
var myArray = [1, 2, 3, 4, 5];
The Array constructor and the Array literal notation both create an array that has five elements. The first element is at index 0, the second element is at index 1, and so on.
You can access the elements of an array by using the index number of the element you want to access. For example, the following code accesses the third element of the myArray array:
var thirdElement = myArray[2];
The following code prints the value of the thirdElement variable to the console:
console.log(thirdElement);
3
You can also use the forEach() method to iterate through the elements of an array. The forEach() method takes a function as its parameter. The function is executed once for each element in the array.
The following code prints the value of the thirdElement variable to the console, using the forEach() method:
myArray.forEach(function(element) {
console.log(element);
});
3
4
5