An Array is a data structure that allows us to store and access multiple values in an ordered manner using a numeric index.
In JavaScript, Arrays are special objects that allow us to work with an ordered collection of elements, where each element has a numeric position (known as an index).
The indices of an array in JavaScript start from 0, which means that the first element has an index of 0, the second has an index of 1, and so on.
If you want to learn more about static Arrays
check the Introduction to Programming Course read more
Declaring Arrays
To declare an Array in JavaScript, the following syntax is used:
let myArray = [value1, value2, value3, ...];
Where value1
, value2
, value3
, etc. are the values we want to store in the Array.
In JavaScript, an Array can contain values of any data type (including other objects and functions).
let numbers = [1, 2, 3, 4, 5];
let fruits = ["apple", "banana", "cherry"];
Other ways
In JavaScript, Arrays can be created in several ways:
Using the Array constructor
let numbers = new Array(1, 2, 3, 4, 5);
let fruits = new Array("apple", "banana", "cherry");
Empty Arrays
let emptyArray = [];
let anotherEmptyArray = new Array();
Arrays with a specific size
let sizedArray = new Array(10); // Creates an array with 10 empty elements
Accessing elements of an Array
To access the elements of an Array in JavaScript, we use the numeric index corresponding to each element.
The first element of an Array has an index of 0
, the second has an index of 1
, and so on.
For example, if we want to access the second element of an Array called myArray
, we can do it like this:
let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // "apple"
console.log(fruits[1]); // "banana"
console.log(fruits[2]); // "cherry"
We can also modify the value of an element in the Array using its numeric index:
let numbers = [1, 2, 3, 4, 5];
numbers[2] = 10;
console.log(numbers); // [1, 2, 10, 4, 5]
Multidimensional Arrays
Arrays in JavaScript can contain other arrays as elements, allowing for the creation of multidimensional arrays.
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[0][0]); // 1
console.log(matrix[1][2]); // 6
Iterating over Arrays
for Loop
let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
for…of Loop
let numbers = [1, 2, 3, 4, 5];
for (let number of numbers) {
console.log(number);
}
forEach() Method
let numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});