These are programming paradigms:
Declarative: tells What to do
Imperative: tells How to do
Example: Find the summation of salary for the employees with dept 'justCode'
Imperative Style:
const employees = [
{id: 1, name: 'james', dept: 'admin', salary: 10000},
{id: 1, name: 'Tom', dept: 'finance', salary: 10000},
{id: 1, name: 'peter', dept: 'justCode', salary: 12500},
{id: 1, name: 'tunner', dept: 'justCode', salary: 14500},
];
const justCodeDept = [];
// filter employees based on dept name.
for (let i=0; i<employees.length; i++) {
if (employees[i].dept === 'justCode') {
justCodeDept.push(employees[i]);
}
}
// summation of justCodeDept employees.
let summation = 0;
for (j = 0; j<justCodeDept.length; j++) {
summation = summation + justCodeDept[j].salary;
}
console.log(summation);
Declarative Style:
const employees = [
{id: 1, name: 'james', dept: 'admin', salary: 10000},
{id: 1, name: 'Tom', dept: 'finance', salary: 10000},
{id: 1, name: 'peter', dept: 'justCode', salary: 12500},
{id: 1, name: 'tunner', dept: 'justCode', salary: 14500},
];
console.log(employees.filter(item => item.dept === 'justCode').reduce(((previousValue, currentValue) => previousValue += currentValue.salary), 0));
Top comments (6)
just to point out the filter function then reduce is inefficient - looping twice. checking for "justDepartment" in the reduce itself (returning previous value if not fulfilling) is therefore double efficient. :)
also, the variables in the reduce should be previous value and current Object. your names would apply to a simple array of numbers.
Thanks
The declarative example is also a good example of functional programming. (Which is a form of declarative programming)
Great ...
Thanks :)
Great example. This may look simple but it does the job of explaining the concept simply. ✌️
Thanks. :)