Arrays in JavaScript
Arrays are ordered collections of values that can hold multiple data types
(numbers, strings, objects, etc.). They are one of the most commonly used data
structures in JavaScript.
Creating Arrays
// Using array literallet fruits = ["Apple", "Banana", "Cherry"]; // Using the Array constructorlet numbers = new Array(1, 2, 3, 4); console.log(fruits); // ["Apple", "Banana", "Cherry"]console.log(numbers); // [1, 2, 3, 4]
Accessing Elements
let fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits[0]); // Apple (first element)console.log(fruits[2]); // Cherry (third element) // Changing an elementfruits[1] = "Blueberry";console.log(fruits); // ["Apple", "Blueberry", "Cherry"] // Array lengthconsole.log(fruits.length); // 3
Common Array Methods
let fruits = ["Apple", "Banana", "Cherry"]; // push() - Add to endfruits.push("Mango");console.log(fruits); // ["Apple", "Banana", "Cherry", "Mango"] // pop() - Remove from endfruits.pop();console.log(fruits); // ["Apple", "Banana", "Cherry"] // shift() - Remove from startfruits.shift();console.log(fruits); // ["Banana", "Cherry"] // unshift() - Add to startfruits.unshift("Strawberry");console.log(fruits); // ["Strawberry", "Banana", "Cherry"] // slice() - Copy part of arraylet newFruits = fruits.slice(1, 3);console.log(newFruits); // ["Banana", "Cherry"] // splice() - Add/Remove items at specific indexfruits.splice(1, 1, "Kiwi"); // Remove 1 element at index 1 and add "Kiwi"console.log(fruits); // ["Strawberry", "Kiwi", "Cherry"]
Looping Through Arrays
For Loop
let fruits = ["Apple", "Banana", "Cherry"]; 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(fruit, index) { console.log(index, fruit);});