In this post, I will explain why declarative code is better than imperative code.
Then I will list some techniques to convert imperative JavaScript to a declarative one in common situations, defining key terms along the way.
First, let’s define what declarative and imperative mean.
Declarative code is one that highlights the intent of what it’s doing.
It favors the “what” over the “how”.
In other words, the exact implementations actually doing the work (aka the “how”) are hidden in order to convey what that work actually is (aka the “what”).
At the opposite, imperative code is one that favors the “how” over the “what”.
Let’s see an example:
The snippet below perform two things: it computes the square of x
, then check if the result is even or not.
// imperative way
const x = 5;
const xSquared = x * x;
let isEven;
if (xSquared % 2 === 0) {
isEven = true;
} else {
isEven = false;
}
view raw
block1.js hosted with ❤ by GitHub
Here, we can see that we finally get isEven
after several steps that we must follow in order.
These steps describe “how” we arrive to know if the square of x
is even, but that’s not obvious.
If you take a non-programmer and show him this, he might have a hard time deciphering it.
Now let’s see another snippet where I introduce a magic isSquareEven
function that performs the two same things than the previous one.
#functional-programming #javascript #javascript-tips #programming #declarative-programming #function