BG Photo by Sepp Rutz on Unsplash

JS Array iterators cheat sheet — Part 1

Krishna Damaraju
Nov 12 · 3 min read

Iterator methods are helpful and slightly confusing if you don’t understand the slight differences between them. This cheat sheet discusses the contrasting differences between forEach , map , filter andsome

⭐️ Array.prototype.forEach

  • Usage: An alternative to for with advantages of scoping. Use this when no other function fits your needs.

callback — A function to be called after the current code execution.

  • Returns: undefined

Mutate — Change the original copy

  • Breaking the loop: Cannot skip the loop execution.

Chainable — A method to pass the returned value to the other function.

  • On Data change: Any new data added after the loop execution will be ingnored. Any data modified or deleted will be provided Chainable to the forEach when forEach visits it. Any modifications to the processed data will be ignored and deletion of the processed element might make the next element in the loop to be skipped due to the change of index.
let things = ['scissor', 'paper', 'rock', 'pen', 'paperclip']//1
things.forEach((element, index, arr) => {
if(element === 'pen') arr.push('ring');
console.log(element);
}); // prints scissor, paper, rock, pen, paperclip. ring is ignored.
// 2
things.forEach((element, index, arr) => {
if(element === 'pen') element[index+1] = "ring";
console.log(element);
}); // prints scissor, paper, rock, pen, ring. paperclip value is changed before it is visited.
//3
things.forEach((element, index, arr) => {
if(element === 'pen') arr.shift(); //pops 'scissor'
console.log(element);
}); // prints scissors, paper, rock, pen. 'paperclip' will be ignored since the index positions are updated -1. Any other element next to the immediate element of the current index will not be skipped.
  • Empty arrays/elements: Will be ignored.

⭐️ Array.prototype.map

  • Usage: use this when you want to transform the given array. If you use case is not to return anything, use forEach or for...of

⭐️ Array.prototype.filter

  • Usage: To filter an array based on a given condition.If you need to return the first element matched, use Array.prototype.find()

⭐️ Array.prototype.some

  • Usage: Returns true if at-least one element passes the provided condition in the callback or else false

Hope it is helpful and would like to know your thoughts.

Cheers 🙌
KD

Small Things

Coding tips for beginners

Krishna Damaraju

Written by

JS Developer working with EmberJs and ReactJs. Find me at https://krishnasarath.xyz

Small Things

Coding tips for beginners

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade