A guide to functional programming in JavaScript

JavaScript higher-order functions

What is Functional Programming?

Functional programming is a programming model designed to handle pure mathematical functions. This model is totally focused on writing manageable and reusable code.

Functional programming and JavaScript

JavaScript is a high-level multi-paradigm language, which means that we can easily use different programming paradigms like object-oriented, functional and procedural in a single JavaScript code. This makes JavaScript so beautiful and powerful.

Functional programming has few important concepts that we need to know and understand. By using these concepts in your application makes your code shorter, manageable, easy to test and bug-free.

In this blog we are looking at the most common functional programming techniques that is Higher-Order Functions. Lets get into it.

Higher-Order Functions

A higher-order function is a function that takes another function as a parameter(often called a 'callback function') or returns a function as a return value.

JavaScript provides some built-in methods that takes a callback function. By using these methods we can wrote short code in general.

The most commonly used functional-programming methods are following,

  • forEach
  • map
  • filter

forEach:

We use forEach only with arrays. It takes a callback function with elements, index parameter and array itself. The index and the array optional.

arr.forEach(function(element, index, arr){
   console.log(index,element,arr)
})

We can also write it using arrow function.

Example: Calculating Sum of array using forEach method.

let sum = 0;
const arr = [ 1, 2, 3, 4, 5];
arr.forEach( element => sum+=element)
console.log(sum) //  15

map:

It takes a callback function with elements, index, array parameter and returns a new array. It iterates over an array and used for modifying the array elements

Example : let say we have an array containing names of countries and we want a new array containing names of countries in uppercase.

const countries = ['pakistan','Japan','Germany','Ireland'];
// using map method(arrow function shorthand)
const countriesNamestoUpperCase = countries.map(country => country.toUpperCase())
console.log(countriesNamestoUpperCase) // ['PAKISTAN',JAPAN','GERMANY','IRELAND']

Well, this is easy isn't it? that's the thing a like most about these methods that it saves a lot of time and we have to write less code and less code mean less bugs :)

filter:

It takes a callback function with elements, index, array parameter and returns a new array. It iterates over an array and filter out items which full fill filtering conditions and return a new array.

Example: Let's take a real world example this time lets say you are developing an app which shows all the restaurants in the searched city and you want to add a filter by rating functionality and only those restaurant will be rendered with the matching rating. What would you do? use some if else or switch conditions in for loops? this can help you solve your problem but filter method got u covered with manageable and less code. lets see how

const restaurants = [
{
  name: 'restaurant1',
  rating: 3
},
{
  name: 'restaurant2',
  rating: 3.5
},
{
  name: 'restaurant3',
  rating: 4
},
{
  name: 'restaurant4',
  rating: 4.5
},
]

// consider user only wants the restaurant with rating greater than 4
let ratingChosenByUser = 4;

const restaurantsWithRatingGreaterThanOrEqualToFour = restaurants.filter(
 restaurant => restaurant.rating >= ratingChosenByUser
) 

// filtered Restaurants
{/*
 [
{
  name: 'restaurant3',
  rating: 4
},
{
  name: 'restaurant4',
  rating: 4.5
},
]
*/}

Look how easy and clean it is using filter method.

That's all, if you want to learn more about these methods and other Higher-order JavaScript Methods you can check out here Higher-Order Functions.