A brief introduction to functional programming concepts in JavaScript

bryaneduardoga

Bryan Acosta

Posted on March 12, 2021

A brief introduction to functional programming concepts in JavaScript

Functional programming is a highly valued programming paradigm, so is a way of thinking about software construction by creating pure functions. It avoids concepts of shared state, mutable data observed in Object-Oriented Programming.

But what are all these buzzwords I'm talking about?

Well. As everyone knows, functions are pieces of code that can be reused once, and once again, they can receive some inputs, compute that input, and finally return an output, piece of cake, huh?

Functional code is characterized by:

  • The absence of side effects.
  • Pure functions.
  • Stateless.
  • First-class functions.

Let's find an easy way to define all these concepts.

What is a side-effect?

Side-effects are the process of modifying any variable or object property (e.g., a global variable, or a variable in the parent function scope chain).

Another side-effect would be print something into the console.
No having side effects means that the function doesn't change the outer world.

What is a pure function?

A pure function is a function which:

  • Take its input and use that and only that to compute an output and then return it.
  • They can't use variables either functions out of their scope.
  • Produces no side effects.

Not pure function
Alt Text
Pure function
Alt Text

What does stateless mean?

That means values don't mutate.

First-class functions.

When functions are treated like any other variable.

For instance:

  • Functions can be stored in variables.
  • Passed around as arguments, or even returned from other functions.

How to do functional programming?

  • Don't iterate, map, filter, and reduce instead.
  • Use higher-order functions.

Higher-order function
A higher-order function meets at least one of the following conditions:

  1. Takes functions as input.
  2. Return another function as output.

Alt Text

The Holy Trinity of Functional Programming

map() instead of for

Alt Text

map() does not mutate the array, it makes a copy.
Alt Text

filter()
Alt Text

reduce() takes an array and return just one reduced element
Alt Text

Advantages of functional programming.

  • They don't raise any side-effects.
  • Easy to refactor.
  • Better encapsulation.
  • Increase reusability.
  • Modularity.
  • Easy to test.

Well, that's all about this brief introduction to functional programming concepts. Thank's for reading.

More information about map, filter, and reduce:
map filter reduce

💖 💪 🙅 🚩
bryaneduardoga
Bryan Acosta

Posted on March 12, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related