Array Methods in JavaScript .

Ansh KotnalaAnsh Kotnala
5 min read

๐Ÿก Introduction โ€“ Arrays are Like Kitchen Dabbas

Imagine your momโ€™s kitchen โ€” thereโ€™s a steel rack of dabbas (containers), each holding something: dal, rice, atta, sugar. Thatโ€™s your JavaScript array โ€” a container that holds multiple values.

Each array method is like a different task you do in the kitchen โ€” picking out what you need, preparing, rearranging, or discarding.

Letโ€™s explore them with relatable Indian household scenarios:

Array Methods :

๐Ÿ› .forEach() โ€“ Checking All Dabbas One by One

Analogy: Mummy is doing a stock check. She opens each dabba, peeks in, and notes if it needs a refill.

const kitchen = ["rice", "dal", "atta", "sugar"];

kitchen.forEach(item => {
  console.log(`Checked ${item} dabba`);
});

๐Ÿ”น Purpose: Executes a function for each item.
๐Ÿ”น Use Case: Performing an action without changing the array.
๐Ÿ”น Returns: Nothing.


๐Ÿช” .map() โ€“ Adding Labels to Dabbas

Analogy: You decide to make cute labels for all the dabbas: โ€œRice (5kg)โ€, โ€œDal (2kg)โ€.

const dabbas = ["rice", "dal", "atta"];

const labeled = dabbas.map(item => `${item} (labelled)`);
console.log(labeled); // ["rice (labelled)", "dal (labelled)", "atta (labelled)"]

๐Ÿ”น Purpose: Create a new array by modifying each item.
๐Ÿ”น Use Case: Changing the format of data.
๐Ÿ”น Returns: A new array.


โŒ .filter() โ€“ Removing Empty Dabbas

Analogy: Some dabbas are empty. Mummy removes those from the main shelf.

const shelf = ["rice", "", "dal", "", "atta"];

const nonEmpty = shelf.filter(item => item !== "");
console.log(nonEmpty); // ["rice", "dal", "atta"]

๐Ÿ”น Purpose: Keep only items that match a condition.
๐Ÿ”น Use Case: Removing unwanted or invalid items.
๐Ÿ”น Returns: A new array with selected elements.


๐Ÿ” .find() โ€“ Locate a Specific Dabba

Analogy: Youโ€™re hunting for the sugar dabba in the stack.

javascriptCopyEditconst kitchen = ["rice", "dal", "sugar", "atta"];

const found = kitchen.find(item => item === "sugar");
console.log(found); // "sugar"

๐Ÿ”น Purpose: Return the first element that matches a condition.
๐Ÿ”น Use Case: Searching for a specific value.
๐Ÿ”น Returns: The item (not an array).


๐Ÿ“ .findIndex() โ€“ Finding the Dabbaโ€™s Position

Analogy: You found the tea dabba, but want to know where it is placed.

const items = ["salt", "tea", "coffee"];

const index = items.findIndex(item => item === "tea");
console.log(index); // 1

๐Ÿ”น Purpose: Find the index of the first matching item.
๐Ÿ”น Use Case: When position matters.
๐Ÿ”น Returns: Index number.


๐Ÿ›’ .reduce() โ€“ Combining All Quantities

Analogy: Youโ€™re totaling the weight of all dabbas to know how much ration is left.

const weights = [5, 2, 3]; // rice, dal, atta in kg

const total = weights.reduce((sum, kg) => sum + kg, 0);
console.log(total); // 10

๐Ÿ”น Purpose: Combine all values into one (sum, product, etc)โ€ฆhere second argument is the initial value of the sum i.e 0โ€ฆand then each weight is added to it.
๐Ÿ”น Use Case: Calculations on an array.
๐Ÿ”น Returns: A single value.


๐Ÿ” .some() & .every() โ€“ Quick Checks

Analogy:

  • .some() โ€“ โ€œIs any dabba empty?โ€

  • .every() โ€“ โ€œAre all dabbas full?โ€

const stock = [5, 3, 0, 2];

console.log(stock.some(qty => qty === 0)); // true
console.log(stock.every(qty => qty > 0));  // false

๐Ÿ”น Use Case: Validation and early checks.
๐Ÿ”น Returns: Boolean.


๐Ÿ” .slice() โ€“ Take a Few Dabbas Out

Analogy: You remove the first two dabbas to refill them, leaving the rest untouched.

const rack = ["rice", "dal", "atta", "sugar"];

const toRefill = rack.slice(0, 2);
console.log(toRefill); // ["rice", "dal"]

๐Ÿ”น Use Case: Extract part of an array without changing the originalโ€ฆextracts the items exclusively at ending index.
๐Ÿ”น Returns: A shallow copy of a portion.


๐Ÿ’ฅ .splice() โ€“ Replace Old Masala with New

Analogy: You remove spoiled masala and put in fresh ones at the same place.

const shelf = ["haldi", "mirchi", "garam masala"];

shelf.splice(1, 1, "jeera"); // remove 1 item at index 1 and insert "jeera"
console.log(shelf); // ["haldi", "jeera", "garam masala"]

๐Ÿ”น Use Case: Modify array by removing/replacing items.
๐Ÿ”น Returns: Removed elements.


๐Ÿงผ .flat() โ€“ Merge All Small Dabbas into One

Analogy: Mummy has smaller boxes inside a big box โ€” now you empty them all into a single big dabba.

javascriptCopyEditconst nested = [["dal", "chana"], ["rice", "sugar"]];

const merged = nested.flat();
console.log(merged); // ["dal", "chana", "rice", "sugar"]

๐Ÿ”น Use Case: Flatten nested arrays.
๐Ÿ”น Returns: A new flattened array.


Summary :

MethodDescriptionMutates Original ArrayReturn Type
forEach()Executes a callback for each element in the arrayโŒ Noundefined
map()Creates a new array by transforming each element using a callbackโŒ NoArray
filter()Creates a new array with elements that pass a test implemented by callbackโŒ NoArray
find()Returns the first element that matches the conditionโŒ NoElement or undefined
findIndex()Returns the index of the first matching elementโŒ NoNumber (-1 if not found)
reduce()Reduces the array to a single value using an accumulator functionโŒ NoDepends (any type)
some()Returns true if any element passes the testโŒ NoBoolean
every()Returns true if all elements pass the testโŒ NoBoolean
slice()Extracts a section of the array into a new arrayโŒ NoArray
splice()Adds, removes, or replaces elements in-placeโœ… YesArray (removed elements)
flat()Flattens nested arrays into a single-level arrayโŒ NoArray

Conclusion

JavaScript array methods offer powerful, declarative ways to manipulate and process data efficiently. By understanding their individual behaviors and return types, developers can write cleaner, more readable, and maintainable code.

Understanding when and how to use these methods leads to more expressive and performant code.

For a deeper dive into these methods, detailed syntax, browser support, and edge cases, it's highly recommended to explore the official MDN Web Docs โ€“ Array.

10
Subscribe to my newsletter

Read articles from Ansh Kotnala directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ansh Kotnala
Ansh Kotnala