Become a Better Developer by Learning Functional Programming in JavaScript

\
Functional programming (abbreviated as FP) is a programming paradigm that’s popular in JavaScript. JavaScript treats functions as first-class citizens and this makes it easy to write functional programming in JavaScript.

\
This post will tell you the basics and benefits of functional programming and how to use them in JavaScript.

\

What is Functional Programming?

Functional programming is a way of writing software with specific principles. The idea is that these principles will

  • Make it easier to write, test, and debug the code
  • Make it easier to reason about the code
  • Improve developer productivity
  • And more

\

Core Principles of Functional Programming

Pure Functions

Functions should be pure. Pure functions always produce the same output and have no side effects affecting the output. Side effects are anything that’s outside the control of the function. e.g., any input/output (I/O) such as reading from a database/file or using console.log. Or even a static variable.

\
Here’s a simple example.

\

// This function is pure because it's determinisic.
// It has no side effects.
// Nothing outside the function can influence the output.
// addTen(5) will _always_ be 15
const addTen = input => {
  return input + 10;
};

// Fetch the number from the database
const numberFromDb = DB.getNumber();

// This function is not pure because it's not deterministic.
// It has a side effect (the numberFromDb value).
// We cannot know for sure that the outcome will be the same
// every time we call it, and that's why it's not pure
const addWithNumberFromDb = input => {
  return input + numberFromDb;
};

\

But I Need I/O?

An application without I/O is not that useful. Functional programming is not about eliminating I/O. Instead, you should separate the business logic from I/O. Any side effects should be handled at the edges of our processes, and not in the middle of them. By doing this you achieve pure business logic that is easily testable.

\
JavaScript is not a purely functional programming language. So there’s nothing from stopping you doing whatever you feel comfortable with though. Haskell, on the other hand, is an example of a purely functional programming language. In Haskell, you’re forced to use functional programming principles.

\

Immutable State

An immutable state means that the state should not change. Instead of changing the state, in functional programming we copy it. This might seem counter-intuitive: why would we want to copy the state instead of changing it?

\
In JavaScript, you can pass on values by reference. This can be dangerous. Let’s look at an example.

\

// Create a person with a name
let simon = {"name": "simon"};

// Instead of copying simon, we assign it by reference.
// This is dangerous and can have unwanted behavior later.
let lisa = simon;

// Set the correct name of lisa
lisa.name = "lisa";

// But now we also updated simon's name!
console.log(simon); // { name: 'lisa' }

// If we would have copied simon, this would not have happened
// Let's see how we would do it in functional programming
let beth = {"name": "beth"};

// Copy beth instead of using a reference to it
let andy = {...beth};

// Set the correct name of andy
andy.name = "andy";

// Now both variables have the correct name
console.log(andy); // { name: 'andy' }
console.log(beth); // { name: 'beth' }

\

Recursion

With recursion, lists are not iterated using forwhile, or do...while because they mutate state (increasing the counter, for example). Instead, functional programming functions such as map()filter(), and reduce() are used.

\
The word “recursion” scared me for a long time, I have to admit. But in JavaScript, you can quickly see the benefits of readability and productivity using these functions.

\
Let’s look at an example!

\

// A list of fruit, and their price
const fruit = [
  {name: 'banana', price: 5},
  {name: 'apple', price: 3},
  {name: 'pear', price: 7}
];

// Now we want to increase the price of all fruit
// Let's do this using a for loop
// NOTE: We're also mutating state here,
// which as you know can be dangerous
for (f of fruit) {
  f.price = f.price + 5;
}

// Instead, let's use map()
const moreExpensiveFruit = fruit
  .map(f => {
    return { ...f, price: f.price + 5 }
  });

// Now we're using functional programming!
// 1. We're not mutating fruit, instead we're copying data with the spread operatator `...`
// 2. map() returns a new list, so the fruit list is still unchanged

\

Functional Programming in JavaScript

I showed you briefly how to use map() already. Let me dig into it some more.

\
map() iterates over your list, one element at a time, and lets you replace it with something new. This is useful for updating the value for all elements in a list, for example. It then returns to a new list, leaving the old one unmodified. So it follows the functional programming principle of not modifying the state.

\
And there are two more functions you should know about, filter() and reduce().

filter() will let you filter out unwanted elements from the list. This is useful for removing elements that meet certain criteria from a list. e.g., “filter out fruit that’s more expensive than 5. And just like map(), it returns a new list.

\

// A list of fruit, and their price
const fruit = [
  {name: 'banana', price: 5},
  {name: 'apple', price: 3},
  {name: 'pear', price: 7}
];

// We use filter() to say
// "only include fruit that has a price of 5 or less"
const cheapFruit = fruit
  .filter(f => f.price <= 5);

// Log the result to see that "pear" was filtered out
console.log(cheapFruit); // [ {name: 'banana', price: 5}, {name: 'apple', price: 3} ]

\
reduce() will let you “reduce” a list of elements into a single value. This is useful for working with numbers.

\

// A list of fruit, and their price
const fruit = [
  {name: 'banana', price: 5},
  {name: 'apple', price: 3},
  {name: 'pear', price: 7}
];

// We use reduce() to get the "total price of all fruit"
const sumPriceFruit = fruit
  .reduce((previous, current) => previous + current.price, 0);

// Log to see the result
console.log(sumPriceFruit); // 15

\
This function was the hardest one to understand for me. I recommend you check out the MDN Web Docs about it.

\

Conclusion

Now you know what functional programming is about, why it’s useful, and how to use it in JavaScript. It might take some time to get used to but it’s well worth the effort. The functions we cover are available in all major programming languages. This is not something specific to JavaScript.


Connect with me on TwitterLinkedIn, or GitHub

\
Originally published at prplcode.dev

Leave a Reply

Your email address will not be published. Required fields are marked *

Instagram

Why do People Say: "Developers are Lazy"?
The saying “work smart, not hard” is applicable for programmers.
.
https://hackernoon.com/why-do-people-say-developers-are-lazy

.
Author: Aga Wozniak
.
.
.
.
.
#blog #100Daysofcode #javascript #vuejs #datascientist #peoplewhocode #learntocode #coding #developerlife #frontenddeveloper #backenddeveloper #fullstackdeveloper #developer #webdeveloper #thedevlife #phpdeveloper #computerscience #programmer #programmingisfun #codingdays
...

Mitigating the DDOS Threats Facing Banks and Fintechs
As much as digitization and cyber simplified banking, the Fintech sector has left digital payment activity exposed to malicious and suspicious activity.
.
https://hackernoon.com/mitigating-the-ddos-threats-facing-banks-and-fintechs

.
Author: Josh Horowitz
.
.
.
.
.
#blog #100Daysofcode #javascript #vuejs #datascientist #peoplewhocode #learntocode #coding #developerlife #frontenddeveloper #backenddeveloper #fullstackdeveloper #developer #webdeveloper #thedevlife #phpdeveloper #computerscience #programmer #programmingisfun #codingdays
...

24 Best JavaScript Blogs and Websites
In this overview, we have compiled a list of popular sites, as well as JS blogs that are worth reading and keeping in your bookmarks.
.
https://hackernoon.com/24-best-javascript-blogs-and-websites

.
Author: natashatsybliyenko
.
.
.
.
.
#blog #100Daysofcode #javascript #vuejs #datascientist #peoplewhocode #learntocode #coding #developerlife #frontenddeveloper #backenddeveloper #fullstackdeveloper #developer #webdeveloper #thedevlife #phpdeveloper #computerscience #programmer #programmingisfun #codingdays
...

The Projects Working to Lower Ethereum Gas Fees
As more investors try their hand at DeFi, gas fees are shooting over the roof, making engaging with decentralized apps uneconomical for most users.
.
https://hackernoon.com/ethereum-gas-fees-are-there-any-projects-working-to-optimize-eth-gas-fees

.
Author: CryptoVirally SLR
.
.
.
.
.
#blog #100Daysofcode #javascript #vuejs #datascientist #peoplewhocode #learntocode #coding #developerlife #frontenddeveloper #backenddeveloper #fullstackdeveloper #developer #webdeveloper #thedevlife #phpdeveloper #computerscience #programmer #programmingisfun #codingdays
...

On the Edge of a New Year: IT Predictions for 2022
The single biggest cause of network errors are people.
.
https://hackernoon.com/an-interview-with-uplogix-ceo-lisa-frankovitch

.
Author: Mignonette Garnier
.
.
.
.
.
#blog #100Daysofcode #javascript #vuejs #datascientist #peoplewhocode #learntocode #coding #developerlife #frontenddeveloper #backenddeveloper #fullstackdeveloper #developer #webdeveloper #thedevlife #phpdeveloper #computerscience #programmer #programmingisfun #codingdays
...

How to Modernize IBM i Applications
If you’re like most IBM i users, you know how much value your IBM i data and applications bring to your business. Your end-users, however, may not. In today’s world of rich user experience, fast-paced application development, and constantly evolving customer expectations, IBM i applications are unde…
.
https://hackernoon.com/how-to-modernize-ibm-i-applications

.
Author: Lansa
.
.
.
.
.
#blog #100Daysofcode #javascript #vuejs #datascientist #peoplewhocode #learntocode #coding #developerlife #frontenddeveloper #backenddeveloper #fullstackdeveloper #developer #webdeveloper #thedevlife #phpdeveloper #computerscience #programmer #programmingisfun #codingdays
...