Learning Iteration: A love story (or the opposite, really)

tmontobbio

Tyler Montobbio

Posted on August 8, 2022

Learning Iteration: A love story (or the opposite, really)

What is iteration?

This was the first question I had when exposed to the abstracts that make up JavaScript methods. I didn't love all these concepts, in fact most of them made my brain hurt. I am by no means an expert, merely a student sharing his journey.

Reading pages upon pages of text and code can be daunting, stressful even. When reading about iterators I asked myself, "Why the heck would you need to "go through" or iterate over an object or array?". After a couple weeks of bombarding my brain with various other concepts it became clear to me.

To show where my learning started, here's an example.

const numbers = [1, 2, 3, 4];

for (num = 0; num < numbers.length; num++) {
  console.log(numbers[num]);
} 

//=> [ 2, 3, 4, 5 ]
Enter fullscreen mode Exit fullscreen mode

This kind of makes sense, right? I chose num to represent the numbers in our array; num starting at zero, while num is less than(total length), increment num by 1 - until it reaches the length of the array. Pretty neat! This concept is easy to understand, there are many uses for incrementing numbers.

The one that boggled my brain..

The concept that took me a while to understand, going back to my preface; ...bombarding my brain with various other concepts it became clear to me... is the forEach() loop. The forEach() loop is interesting, it does exactly what it says, "Iterate through this object or array and for EACH of these items, do this!".

A simple example, lets add 1 to each item in our array.

const numbersArray = [1, 2, 3, 4];

numbersArray.forEach((num, index) => {
  numbersArray[index] = num + 1;
});

console.log(numbers);

//=> [ 2, 3, 4, 5 ]
Enter fullscreen mode Exit fullscreen mode

While this also makes a lot of sense at first glance, both of these concepts can be applied to bigger, more complex things. The one I'm really trying to focus on is the forEach() loop.

forEach(biggerTHING)

I truly realized the power of the forEach() loop when I started learning about appending elements to the DOM. In JavaScript we can start with our basic HTML as you may know, and determine some CSS rules to stylize our headers, paragraphs, ect. In a situation where we have multiple elements on a page, with the same basic structure (think of yelp results displaying restaurant info) we can avoid the repetition of hard-coding each restaurant card containing all the same relevant info by using a forEach(). This also makes our code more dynamic; one day there might be 10 restaurants that fit our search criteria, but the next day, two more might open up. Writing code in this way makes our function reusable no matter how many results remain relevant without the need to go back and un-do, or re-do our hard coded restaurant cards.

Here's an example...

// Our returned fetch object:

 const restaurant = {
    name: "Midtown Sushi",
    rating: "4.3",
    location: "2801 P Street",
  };

Enter fullscreen mode Exit fullscreen mode
  // To keep it simple, lets pretend that searchQuery is a
  // form that calls this function when you search for food.

  searchQuery.addEventListener("submit", (e) => {
    e.preventDefault();

    const restaurantQuery = (rest) => {
      // Select our list and give it a variable name
      const restaurantList = document.querySelector("#restaurant-list");
      // Create a 'home' for each of our fetch data items
      const card = document.createElement("div");
      card.className = "rest-info";
      const header = document.createElement("h2");
      header.textContent = rest.name;
      card.append(header);
      const rating = document.createElement("p");
      rating.textContent = rest.rating;
      card.append(rating);
      const location = document.createElement("p");
      location.textContent = rest.location;
      card.append(rating);
      // Append that new 'card' to our list
      restaurantList.append(".rest-info");

      fetch("http://your-local-restaurant-api.com")
        .then((r) => r.json())
        .then((data) => data.forEach((restaurant) => displayCard(restaurant)));
    };
  });

Enter fullscreen mode Exit fullscreen mode

This example is missing tons of relevant data, and much more complex that I could really fit on a single blog post.

Really the point is, that when designing a dynamic website, we can fetch relevant data, and use JavaScript to give that data homes for their key/value pairs. forEach() of our restaurant cards, we make this template do the work for us! This kind of template gives us so much flexibility and makes it possible to re-use snippits of code instead of having to go back all the time and edit stuff.

Conclusion

While this topic goes much deeper than what I've shown, its a good illustration of the power JavaScript gives us in web development. Iteration provides a unique tool to a repetitious problem, it allows us to apply simple (or complex) actions to help us avoid repetition. I'm still learning, and I'm sure there's mistakes in my examples but I hope this will help a beginning developer understand a little bit more about iterators and their value within our code. If you think there's a better, simpler, or even just a cleaner way to illustrate my example please drop a comment below and I can edit this!

Thanks for reading!
-Tyler

💖 💪 🙅 🚩
tmontobbio
Tyler Montobbio

Posted on August 8, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related