Today… a small article about the approach to writing code. Do you write your JS code declaratively, or rather imperatively? It’s good to take a look closer. Similarly to approaches of writing and organizing CSS styles.
Declarative JavaScript vs imperative in JavaScript/ES6
Declarative programming is a programming paradigm — an approach to building the structure and elements of computer programs, which expresses the logic of calculations without describing its control flow. In contrast to programs written imperatively, the programmer describes the conditions, that the final solution must meet (what we want to achieve), and not the detailed sequence of steps that lead to it (how to do it).
Many languages, that use a declarative approach, tries to minimize or eliminate side effects, describing what the program must do in their field of domains, instead of describing how to achieve this as a sequence of programming language primitives. In turn, in imperative approach we implement algorithms in clear steps.
Boredom. Let’s just look at it.
Imperative code defines what and how has to be done, eg:
– go to the kitchen
– cut the bread
– take the butter out of the fridge
– …
– …
– put a sandwich on the table
In case of declarative we just describe what we need:
– I want a sandwich
Where’s the catch?
Simply, by building our program declaratively, we describe what we need. We compose the program from individual elements. These elements can exist in a framework or library; open-source or in our own libraries. If they are not available, we write them. Imperatively? Yes, in the end, we will come to such a level of abstraction.
Simply, when there is no lower level of abstraction, we need to write a code (functions, libraries, components, etc.) that implements what we need. At a higher level of abstraction, we will use this by building a program declaratively and modifying it more easily.
Boring again, so let’s take a look at JS code samples.