Functional Programming

4. Comparison to imperative programming

Side-by-side comparison of Imperative vs. Functional programming

The following two examples (written in JavaScript) achieve the same effect - they multiply all even numbers in an array by 10 and add them all, storing the final sum in the variable "result".

Traditional Imperative Loop:

const numList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

let result = 0;

for (let i = 0; i < numList.length; i++) {

  if (numList[i] % 2 === 0) {

    result += (numList[i] * 10)

  }

}


Functional Programming with higher-order functions:

const result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

               .filter(n => n % 2 === 0)

               .map(a => a * 10)

               .reduce((a, b) => a + b)