Understanding and working with arrays in JavaScript
Arrays in JavaScript are used to store multiple values in a single variable. They are objects that can hold collections of data, and provide many useful methods for manipulating that data.
There are several ways to create arrays in JavaScript:
// Array literal notation
const fruits = ["Apple", "Banana", "Orange"];
// Using the Array constructor
const numbers = new Array(1, 2, 3, 4, 5);
// Creating an empty array
const emptyArray = [];
Array elements are accessed using their index, which starts at 0:
const fruits = ["Apple", "Banana", "Orange"];
console.log(fruits[0]); // Outputs: Apple
console.log(fruits[1]); // Outputs: Banana
console.log(fruits[2]); // Outputs: Orange
JavaScript provides many built-in methods for working with arrays:
const fruits = ["Apple", "Banana"];
// push(): Adds one or more elements to the end of an array
fruits.push("Orange");
console.log(fruits); // Outputs: ["Apple", "Banana", "Orange"]
// pop(): Removes the last element from an array
fruits.pop();
console.log(fruits); // Outputs: ["Apple", "Banana"]
// unshift(): Adds one or more elements to the beginning of an array
fruits.unshift("Mango");
console.log(fruits); // Outputs: ["Mango", "Apple", "Banana"]
// shift(): Removes the first element from an array
fruits.shift();
console.log(fruits); // Outputs: ["Apple", "Banana"]
There are several ways to iterate over arrays in JavaScript:
const fruits = ["Apple", "Banana", "Orange"];
// for loop
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// forEach method
fruits.forEach(function(fruit) {
console.log(fruit);
});
// for...of loop (ES6+)
for (let fruit of fruits) {
console.log(fruit);
}