1. Iterate through an
A HTMLCollection is a special kind of array you would have dealt with if you do something like
document.getElementsByTagName() etc. ES6 comes handy with a way to convert these collections into an array we are all fond with. The below snippet will add an
awesome class with every element that has a
Array.reduce() functions are pretty ordinary but once you combine them and execute them consecutively, you can do some very neat and interesting things. A good example is that you can hack the
reduce function a bit and leverage it to efficiently unit test your sort algorithm.
As you can see, we don’t have to go through the trouble of storing a temporary variable and swapping it around.
The original use of the
reduce function is to “accumulate” which means it can take the sum of the current and previous value. But with some creativity we used it to do something completely different and the result is satisfying. I’m pretty sure there are a lot more things you can come up with and probable use cases for them.
Probably the most underused
Array functions I’ve seen Developers not taking advantage of them. Yes, you can achieve all of this using the traditional
filter function, but it’s much cleaner to use these newer methods to do some common branching in your code. They are pretty much self explainatory of what they do, if you would like to know more and what they return, it is linked to the docs for your convenience.
Ever wanted to cleanly define functions, but parameters only accept an array and it’s confusing to guess what they are without using object to name them something.
There are many more neat stuff you can do with object and array destructuring, more information can be found here.
5. Use Lodash or Underscore.js for more complex operations
Anything beyond the native array prototype I tend to use
Underscore.js, if you haven’t yet to use them already I strongly recommend you to take a look at their comprehensive list of functions and what they can bring to your project. My favorite one is
.zipObject, which can zip two arrays and turn them into key-value pairs, similar to how python does it.
That’s it for now, it’s been some time since I have posted an article. Nevertheless, I really hope that you guys enjoyed reading this and maybe found some of the features to be useful. Until next time, and Happy Easter!