Definition
An array is an ordered collection of values stored in a single variable. Each value in an array is called an element, and every element has an index. Array indexing starts at 0.
const fruits = ["Apple", "Banana", "Orange"];
console.log(fruits);
Why Do We Use Arrays?
Without arrays, you would need multiple variables to store similar data.
Accessing Array Elements:
Access elements using their index.
const fruits = ["Apple", "Banana", "Orange"];
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
Modifying Array Elements
You can update an element by assigning a new value to its index.
const fruits = ["Apple", "Banana", "Orange"];
fruits[1] = "Mango";
console.log(fruits);
Finding the Length of an Array
Use the length property.
const fruits = ["Apple", "Banana", "Orange"];
console.log(fruits.length);
Adding Elements
push()
Adds an element to the end of the array.
const fruits = ["Apple", "Banana"];
fruits.push("Orange");
console.log(fruits);
unshift()
Adds an element to the beginning.
const fruits = ["Banana", "Orange"];
fruits.unshift("Apple");
console.log(fruits);
Removing Elements
pop()
Removes the last element.
const fruits = ["Apple", "Banana", "Orange"];
fruits.pop();
console.log(fruits);
shift()
Removes the first element.
const fruits = ["Apple", "Banana", "Orange"];
fruits.shift();
console.log(fruits);
Looping Through Arrays
Using a for Loop
const fruits = ["Apple", "Banana", "Orange"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Using for...of
const fruits = ["Apple", "Banana", "Orange"];
for (const fruit of fruits) {
console.log(fruit);
}
Using foreach();(TBD)
const fruits = ["Apple", "Banana", "Orange"];
fruits.forEach((fruit) => {
console.log(fruit);
});
Top comments (0)