SmartCodingTips

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 end
  • pop() – Remove from end
  • shift() – Remove from start
  • unshift() – Add to start
  • indexOf() – Find index of item
  • includes() – Check if value exists
  • slice() – Get part of array
  • splice() – 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 element
  • filter() – Select elements based on condition
  • reduce() – Accumulate a value
  • find() – 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.