You may have come across the terms declarative and imperative programming, but aren’t sure what they mean. If you’ve been writing a code for a reasonable amount of time, you most likely know these concepts, you just don’t know what they’re called.
Declarative programming
With declarative programming you are telling the program what you want to happen, but not how to make it happen. For example:
let res = data.filter((d) => d % 2 !== 0);
This code is saying "Give me everything where it is odd", rather than "Step through this collection. Check this item and if it is odd add it to the res
array".
As a side note, functional programming is a declarative paradigm.
Imperative programming
With imperative programming you are telling the program how you want something to happen. For exampe:
let res = [];
data.forEach((d) => {
if (d % 2 !== 0) {
res.push(d);
}
});
This code is saying:
- Create a results array
- Step through each item in the data array
- Check the number and if it is odd, add it to the
res
array
As a side note, imperative programming can also be known as procedual or object oriented programming.
Conclusion
Hopefully this helps to clear up any confusion you may have about the meaning of these terms.