Array Methods In JavaScript

Adding and Removing: push() and pop()
Think of these like a stack of cafeteria trays. You add to the top and take from the top. These methods affect the end of the array.
push(): Adds an item to the end.pop(): Removes the last item.
let fruits = ["Chai", "Code"];
// Adding an item
fruits.push("Coffe");
// Result: ["Chai", "Code", "Coffe"]
// Removing the last item
fruits.pop();
// Result: ["Chai", "Code"]
The Front Runners: shift() and unshift()
These are the opposites of push/pop. They handle the beginning of the array.
unshift(): Adds an item to the front.shift(): Removes the first item.
let queue = ["Hitesh", "Piyush"];
queue.unshift("Mr.Ambani");
// Result: ["Mr.Ambani", "Hitesh", "Piyush"]
queue.shift();
// Result: ["Hitesh", "Piyush"]
Transformation: map()
map() creates a new array by doing something to every item in the original array. It's like a factory assembly line where every raw material gets processed into a finished product.
Traditional for loop vs. map():
Method | Code Style |
For Loop | Requires a counter, manual array creation, and |
Map | Clean, one-liner, and returns the new array automatically without changing the original array. |
const prices = [10, 20, 30];
// Goal: Add $5 tax to each price
const taxedPrices = prices.map(price => price + 5);
console.log(taxedPrices); // [15, 25, 35]
console.log(prices); // [10, 20, 30]
The "Big Boss": reduce()
reduce() can be intimidating, but think of it as a juicer. You put in many fruits (items) and get one glass of juice (one single value). It "reduces" the entire array to one number, string, or object.
Accumulator: The "running total."
Current Value: The item currently being processed.
const numbers = [1, 2, 3, 4];
// Goal: Find the total sum
const total = numbers.reduce((accumulator, current) => {
return accumulator + current;
}, 0); // 0 is the starting point
console.log(total); // 10
Action: forEach()
Use forEach() when you want to "do something" with every item (like logging to the console), but you don't need to create a new array.
const names = ["Hitesh", "Piyush", "Akash"];
names.forEach(name => {
console.log("Hello, " + name + "!");
});