Imperative programming focuses on describing how a program operates. Take an example of the below function “ isPresent “.
Of course, it searches a number (search term) in the numbers array and replies with true or false.
If you observe carefully, it focuses on how the number is searched.
It iterates each number one by one in an array of numbers and checks if criteria are fulfilled (HOW part: for/if). Eventually, it tells you if the number is present/not in the array.
Let’s look at the declarative way of searching a number in an array.
In the above code, the method Any (present on array data type), is an extension method provided by LINQ.
It determines whether any element of a sequence contains a given number. It does not tell you how it is searched. That part is hidden behind API: Any.
The benefit of a declarative approach over the imperative approach is improved readability of code.
This function “ containsAllMen “ tells you how searching is implemented and control flow like if clause determine the condition.
Now see the declarative way, it is using lodash’s every to determine the condition.
This technique is language agnostic.
You search libraries that do such work for you instead of implementing it by yourself.