Declarative Programming
Declarative programming is a style where you say what you want rather than how to get it. Instead of writing out the steps, you state the result you want and let the language take care of the details.
Take counting the even numbers in an array. The imperative version spells out each step:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Imperative: how to count
let count = 0;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
count++;
}
}
console.log(count); // 5
The declarative version says what we want directly:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Declarative: what to count
const isEven = (n) => n % 2 === 0;
const count = numbers.filter(isEven).length;
console.log(count); // 5
Both produce the same result, but the declarative version reads like a description of the result: “filter to even numbers, then get the length.” You do not manage loop counters or array indices. The filter method takes care of those.
JavaScript arrays come with many methods that let us write in this style. Many of them, like map, filter, and reduce, take functions as arguments and return new values without modifying the original array. Others, like sort and reverse, do modify the original array (though ES2023 added versions that do not).
Learning Outcomes
- Distinguish between imperative and declarative programming styles
- Use array methods such as map, filter, reduce, find, some, and every to transform, search, and validate data declaratively
- Choose the appropriate array method for a given data-processing task
- Work with Map and Set as declarative alternatives to objects and arrays