Learn JavaScript – Online Resources

https://www.technotification.com/2018/07/10-resources-to-learn-javascript.html

 

Advertisements

Functional Programming Part – 1

Higher Order Functions

A higher-order function is a function that can take another function as an argument, or that returns a function as a result.

In this article I will cover the three most used higher order functions in JavaScript. These are .filter().map() and .reduce().

Filter

Imagine writing a piece of code that accepts a list of people where you want to filter out the people that are equal or above the age of 18.

Our list looks like the one below:

const people = [
 { name: ‘John Doe’, age: 16 },
 { name: ‘Thomas Calls’, age: 19 },
 { name: ‘Liam Smith’, age: 20 },
 { name: ‘Jessy Pinkman’, age: 18 },
];

Let’s look at an example of a first order function which select people that are above the age of 18. I’m using an arrow function that is part of the ECMAScript standard or ES6 for short. It’s just a shorter way of defining a function and allows you to skip typing function and return, as well as some parentheses, braces, and a semicolon.

const peopleAbove18 = (collection) => {
  const results = [];
 
  for (let i = 0; i < collection.length; i++) {
    const person = collection[i];
 
    if (person.age >= 18) {
      results.push(person);
    }
  }
  return results;
};

Now what if we want to select all the people who are between 18 and 20? We could create another function.

const peopleBetween18And20 = (collection) => {
  const results = [];
 
  for (let i = 0; i < collection.length; i++) {
    const person = collection[i];
 
    if (person.age >= 18 && person.age <= 20) {
      results.push(person);
    }
  }
  return results;
};

You may already recognize a lot of repeating code here. This could be abstracted into a more generalized solution. These two functions have something in common. They both iterate over a list and filter it on a given condition

We can improve our previous function by using a more declarative approach, .filter().

const peopleAbove18 = (collection) => {
  return collection
    .filter((person) => person.age >= 18);
}

That’s it! We can reduce a lot of extra code by using this higher order function.

https://github.com/sathyalog/functional-programming/blob/master/higherOrderFunctions.js

just clone repo and run ‘node higherOrderFunctions’