DEV Community

Kurapati Mahesh
Kurapati Mahesh

Posted on • Edited on

Javascript: Declarative vs Imperative programming style

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);
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

Top comments (6)

Collapse
 
ankletime profile image
ankletime

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

Collapse
 
cadams profile image
Chad Adams • Edited

The declarative example is also a good example of functional programming. (Which is a form of declarative programming)

Collapse
 
shubhankar_bag_coder profile image
shubhankar-bag-coder

Great ...

Collapse
 
urstrulyvishwak profile image
Kurapati Mahesh

Thanks :)

Collapse
 
otumianempire profile image
Michael Otu

Great example. This may look simple but it does the job of explaining the concept simply. ✌️

Collapse
 
urstrulyvishwak profile image
Kurapati Mahesh

Thanks. :)