In JavaScript, an array is a special type of object used to store multiple values in a single variable. Arrays can hold elements of any data type, including numbers, strings, objects, and even other arrays. Arrays are versatile and widely used in JavaScript for storing and manipulating collections of data. Here's how we can work with arrays in JavaScript:
1. Creating an Array:
Arrays can be created using the array literal notation '[]' or the 'Array()' constructor.
Using Array Literal:
let fruits = ['apple', 'banana', 'orange'];
Using Array Constructor:
let cars = new Array('Toyota', 'Honda', 'BMW');
2. Accessing Array Elements:
We can access individual elements of an array using square brackets '[]' and their index, starting from 0.
console.log(fruits[0]); // Output: 'apple'
console.log(cars[2]); // Output: 'BMW'
3. Modifying Array Elements:
We can modify array elements by assigning new values to them using their index.
fruits[1] = 'grape';
console.log(fruits); // Output: ['apple', 'grape', 'orange']
4. Array Length:
We can get the length of an array using the length property.
console.log(fruits.length); // Output: 3
5. Array Methods:
JavaScript provides several built-in methods for working with arrays, such as push(), pop(), shift(), unshift(), slice(), splice(), concat(), join(), indexOf(), includes(), etc.
fruits.push('pineapple'); // Add an element to the end
console.log(fruits); // Output: ['apple', 'grape', 'orange', 'pineapple']
let removedFruit = fruits.pop(); // Remove the last element
console.log(removedFruit); // Output: 'pineapple'
fruits.unshift('kiwi'); // Add an element to the beginning
console.log(fruits); // Output: ['kiwi', 'apple', 'grape', 'orange']
6. Iterating over Arrays:
We can loop through the elements of an array using loops like for, for-of, forEach(), etc.
for (let fruit of fruits) {
console.log(fruit);
}
fruits.forEach(function(fruit) {
console.log(fruit);
});
7. Multi-dimensional Arrays:
Arrays can contain other arrays, allowing us to create multi-dimensional arrays for storing complex data structures.
let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
console.log(matrix[1][2]); // Output: 6
8. Array Destructuring:
We can destructure arrays to extract values into separate variables.
let [first, second] = fruits;
console.log(first); // Output: 'kiwi'
console.log(second); // Output: 'apple'