Finding what iterator to use and when from a beginner!
Tags: javascript, beginners, programming, tutorial
Published: 2024-05-30 04:53:57

Hello, my name is Kaleb and I'm a beginner at coding. I am an active student at Flatiron School and our first phase is javascript. Learning arrays and objects was easy, but adding them together and iterating over them was extremely difficult. I will be going over some the iterators as I understand them and give detailed examples. When I was doing research it was difficult to understand which to use and why. 

The iterators I will be going over are:
.forEach()
.map()
.find()
.filter()


Starting with forEach() this is an iterator that does something for each value or object in the array. This is an iterator we learned with little value in the real world from my perspective. forEach is a loop as well, it can be used to console log elements in the array like the example below. 

numberedArray = [1,2,3,4,5,6,7,8,9,10]


numberedArray.forEach(function (number) {
  console.log("What number is being logged" + number);
});

This will console.log:
What number is being logged1
What number is being logged2
What number is being logged3
until it reaches 10 and then will stop.
this can be useful to see what values you are getting or for debugging. forEach is not something I personally would learn due to .map outshining it, forEach returns the same array but changed where .map returns a new array.

the map() definition that I believe explains this very well is: The map() method of Array instances creates a new array populated with the results of calling a provided function on every element in the calling array.
 
What does this actually mean? how does it work? what does it look like?

first, we should break down the definition it is a method that creates a new array populated with results from the provided function on EVERY element. exactly like the forEach iterator it goes through the [1-10] and does something on everyone and provides a NEW array. 
Second let's see it in use to wrap our head around when and why we would use it. For example, We only want the last names of the guests staying at the hotel we run. our data might look like this:

let guests = [
  { firstName: 'Bob', lastName: 'Joeseph'},
  { firstName: 'Tracy', lastName: 'Miller'},
  { firstName: 'Siera', lastName: 'Allen'}
]

const lastNamesOfGuests = guests.map(firstAndLastNames => firstAndLastNames.lastName)
console.log(lastNamesOfGuests)

it will return: [ 'Joeseph', 'Miller', 'Allen' ]

Let's walk through it, We set a variable name for guests that is an array of objects and those objects have the first and last names of our 3 guests. We are setting lastNamesOfGuests to equal our variable guests and calling .map then we are passing in the objects it is going to each one and grabbing the .lastName and implicitly returning the strings inside a new array.

Now that we understand both of those we are finishing it up with my favorite combo the .find and .filter iterators and personally my favorite to use. .find is very easy to understand its job is to find something and return it once found, if nothing is found .find returns undefined and filter returns a new array with no elements looking like []. The difference between .find and .filter is once find gets a match it will stop looping and return that element. in our example, if we wanted all the fruits and vegetables starting with the letter B. Find will only return the banana in our example below.



let fruitAndVegetables = ['apple', 'banana', 'broccoli', 'carrots']

const namesWithB = fruitAndVegetables.find(fruitAndVeg => {
    return fruitAndVeg.toLowerCase().startsWith("b")
})
console.log(namesWithB)
This will return: banana

small explanation on why I used .toLowerCase() and .startsWith(), toLowerCase makes all of the elements lowercase making it so if banana was a capital B it would still start with lowercase b. making our search case insensitive. the startsWith is very self-explanatory but if it starts with what is in the () it will match and return those elements.

.filter is very similar to .find but has some key differences. The filter offers more than 1 match and returns a new array with the match from the search. an example will show you the differences very nicely. in our example, we changed one word and got both bana and broccoli. we changed find to filter. find returns the first match and stops the loop, filter goes through and makes a new array and populates it with all the matches from the elements passed in.



let fruitAndVegetables = ['apple', 'banana', 'broccoli', 'carrots']

const namesWithB = fruitAndVegetables.filter(fruitAndVeg => {
    return fruitAndVeg.toLowerCase().startsWith("b")
})
console.log(namesWithB)
This will return: [ 'banana', 'broccoli' ]








// used the definition for map() 
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map