Example: Imperative vs. Functional

Lately, I got a lot of questions about functional programming.

So here's a small example about the different approaches.

// list of my friends
const friends = [
  { name: "Erwin", drinks: ["beer", "coffee"] },
  { name: "Peter", drinks: ["beer"] },
  { name: "Heidi", drinks: ["water"] },
];

// what do we want to search?
const itemToSearch = "beer";

/***********************************
 * imperative approach
 */

// a place to store the results
let resultImperative = [];

// go over every friend
for (friend of friends) {
  // check if the person drinks this
  if (friend.drinks.includes(itemToSearch)) {
    // add it to the results
    resultImperative.push(friend.name);
  }
}
console.log(resultImperative); // [ 'Erwin', 'Peter' ]

/***********************************
 * functional approach
 */
const resultFunctional = friends
  // check if the person drinks this
  .filter((friend) => friend.drinks.includes(itemToSearch))
  // only give me the name
  .map((friend) => friend.name);
console.log(resultFunctional); // [ 'Erwin', 'Peter' ]

I like the second approach more:

  • less complexity,
  • increased readability
  • constant level of abstraction