So there are native methods, utility library methods that are in popular frameworks like lodash, and then there is the idea of making my own, application specific custom solutions for a project. That is using any or all of these solutions to make some kind of method or module that loops over the contents of a given array, or collection of any kind, but provides an API to be provided in the body of a function that is called for each element in the collection. So then this way I create my own custom forEach method of sorts that has everything that I want to work with in the body of the function that is called for each item via a function argument, or the this keyword. Such For each methods can be designed to work just the way I want them to, without any unnecessary bloat.
I might not get into all of them in detail here in this section, as I want to keep the source code examples here in this section simple. However I have a number of more advanced section in this post and I will also be linking to any and all additional posts that are relevant here and there as needed.
This is one of a few posts that I do get around to editing a little now and then, and the test vjs repository would be where I have the latest revisions of what I am working on as well as notes for any and all future edits. The test vjs Github repository would be a good place to make a pull request if you are on Github and have found a reason why doing so might be justified. There is also the comments section in this post that can be used to bring something up that might need to chance or can be added to the over all content of this post in some way.
So a basic example of Array.forEach might just involve using it to loop over the contents of an array of numbers, and add up the numbers in the array to a variable that will serve as a sum of those numbers. So such an example might look something like this then.
Although this might work just fine with such a trivial task, there are many other ways to go about doing a simple sum of numbers in an array. The array reduce method might prove to be a more appropriate way of going about adding up a sum actually for example. There are of course more options to work with in the array prototype other than just the array for each method after all.
Also In real projects what might need to happen for each element in an array might end up being far more complex than just adding up each number in the array. There might come a time where I might not want to start at index 0 each time, or I might want to do something with each array index and so forth. Once again these are reasons while I tend to prefer while loops, however I do fine myself using these convenience methods now and then.
So lets look as some more basic examples that make use of other array prototype methods that work in a similar way to that of the array for each prototype method. After this section we can start to look at loops, and custom user space options for specific tasks when it comes to making custom for each style methods.
On top of the first argument of the function that is called for each element being a reference to the current element value, the second argument will be the index value of the current element also. In addition the third argument will be a reference to the array in which for each is being called off of. Many other similar Array prototype methods follow this pattern where the first argument is the current element of the array, and the second argument is the index value of that element.
Simply put the array for each method might not always be the best choice for the job when it comes to looping over the contents of an array, let alone any kind of collection when dealing with objects in general. There is no golden hammer when it comes to looping over an array. In some cases it will work just fine, bit often I might use one of the many other array prototype methods, a loop of one kind of another, or maybe I still will use the array for each method just not by itself because there are some additional things I need to do first to get the array that I want to begin with.
So then it is not so hard to make a user space solution for looping over the contents of an array, or Object in general just like that of the for each method of lodash. In the above example I am using the Object.keys method to get a collection of public key values for any given object regardless if it is an array, or just a plain old object. In the event that is is an array then the returned array will be all the numbered index values, in the event that it is a plan old object the returned array will be any and all public key names, whatever they may be.
Some options for looping over the contents of an object might be more readable, others might be or more flexible with a greater number of objects, but performance takes a hit. While loops might be fast, and can be even faster depending on how and where they are used when it comes to defining what the expressions are for figuring out of looping should continue or not. In addition the break and continue keywords can be used in the body of the loop in some ways that can help for a loop to run along even faster, but often might end up being a lengthly block of code that might prove to be a littler harder to follow as there is not much of anything being abstracted away.
One of the nice things about for each is that it does help with readability of code I would say that the name alone is pretty clear as to what it does. However when it comes to performance it is not at all one of the best options. The main reason why for each is slow may have to do with function calls, the for each method will make an awful lot of them with a large array where a while loop will make node aside form any function calls that happen in the body of code that is being called for each iteration which would happen anyway.
However do not just take my word for it that while loops are way faster, confirm it to yourself by working out a little code like this:
Another option would be to feature test and monkey patch using something like this that I pulled from the Mozilla page on the array forEach method.
When it comes to doing anything that might involve a sum of any kind, it might be better to use Array.reduce in place of array for each. This reduce method works just like array for each in the sense that I call if off of an instance of an array, and pass a function as an argument. However this time the first argument is an accumulator value and then the n next element is the current value of the current element. The idea here then is that I add to the accumulator and then return the accumulator value that will then be there to worm with in the next call, and so forth creating and end result that will be returned at the end.
This is one of many other Array prototype methods that work in a very similar way to that of Array.forEach, but will behave a little differently and create. For one thing the Array.reduce method does not start looping at index 0, but rather index 1. The reason why is that the first element at index 0 is the initial value of an accumulator argument that is the first argument that is given to the function that is passed to Array.reduce. So in this example the value of s starts out as 1 and the value of r is 2, then on the next call the value of s is 3 and the value of r is 3 making the final value that is reduced to 6;
Another way to loop over elements in an array is to use the Array.map method which will also come up a lot in come examples. This method works more or less the same way as Array.forEach but with one significant difference. That difference is that whatever is returned in the method that is given as an argument this time will become that element in the array. Actually the new element will be in a new copy of the array that can then be reassigned to the array or not. So in a way the array map method is in line with functional programing in the sense that the array that that the prototype method is called off is not mutated in place.
2.3 - Array filter for creating a new array that is only a few elements from another that meet a given condition.
Yet another alternative array prototype method to the for each method might be the filter method. As the name would suggest this can be used to filter out elements from an array that are not wanted. Also like that of the array map method this will create and return a new array rather than mutating an array in place. To use this method I just need to call the array filter method off of the array that I want to use it with and pass a function that will be used to preform the filter. Inside the body of this function I just need to create and return a boolean value. If the boolean value is true then the current element will be in the new array, else it will not.
Often the method might prove to be a more concise alternative to using the array reduce method, but that method can also of course me used in filtering related tasks. The reduce method is typically used to create a single privative value form an array of values, but of course I can set the initial accumulator value to that of an array, and then just push into that new array what I want in the body of the method that I use with reduce. Still this filter method is nice in the sense that it is all about just returning a true or false value for each element in an array as a way to create a new array with values filtered out that I do not want.
There are also methods like array some, and array every that can be used to create and return a boolean value for an array depending on the condition returned in the method given. Say you want to test if just one element in an array meets a given condition for that there is the array some method. In addition there is the array every method that will return true if all elements in the array meet a given condition.
On top of the array some method there is also the array every method that can also be used to create a boolean value from the array that it is called off of with a method that will be used for each element in the array. Unlike the array some method this will only result in a true boolean value of all of the elements in the array meet the given condition that will be called for each element in the array.
In addition when using a while loop keywords such as break and continue can be used to skip things completely which can come in handy how and then. Another thing about loops is that I am not defining logic in a method so I can use the return keyword in the body of the logic in the while loop if it is in the body of a function to stop the loop.
Yet another advantage is that while loops can often prove to be a little faster then array for each when it comes to benchmark testing. The main reason why would have to do with function calls, the array for each method as well as all of the array prototype method will end up making a lot of them when working with a large array. This might not be a big deal when it comes to small arrays, but if I am working with arrays that are large enough I have found a significant difference in the amount of time it takes for the array for each method to loop over all elements which odes in fact take longer when compared to a while loop.
So the a basic example of a while loop could just be using an index variable that is set at zero for starters. Then I check if the index variable is greater than the length of the array as the condition for the while loop. Inside the body of the while loop I will want to step the index variable or else I will end up with an infinite loop. I can then use the bracket syntax inside the body of the while loop to get the current element of the array by using the index value as the value to use with the bracket syntax of the array.
There is of course more than one way to skin a cat when it comes to while loops, and loops in general. What is great about loops is that I have control over the conditions for how to go about breaking the loop, how to go about stepping an index value, and also how to start looping in the first place. For example I can just start off the index variable at the end of an array, and loop backwards. Also because the number zero evaluates to false I can also have the index variable double as a way to break the loop.
Another major advantage of using loops like while loops over array forEach is that I can set the starting condition, and ending condition in terms of the array index value. I can if I want start looping at an index value greater than zero, and end before I get to the end of the array for example.
There is of course also the array slice method that can also be used to get a new array that is a range of another array. However I would need to know both the starting and ending index values. With a while loop I can make coming across some kind of value a way to stop looping.
There is also of course using the return keyword in the body of a function that will be used to return something, and the fact that when using the array forEach method I am working inside the body of a function. So when doing something that involves nesting loops, or even just using one loop I can not just use the return keyword in the body of a method that is passed to array for each.
However with while loops I can place that return keyword anywhere in a single while loop, or even one or more nested while loops, and the return keyword will break out of the whole situation with looping and given me what it is that I wanted returned.
In addition to the return keyword there is also the break keyword that can be used even when working out a loop that is top level code outside of a function that can be used as yet another way to accomplish a similar result that can not be done with array forEach.
However often in javaScirpt I come across Objects that are formatted like an Array, but they are an instance of another kind of constructor. these kinds of objects have key value pairs where each key name is a number rather than a named key, and there is a length property that reflects the number of these key value pairs. Sometimes the values of these objects might be read only, but even then it is possible to get a method like Array.froEach to work with these it just requires some trickery with Function.call, or Array.from.
An Example of an Array like object might look like this
So in this section I will be outlining some ways to loop over these kinds of objects.
The Array.from method is one way to go about converting one of these array like objects into an Array. Once that is done it is possible to use some Array prototype methods such as Array.forEach
The array from method is one way to go about creating an array from an array like object. I just pass the object to array from when calling it, the returned result is an instance of array to which I can then use the array for each method, or any array prototype method.
Another trick is to leverage the power of Function.call. If you are not familiar with Function.call, Function.apply, and Function.bind it would be a good idea to look into them at some point. If any kind of object has properties that will work with a prototype method of another it can be done with these Function prototype methods.
That is nit to say that there are draw backs to using a for in loop, there are of course. For one thing it is a little slow compared to other options that there are to work with in more modern environments. Maybe the main point of concern is that a for in loop will only loop over public keys.
The Object values method is one way to loop over the contents of an object in general in terms of key values. Assuming that all the key names that I want to loop over are public, I do not need the key name values, and I do not care about anything that might be in the prototype chain. The method works by creating and returning a new array where each element in the array is a value of one of the public keys of the object that was given to the Object.values method. So then because it is an array that is returned I can then use any array prototype method that I want after that, including the array for each method.
So on top of the Object values method there is also the Object.keys static method also. This method works the same way as Object values only it returns an array of key names rather than the values of the keys. In any case this can be used to quickly create an array from a plain old object and then of course array prototype methods can be used with that resulting array, and not just array forEach.
All of the examples that I have covered thus far in this section have to do with public own properties of an object, but not private ones. If you are not familiar with the define property static method of the Object global it might be a good idea to look into that more at some point. One of the key features of this define property method is that it can be used to define property of an object that have special values one of which is to make it so that the key is not public, or enumerable actually which might be a better term actually. Sense the object property can still be accessed if not is not set as being enumerable it is just that it will not show up in a for in loop, and the key name will not show up in an array created with the Object.keys method.
There is however another method of interest that is like the Object keys method but will always give a full like of own properties of an object. This method is called the Object get own property names method which is a method that when called will give a full array of key names for objects that have these kinds of hidden properties.
In the basic section I covered a methods that will work well with objects in general it made use of the Object.keys method as a way to get all public key names for an object, and used that returned array as a way to set the len value when it comes to looping over the contents of the object. One added feature that I included is the ability to stop the looping by returning a value in the function that I give to for each that will evaluate to true.
Although I have not took the time to make use that this method really truly is spec compliant to array for each when it comes to arrays at least it seems to behaves more or less the same way as array for each when it comes to the nature of skipping over empty elements when I give a sparse array.
One additional feature that I might want to add to a general for each collection method is a mode that will cause the method to work in a kind of sparse array mode. That is to have a mode that will use the length value of the source object rather than an array that is returned by giving the source object to the Object.keys method. Also this sparse mode would change the way that I am getting key names and values going by a logic that is just simply a current index value and the value at that index if any, rather than an index and value based of the results of a key array from Object.keys.
So nw I have a for each method that will work well with collections in general, and also give me a little extra flexibility when it comes to working with a sparse array in which I want to do something with empty element locations.
Simply put I like to use different tools for the job, and also try to always pick the best choice depending on the situation. There is readability which I would say is of value, but of course the same is to be said about performance. There is functional programing which is great, but there is also working with classes, state, and other ways of programing that are not necessary inherently inferior. There is trying to be perfect, and then there is just getting together a working proof of concept today rather than six months from now. So just pick a way to loop, and move on with your project, and your life.