As we all know, in our daily coding, for some data iteration and traversal, the first thought is for loop

The syntax of the for loop is very simple. You only need to know the length of the data list to iterate over the value. For example:

A little programming basic children’s shoes, can quickly think of the above preparation method. That don’t know whether you would like me to write a for loop, the function is no problem, but always feel to write is not very elegant, such as to define the corresponding variables (with the above example), and I will control the I variable changes, so will no doubt become cumbersome, also can let us write code efficiency declined

Ok, so is there some elegant way we can handle this case? The answer is yes, which brings us back to the subject of this article: How to gracefully improve the for loop?

ForEach

I believe that learned ES6 children’s shoes, will soon think of this method, I take the above example to transform:

This approach, which seems much more elegant, eliminates unnecessary definition and control of queue length comparison variables and queue length judgments

At this point, is ForEach the best elegant solution? Is there a problem? , believe that part of the children’s shoes may not be able to answer, that I do not keep in suspense. If we have a situation where we need to return a processed array after traversing a list, would continuing with forEach serve our purpose? We might do the following:

As you can see, the first method is to assign to a variable directly after processing, but the forEach loop returns undefined. The second method, although it does achieve our goal of retrieving the processed data, causes a problem — global variable contamination. Of course, we can also make an external array and push the processed data into the new array to achieve our goal, but the whole thing still doesn’t look very elegant.

Is there a way to return a new array without affecting the original data? The answer is yes, which requires the powerful Functional Programing(REFERRED to as FP).

Functional Programing

What is FP? What is it for?

Functional programmings(FP) means coding in functions

That’s the succinct and official way of saying it. What does that mean? In a nutshell, it is a function approach to problems, and one of its core ideas will be used today: pure functions (for the same input, always get the same output, without any side effects).

See here is a little clue 😄. Anyway, back to the point, what methods in JS are pure functions that can elegantly replace the for loop? I believe that children will think of map()

Map()

The Map method iterates through each element in the original array and calls callback, eventually returning a new array without affecting the original array.

Let’s take the aforementioned chestnut with the problem of forEach and transform it:

Obviously, the old multi-line loop can be done in one line, looks a lot more elegant, and returns a new set of elements without polluting the original array

Filter()

The Filter method simply filters an array and returns a new array without affecting the original array

This brings us back to the for loop: Can we use the Filter method to make our code elegant? Let’s do it now:

Obviously, using the Filter method only achieves the first step, which is to elegant the conditions in the for loop. So what do we do?

We can see that the Filter method returns a new array, so we can relate to the Map method. What happens when the two methods are combined?

At this point, does it look a lot more comfortable and easy to understand, and this is the ultimate elegant solution. So the question is, when should you use forEach and when should you use map?

ForEach is better for doing things with the array data without changing the original array data, whereas map is better for changing the value of the data and returning a new array. Of course, it varies from situation to situation, but this is just a reference

Extension

In addition to the common scenarios mentioned above, we will encounter many other places where we can continue to elegant for loops, which brings us to some methods and every methods and reduce methods (reduce is also FP).

  1. Every () and Some ()

    There is now a scenario where the prompt is displayed when the cost is below zero based on a list returned from the back end. Combined with the methods learned above, maybe we will do the following:

    In addition to the more direct methods mentioned above, some children may want to use forEach directly for elegance:

    Because forEach handles the data on callback, using break syntax would obviously cause a syntax error, so even if break is omitted, all elements would need to be iterated through, and some and every would be called:

    • Some: Iterates over a group of elements, returning true whenever a condition is true, and false otherwise

    • Every: iterates over a group of elements. If false is encountered, false is returned. Otherwise, true is returned at the end of the loop

    Obviously looking at the amount of code is much simpler, but also elegant 😆.

  2. reduce()

    For those of you who are unfamiliar with the Reduce method, what exactly is it for? What are the application scenarios?

    The reduce() method receives a function as an accumulator, where each value in the array (from left to right) is reduced to a single value

    Iterating through a list, taking two elements to get a new value, then taking that new value to the third element on the next iteration, and so on, finally getting a value and returning it. Text too complex, direct diagram:

    Isn’t that much clearer, and what are the elegant scenarios of the application? I’m not going to keep you in the loop here, for example, if the back end returns an object, and we need to do something with that object just by getting the specified property value, the extra properties are filtered out. Daily practice:

    As you can see, the double loop makes people look really complicated, and it can easily go wrong if you’re not careful. Using the Reduce approach, however, can be elegant

    After reading this, do you feel that reduce is very simple and elegant after being used?

    If you don’t think it’s powerful enough, take a look at the next chestnut to see how powerful it is (this is an extra topic for you to study at your leisure). We often encounter a situation where the back end returns a deeply nested object, and when the front end gets an attribute in the complex object, it will inevitably need to check the existence of each value, and then reach the specified attribute. This is the chain value problem:

    In fact, there are many solutions to the chain value problem on the Internet, so if it is the most elegant solution, I think it is to use reduce method, then how to write using reduce? Directly above

    So far, for the elegance of the for loop, different scenarios can have a lot of elegant solutions, but I want to say that native JS API itself provides a lot of ways to make our program convenient and concise, only if you use it more, you will realize its power. Ha ha, if above if have improper place, welcome everybody big guy to give directions 👻

Last

Now that you know what the for loop is (I guess), let’s end with a common interview question to get you thinking about the best way to do it:

Implement a method that counts the number of occurrences of each character in a string?

Method I don’t write, let everyone come to a brainstorming 🙈