Skip to main content

Command Palette

Search for a command to run...

Iteration Methods in Javascript

Published
•2 min read•View as Markdown
Iteration Methods in Javascript
D

Hi, I'm Dikshant – a passionate developer with a knack for transforming ideas into robust, scalable applications. I thrive on crafting clean, efficient code and solving challenging problems with innovative solutions. Whether I'm diving into the latest frameworks, optimizing performance, or contributing to open source, I'm constantly pushing the boundaries of what's possible with technology.

On Hashnode, I share my journey, insights, and the occasional coding hack—all fueled by curiosity and a love for continuous learning. When I'm not immersed in code, you'll likely find me exploring new tech trends, tinkering with side projects, or simply enjoying a great cup of coffee.

Let's connect, collaborate, and build something amazing—one line of code at a time!

Here’s a short and easy way to remember JavaScript array methods:

🔹 Iteration Methods

  1. forEach → Runs a function on each item (No return).

     [1, 2, 3].forEach(num => console.log(num));
    
  2. map → Creates a new array by transforming each item.

     const squared = [1, 2, 3].map(num => num * num); // [1, 4, 9]
    
  3. filter → Creates a new array with items that pass a condition.

     const evens = [1, 2, 3, 4].filter(num => num % 2 === 0); // [2, 4]
    
  4. reduce → Reduces an array to a single value.

     const sum = [1, 2, 3, 4].reduce((acc, num) => acc + num, 0); // 10
    

🔹 Checking Methods

  1. some → Returns true if at least one item meets a condition.

     [1, 2, 3].some(num => num > 2); // true
    
  2. every → Returns true if all items meet a condition.

     [1, 2, 3].every(num => num > 0); // true
    

🔹 Finding Methods

  1. find → Returns first matching item.

     [1, 2, 3, 4].find(num => num > 2); // 3
    
  2. findIndex → Returns index of the first matching item.

     [1, 2, 3, 4].findIndex(num => num > 2); // 2
    

🔹 Sorting Methods

  1. sort → Sorts array (modifies original!).

     [3, 1, 4].sort((a, b) => a - b); // [1, 3, 4]
    

🔹 Conversion Methods

  1. toString → Converts array to a string.
[1, 2, 3].toString(); // "1,2,3"
  1. join → Joins array items into a string with a separator.
[1, 2, 3].join('-'); // "1-2-3"

🔹 Modifying Methods

  1. slice → Extracts part of an array (does not modify original).
[1, 2, 3, 4].slice(1, 3); // [2, 3]
  1. splice → Adds/removes items (modifies original).
const arr = [1, 2, 3];  
arr.splice(1, 1, 99); // [1, 99, 3]

🔹 Index Methods

  1. indexOf → Finds first index of a value.
[1, 2, 3, 2].indexOf(2); // 1
  1. lastIndexOf → Finds last index of a value.
[1, 2, 3, 2].lastIndexOf(2); // 3

🔹 Flattening Method

  1. flat → Flattens nested arrays.
[1, [2, [3]]].flat(2); // [1, 2, 3]