What you do in general while coding? Tell the machine how to do it or ask the machine to do it for ourselves.
So today we will be going through the concepts like imperative programming and declarative programming.These concepts are not languag specific.
So what is imperative programming? Imperative programming means you will tell the computer/machine/program etc how to do something and as a result what you want to happen will happen.
Taking a simple example, let’s say we wish to double the number in an array. We could do this in an imperative style like so:
In the above example, we are explicitly iterating through the array. Then we are taking a single element multiplying it by 2 and then pushing it into the result array, mutating the result array until we are done.
A more Declarative approach might use a map function and we will tell the function what we want. See the below example.
Before going to the example let’s see what is Declarative Programming?It simply means telling the machine what you would like to happen and let the computer/program/machine figure out how to do it.
As you can see this approach leads us to write lesser and clean code.
In above example map creates a new array from an existing array, where each element in the new array is created by passing the elements of the original array into the function passed to the map(item=>item*2, flat arrow function in this case)
What the map function does is abstract away the process of explicitly iterating over the array and let us focus on what we want to happen.
Declarative programming allows us to describe what we want and let the underlying program/machine/computer deal with it how should it happen.
This can lead us to some real improvements in how we write code, not only in terms of writing fewer lines of code or in case of performance but by writing code at a higher level of abstraction we can focus much more on what we want, which ultimately is all we should really care about as a problem solvers.
Declarative programming allows us to describe what we want and let the underlying program/machine/computer deal with it and how should it happen.
This can lead us to some real improvements in how we write code, not only in terms of writing fewer lines of code or in case of performance, but also in writing code at a higher level of abstraction, where we can focus much more on what we want, leading to a real-world problem-solving.
Thanks for the reading…have a good day
One thought on “A Brief Guide to Imperative & Declarative Programming”