Arrays and Common Methods in JavaScript
Arrays are used to store multiple values in a single variable. JavaScript provides many built-in methods to manipulate arrays efficiently.
📦 Creating Arrays
let fruits = ["apple", "banana", "cherry"];
let numbers = new Array(1, 2, 3, 4);
🔁 Looping Through Arrays
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
fruits.forEach(function(item) {
console.log(item);
});
🛠️ Useful Array Methods
push()
– Add to endpop()
– Remove from endshift()
– Remove from startunshift()
– Add to startindexOf()
– Find index of itemincludes()
– Check if value existsslice()
– Get part of arraysplice()
– Add/remove at index
let colors = ["red", "green", "blue"];
colors.push("yellow"); // ["red", "green", "blue", "yellow"]
colors.splice(1, 1); // ["red", "blue", "yellow"]
console.log(colors.includes("blue")); // true
🧠 Higher-Order Methods
These are especially powerful when working with data:
map()
– Transform each elementfilter()
– Select elements based on conditionreduce()
– Accumulate a valuefind()
– Find first matching element
let nums = [1, 2, 3, 4, 5];
let doubled = nums.map(n => n * 2); // [2, 4, 6, 8, 10]
let evens = nums.filter(n => n % 2 === 0); // [2, 4]
let total = nums.reduce((sum, n) => sum + n, 0); // 15
💡 Tip: Arrays in JavaScript are flexible and dynamic. You can mix data types, nest arrays, and use them like lists or stacks.