A few months ago, I start moving my Javascript code from an Oriented Object/unorganized code to
something much more close to Functional Programming. In this paradigm, I found interesting concepts
such as immutability and high order functions…
And later on, colleague submitted a pull request with a javascript loop (plain old “for”). I
suddenly remember how far was my last loop in Javascript…
Let’s start from the beginning, with the following data and a simple function:
The goal is to create a new squad of Heroes which are good and not from DC Comics. I also want to
stringify each one.
The plain old loop way
With a loop the code should be like this:
I see 3 problems here:
after my loop, my data are altered. After the loop, the heroes variable doesn’t represent heroes
anymore. It breaks the S from SOLID.
this code isn’t “thread-safe”. What happens if you want to use your heroes during the loop? With
this kind of code, it can be risky to parallelize tasks.
there are already 2 levels of indentation. Adding the third rule will probably add another level
of indentation.
We call this approach: imperative programming. We explicitly declare how to get what we
want, step by step.
Otherwise, we have the declarative programming. It consists of focusing on the what, without
specifying how to get it…
Array.map and Array.filter to the rescue!
In a few words:
Array.map:
browse an array and apply on each element;
Now the same code with these two high order functions:
If I don’t need squadAlpha variable, we can chain everything:
Now hero object isn’t changed and heroesExtended is a copy of hero which contain a new property.
Embrace the power of ES6 (or es2015)
First of all,
it is recommended
to drop the var keyword in favour of const.
Then, if you think that anonymous function reduces visibility and are redundant, I’ve got good news!
ES6 bring something call
Arrow functions,
a shortness way to write functions.
It’s nicer… but we can also go deeper with implicit return (drop the curly braces):
Now, this code is thread-safe, the initial data aren’t altered and overall: it’s much more
readable. ❤️️
Note: with an arrow function, you can also forget this ugly hack: var self = this. In fact, it
did not bind the this. When you write a function with the function keyword, this function
redefines 4 things (this, arguments, new.target and super). With the arrow function, it redefines
none of them.
Not enough?
Array.find
I also enjoy
Array.find.
You can use it like this:
Array.reduce
Another function is always present when we speak about Functional programming & high order function:
Array.reduce
It can also be useful for creating a custom object from an array of object:
Array.sort
Then sorting an array is also common in JS. In this case, we use
Array.sort.
Array and Immutability
It isn’t recommended to alter the original object. But if we need to update it (add a property for
instance), you should work with a copy of this object, to keep the original one immutable.
Object.assign
is fine for cloning, and it works like this:
So in our case, adding a new property will produce a code like this (we need to copy each object):
Set theory: union (∪), intersection (∩) and difference (∖)
If you want to deal with unique items, you should use the
Set object.
It takes an iterable object as a parameter (such as an array). Then to convert a Set to a classic
array, we use the
spread operator (...iterable).
Let’s take the previous example and see how do it in JavaScript!
If you cannot reminder what is the Set theory, here’s a schema:
Notes:
if the 2 arrays are built from different API, your object will probably not share the same
reference. I mean tolkienHeroes[y] === evilHeroes[y]. In this case, your Set should only contain
the object’s id (to ensure unicity).
the Set Object keep the objects references (no copy will be created on instantiation).
Bonus: console.table
When working with array, you can debug your array in something much more nicer than console.log:
console.table (you can click on the header to sort the data).
About the author
Hey, I'm Maxence Poutord, a passionate software engineer. In my
day-to-day job, I'm working as a senior front-end engineer at Orderfox.
When I'm not working, you can find me travelling the world or cooking.