Arrays
In JavaScript, an array is a special variable that can hold more than one value at a time. Arrays are used to store multiple values in a single variable. These values can be of various types, including other arrays, and they're maintained in an ordered collection. Here's how you work with arrays in JavaScript:
Creating an Array
You can create an array by using the array literal syntax, or the Array constructor.
Array Literal Syntax (preferred way because it's more concise):
let fruits = ["Apple", "Banana", "Mango"];
Array Constructor:
let vegetables = new Array("Carrot", "Pea");
Accessing Array Elements
You can access an element in an array by referring to the index number. This reference is zero-based, meaning that the first element has the index 0, the second has index 1, and so on.
let fruits = ["Apple", "Banana", "Mango"];
let firstFruit = fruits[0]; // "Apple"
Changing an Array Element
Similarly, you can change the value of a specific element in an array by using the index number.
fruits[1] = "Strawberry"; // Now the array is ["Apple", "Strawberry", "Mango"]
Accessing the Full Array
If you want to access the whole array, you can just use the array's name:
console.log(fruits); // ["Apple", "Strawberry", "Mango"]
Array Properties and Methods
Arrays have properties and methods that you can use to manipulate them. Here are a few common ones:
length: This property returns the number of elements in the array.
let count = fruits.length; // 3
push(): This method adds a new element to the end of an array.
fruits.push("Orange"); // ["Apple", "Strawberry", "Mango", "Orange"]
pop(): This method removes the last element from an array.
fruits.pop(); // Removes "Orange" from the fruits array
shift(): This method removes the first item of an array.
fruits.shift(); // Removes "Apple" from the fruits array
unshift(): This method adds a new item at the beginning of an array.
fruits.unshift("Pineapple"); // Adds "Pineapple" at the beginning of the fruits array
indexOf(): This method searches the array for an element and returns its first index. If it's not found, it returns -1.
let pos = fruits.indexOf("Mango"); // 1
splice(): This method can be used to add new items to an array or remove existing items.
fruits.splice(1, 1, "Peach"); // Removes "Strawberry" at index 1 and adds "Peach" at that position
Iterating Over an Array
To loop through each item in an array, you can use a simple for loop, for...of loop, or the forEach() method, among others.
// for loop
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// for...of loop
for (let fruit of fruits) {
console.log(fruit);
}
// forEach() method
fruits.forEach(function(item, index, array) {
console.log(item, index);
});
Arrays in JavaScript are versatile and powerful, and they include many more methods than what's listed here. They are a fundamental part of the language and are used to store and manipulate collections of data efficiently.