Let's assume that we have an array of numbers — [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] — and we want to extract all the odd numbers in this array.
Let's look at a couple of ways through which we can achieve a solution to the above problem, using JavaScript!
const arrayOfNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const getOddNumbers = (arr) => {
const oddNumbers = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 !== 0) oddNumbers.push(arr[i]);
}
return oddNumbers;
};
console.log(getOddNumbers(arrayOfNumbers));
// [1, 3, 5, 7, 9]
const arrayOfNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const getOddNumbers = (arr) => arr.filter(x => x % 2 !== 0);
console.log(getOddNumbers(arrayOfNumbers));
// [1, 3, 5, 7, 9]
Notice the implementation of getOddNumbers in both pieces of code. The differences between the imperative way, and the declarative way could be summed, as follows:
| Imperative programming | Declarative programming |
| Deals with the "how" of a solution using procedural statements | Deals with the "what" of a solution using declarative statements |
| The control flow of the program is managed by the programmer | The control flow of the program is abstracted away from the programmer |
Usually deals with the manipulation of some "state" (look at oddNumbers) | "State", if any, is dealt with internally, and abstracted away from the programmer |
| Conforms to the operational model of the machine | Conforms to the mental model of the programmer |
There you go, those are the core differences between the imperative, and declarative paradigms of programming.
SELECT * FROM MEMBERS WHERE age >= 25
Notice, how the "how" is abstracted away from us; and we only declare the "what"!
Hope this helps! :)
Sai Kishore Komanduri
Engineering an eGovernance Product | Hashnode Alumnus | I love pixel art