Differentiating between declarative and imperative programming
When reading the React documentation or blog posts about React, we will have undoubtedly come across the term declarative. One of the reasons why React is so powerful is that it enforces a declarative programming paradigm.
Therefore, to master React, it is essential to understand what declarative programming means and what the main differences between imperative and declarative programming are. The easiest way to approach this is to think about imperative programming as a way of describing how things work, and declarative programming as a way of describing what we want to achieve.
Entering a bar for a beer is a real-life example in the imperative world, where normally we will give the following instructions to the bartender:
In the declarative world, we would just say, “Can I have a beer, please?” The declarative approach assumes that the bartender already knows how to serve a beer, an important aspect of the way declarative programming works. Let’s move into a JavaScript example. Here we will write a simple function that, given an array of lowercase strings, returns an array with the same strings in uppercase:
toUpperCase(['foo', 'bar']) // ['FOO', 'BAR']
An imperative function to solve the problem would be implemented as follows:
领英推荐
const toUpperCase = input => {
const output = []
for (let i = 0; i < input.length; i++) {
output.push(input[i].toUpperCase())
}
return output
}
First, an empty array to contain the result is created. Then, the function loops through all the elements of the input array and pushes the uppercase values into the empty array. Finally, the output array is returned.
A declarative solution would be as follows:
const toUpperCase = input => input.map(value => value.toUpperCase())
The items of the input array are passed to a map function that returns a new array containing the uppercase values. There are some significant differences to note: the former example is less elegant, and it requires more effort to be understood. The latter is terser and easier to read, which makes a huge difference in big code bases, where maintainability is crucial.
Another aspect worth mentioning is that in the declarative example, there is no need to use variables or to keep their values updated during the execution. Declarative programming tends to avoid creating and mutating a state.
Reference: Carlos Santana Roldán. (2023). React 18 Design Patterns and Best Practices. Packt Publishing. ISBN: 978-1-80323-310-9