DEV Community

Cover image for Functional Programming in Javascript
Ola-Balogun Taiwo
Ola-Balogun Taiwo

Posted on

Functional Programming in Javascript

Introduction

Functional Programming has gained popularity over the years and its widespread use in JavaScript is prominent. This article explores the key concepts of functional programming, including immutability, pure functions, and higher-order functions. We also discuss the advantages of using functional programming in JavaScript, such as improved performance and easier debugging.
To illustrate how functional programming can be implemented in JavaScript, we provide code examples using popular higher-order functions like map(), reduce(), and filter(). We will address popular misconceptions about functional programming.

Key Concepts of Functional Programming

Functional programming is a programming paradigm that emphasizes the use of functions to write programs. In functional programming, functions are treated as first-class citizens, meaning they can be assigned to variables, passed as arguments to other functions, and returned as results from functions. This allows for the creation of small, reusable pieces of code that can be combined to create larger programs.

Core concepts of Functional Programming_

The core concepts of functional programming include immutability, pure functions, and higher-order functions.

immutability

Immutability is a term that is regularly used in programming. It basically refers to the property of an object or data structure that cannot be modified once it is created. In functional programming, new objects are created instead of modifying the original object. let's take map for example, if you are are to map an array, a new array is returned instead of changing the original array

const array = [2,4,6,8];

const newArray = array.map(item => item ** 2);
console.log(array); // [ 2, 4, 6, 8 ]
console.log(newArray); // [ 4, 16, 36, 64 ]
Enter fullscreen mode Exit fullscreen mode

pure functions

A pure function is a function that satisfy the following conditions

  1. It always returns the same output for a given input.

  2. It does not modify any external state or mutable data.

Example of pure function

function add(x, y) {
    return x + y
}
Enter fullscreen mode Exit fullscreen mode

Example of an impure function

function add(x, y) {
    x = x + 1
    return x + y
}
Enter fullscreen mode Exit fullscreen mode

Implementing Functional Programming in JavaScript

Okay we have talked enough, let's get down to some functional programming methods in javascript

Map: The map method creates a new array by applying a function to each element of an existing array.

const numbers = [1, 2, 3, 4, 5];
const squares = numbers.map(x => x * x);
console.log(squares); // Output: [1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

Filter: The filter method creates a new array by selecting elements from an existing array that pass a given test.

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(x => x % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
Enter fullscreen mode Exit fullscreen mode

Reduce: The reduce method applies a function to each element of an array, accumulating a result along the way.

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, x) => acc + x, 0);
console.log(sum); // Output: 15
Enter fullscreen mode Exit fullscreen mode

forEach: The forEach method applies a function to each element of an array, but doesn't create a new array.

const numbers = [1, 2, 3, 4, 5];
numbers.forEach(x => console.log(x)); // Output: 1 2 3 4 5
Enter fullscreen mode Exit fullscreen mode

Sort: The sort method sorts the elements of an array.

const numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
numbers.sort();
console.log(numbers); // Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
Enter fullscreen mode Exit fullscreen mode

Concat: The concat method creates a new array by combining two or more arrays.

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combined = array1.concat(array2);
console.log(combined); // Output: [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

Resources for Further Learning

If you are interested in learning further into Functional programming, the following resources will be useful

  1. Books:
    "Functional Programming in JavaScript" by Luis Atencio: This book provides a comprehensive guide to functional programming concepts and techniques specifically tailored for JavaScript developers.
    "JavaScript Allongé" by Reginald Braithwaite: This book explores functional programming concepts in JavaScript, providing in-depth explanations and practical examples.

  2. Online Courses:
    "Functional Programming Principles in JavaScript (Coursera)": Offered by the University of California, this course teaches the fundamentals of functional programming using JavaScript. It covers topics like higher-order functions, recursion, and immutable data structures.
    "Introduction to JavaScript and Algorithms" by FreeCodeCamp.

Conclusion

Functional programming brings a powerful paradigm to JavaScript development, offering numerous benefits and opening up new possibilities for creating robust and maintainable code. By embracing immutability, pure functions, and higher-order functions, developers can achieve code that is easier to reason about, test, and debug.

One of the key advantages of functional programming in JavaScript is improved code organization. By breaking down complex problems into smaller, composable functions, developers can build a codebase that is easier to understand and maintain. Pure functions, which produce the same output for a given input and have no side effects, enhance predictability and reduce the chances of bugs creeping into the code.

Another significant benefit of functional programming is better performance. By avoiding mutations and embracing immutable data structures, JavaScript engines can optimize code execution more effectively. Additionally, functional programming allows for easier parallelization and distributed computing, which can lead to improved scalability and efficiency in applications.

I hope you try out functional programming in your next project.

Top comments (7)

Collapse
 
ant_f_dev profile image
Anthony Fung

Nice overview!

However, I wouldn't include sort and forEach in your list of functions.

sort sorts the elements in place, i.e. it modifies the original array. While it does return an array, it is a reference to the original one.

forEach has no return value and is generally used to mutate state. Where data in an array should be transformed, map is often a better choice in functional programming as the transformed data is returned (as pointed out in the article).

Collapse
 
tracygjg profile image
Tracy Gilmore

Anthony,

I agree with your comment. I would also add, using the concat method is also not quite in the FP style and

const combined = [...array1, ...array2];

would be more in keeping.

Tracy

Collapse
 
titre123 profile image
Ola-Balogun Taiwo

Hi Tracy, thanks for reading through the article, I was trying to define the functional programming methods, I needed to use the concat for easier understanding for a beginner.

Collapse
 
titre123 profile image
Ola-Balogun Taiwo

I agree with you that sort doesn't follow the functional programming rules but it is used extensively in functional programming.

Collapse
 
ant_f_dev profile image
Anthony Fung • Edited

I see your point, but the example above doesn't illustrate a functional style. As mentioned, functions take input values and return an output value. Ignoring that sort introduces side effects in JavaScript, calling the following does nothing with the return value.

numbers.sort();
Enter fullscreen mode Exit fullscreen mode

Instead, we could do

const numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
const sorted = numbers.sort();
console.log(sorted); // Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
Enter fullscreen mode Exit fullscreen mode

which would also be in line with the other examples provided.

Collapse
 
tracygjg profile image
Tracy Gilmore

Hi,
A tip: You might want to include the word "javascript" immediately inside the code blocks as this will provide syntax highlighting. See
Tracy

Collapse
 
titre123 profile image
Ola-Balogun Taiwo

Read through the article, thanks a lot. I will make my next article more colourful.