JavaScript arrays are used to store multiple values in a single variable. They are a type of object, but unlike objects, they use numbered indexes to access their elements. Arrays can hold any data type, including numbers, strings, objects, and even other arrays.
1. Creating Arrays:
- You can create arrays using array literals
[]
or theArray()
constructor:
const fruits = ['Apple', 'Banana', 'Orange'];
const numbers = new Array(1, 2, 3, 4, 5);
2. Accessing Array Elements:
- Array elements are accessed using square brackets
[]
and their index, which starts from 0:
console.log(fruits[0]); // Outputs: 'Apple'
console.log(numbers[2]); // Outputs: 3
3. Modifying Array Elements:
- You can modify array elements directly by assigning new values to them:
fruits[1] = 'Grapes';
console.log(fruits); // Outputs: ['Apple',
'Grapes', 'Orange']
4. Array Properties and Methods:
length
: Property that returns the number of elements in the array.push()
: Method that adds one or more elements to the end of an array.pop()
: Method that removes the last element from an array and returns that element.shift()
: Method that removes the first element from an array and returns that element.unshift()
: Method that adds one or more elements to the beginning of an array.
Example Usage:
console.log(fruits.length); // Outputs: 3
fruits.push('Mango');
console.log(fruits); // Outputs: ['Apple',
'Grapes', 'Orange', 'Mango']
const removedElement = fruits.pop();
console.log(removedElement); // Outputs: 'Mango'
fruits.unshift('Kiwi');
console.log(fruits); // Outputs: ['Kiwi',
'Apple', 'Grapes', 'Orange']
When you pass the single numeric argument to the Array() constructor, it defines the array of argument length containing the undefined values. The maximum length allowed for an array is 4,294,967,295.
5. Iterating Over Arrays:
You can use loops like for
and forEach()
to iterate over array elements:
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
fruits.forEach(function(fruit) {
console.log(fruit);
});
6. Multidimensional Arrays:
JavaScript arrays can contain other arrays, creating multidimensional arrays:
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[1][2]); // Outputs: 6