Basics of Functional Programming in JavaScript

Basics of Functional Programming in JavaScript from Coding compiler – This tutorial explains the basics of functional programming with simple examples to create a concise and easily supported code. In recent years, an even greater distinction has been made between traditional and functional programming in JavaScript. Its essence is not in the superiority of one over the other but in personal preferences.

This article is designed for beginners who learn the basics of functional programming.

What is functional programming in theory?

  1. Clean code – the program is easy to read and maintain.
  2. Syntactic efficiency – the   problem that the code is trying to solve is expressed by a smaller number of lines without harm to the functionality.
  3. Big abstraction  – volumetric logic for a cycle for is replaced by a more compact, one might even say, symbolic. The code becomes like a mathematical equation.
  4. Less mistakes  – if you learn to think in functional programming categories, you can protect yourself from falling into the series of the most common mistakes and pitfalls.
  5. More work – fewer lines  – such code looks shorter than its counterpart from the traditional programming paradigm.

Of course, with functional programming, you will have to revise your vision of the code. This concept is actively used by developers in projects for which the efficiency and reliability of the code are in the first place.

What is functional programming in practice?

Take a look at the simple loop  for:

 let LIST = [1, 2, 3];

// Часть 1: Цикл for в роли итератора и инкрементора
for (let i= 0; i< LIST.length; i++) {

   // Часть 2: выражение оператора для каждой итерации
   LIST[i] = LIST[i] + 1;

console.log(LIST); // [2, 3, 4]

You take a list and run it through a double iteration (iteration) of the elements of the array. Then increment each value by one. Thus, the initial value  [1,2,3] turns into  [2,3,4].

Simply simple, even google will not have to.

This example perfectly illustrates the traditional use of the famous loop for as an iterator.

Pure Functions

Speaking of functional programming, it is impossible not to mention the pure functions.

What is a pure function?

The main purpose of the clean function is to remove side effects .

A side effect occurs in functions that return unexpected results, or have a different impact on the parameters of the function, changing the state of the system.

When the state of the system changes, there is a threat to the integrity of the program and the quality of the code decreases. One mistake leads to the appearance of another. And now you do not understand where these bugs come from. No one would like that.

But … pure function is not a property of any one language. It was invented to denote a function in which, with a given set of arguments, predictable results are always returned . For example, 1 + 2 will always return 3.

On the other hand, there is Math.random(). It can not pass for a pure function, since each time it returns a different numerical value.

The purity of a function is often determined by the return value.If the function returns an unexpected value even with the same arguments, then it is called an impure function (a function with side effects) .

 // Pure function - returns the same value for the same sets of arguments.
function sum(a, b) { return a + b; }

// Unclean function - returns random values ​​regardless of the arguments passed
function sum(a, b) { return Math.random() * (a + b); }

Can you write mostly pure functions? If so, then you are one step closer to mastering the basics of functional programming.

At first, the purity of the function seems to be somewhat obscure, especially without illustrative examples. However, a computer program is more than a simple set of operators. And what you write inside functions can affect the overall state of the program.

Always remember the main thing: no one can write 100% pure programs. But it is precisely the purity of the functions that makes it possible to avoid many common mistakes .

Then everything will become clearer. You will see how pure functions can be combined with other functional programming principles.

Cycle rewrite for for functional programming

To rewrite the loop for, the array method map(mapping) will be used .

let LIST = [1, 2, 3]; function(item) { return item + 1; } );

In EcmaScript 6 with the support of the functional programming paradigm, you can take the switch functions . The arrow function further reduces the functions in the code: (item) => { return item + 1; } ); 

And when deleting, the return function takes the following form: (item) => item + 1 );

It also works, but it looks shorter and “more functional” . In this case, the functionality does not mean that only JavaScript functions should be used. The essence is different: a concise code is more like a mathematical equation.

Arrow functions return the value inside {}, expressed by a single operator. Moreover, this function can be reduced even more if you delete (): item => item + 1 ); 

Remember the initial cycle for? This is it, only with a record in one expression.

Although maybe it is “almost that”?

Another important feature of functional programming: the arrow functions hide their range of values. That is, the initial values ​​of the array are not added to the function! In the end, it will remain so  [1,2,3].And the method  mapleads to the following:

let LIST = [1,2,3]; item => { item + 1 });
console.log(LIST); // still: [1,2,3], nothing is incremented!

Let’s take the function out of the method map and save it separately:

let LIST = [1,2,3];
let add = item => item + 1; add );
console.log(LIST); // опять: [1,2,3], nothing is incremented!

So the function looks a little cleaner. However, the value of the list is still not increased (not incremented).

This is a paradigm shift. You still have to figure out the reasons why the result remains the same.

The list increment is absent only because it map does not change the list itself. It returns a copy of the list using the callback of each of the elements. And to get the increment of the variable you need to assign

 let copy =; 

Now the incremented value is stored in a copy of the list. But … this is not the same array that you worked with before. Again – another plus functional programming.

Remember how in the beginning of the article it was about side effects ? The arrow function hides its own range of values, so it does not need to leak into the global scope or change the values ​​of the initial array. In terms of functional programming, this is good. And quite predictable.

Clean function in all its glory! And yes, it limits the developer’s capabilities a bit. But such code looks less bulky, and the developer gets a copy of the initial array.

Hidden areas of functional programming

Functional programming is not just a conversion of a loop for to more concise expressions. The scope here is much wider. Example: the code above, in which the function map and arrow hide elements in its scope.

An array contains a whole set of methods characteristic of functional programming.

One of them is called  reduce(abbreviation). When connected map with,  reduce you can change the elements of the array without making them in the global scope. All the logic of the program further (excellent practice in development).

let LIST = [1,2,3];
let add = item => { return item + 1 };
let sum = (A, I) => { return A + I };
let val =, 0);

console.log( val ); // 9

In addition, you can safely delete  return and {} without harm to the functionality:

let LIST = [1,2,3];
let add = item => item + 1;
let sum = (A, I) => A + I;
let val =, 0);

console.log( val ); // 9

Again, this structure is somewhat similar to a mathematical equation (function), that is, to functional programming. However, it should be clearly understood that functional programming is not a JavaScript function. And as the first grows, the second gradually fades away.

Gearboxes are functions that shorten the result according to a certain rule. The programmer himself sets this rule. For example, the rule can be expressed in the summation function sum: A + I, which is decoded as  Accumulator + Item. In fact, this is exactly what the cycle does for.

The battery is  always present in the operation reduce(reduction). It tracks the cumulative effect of the operation.

The second parameter is reduce equal to 0. Therefore, the battery is also equal 0.

Thus, the cycle itself starts from zero on the counter. After executing the code, the battery is assigned a return value (it is stored in a variable  val).

As the code iterates and the functions are added, a new value is added.

The result is 9.

Once the conditions are  1 added to [1,2,3], it turns out [2,3,4].

Then, when the gearbox is started, all the values ​​from are added  [2,3,4], and the result is returned.

The result:  2 + 3 + 4 = 9.

This example clearly shows a slight difference in the logic of functional programming and the use of a loop for.

Functional programming brings the beauty of the code and its perfect execution. Functions work as well as a mathematical equation.

Related JavaScript Tutorials

JavaScript Introduction Tutorials
Introduction to JavaScript
Javascript Code editors
Javascript Reference and Specifications
Javascript Developer Console
Javascript Basics
JavaScript Hello World.!
External JavaScript Files
JavaScript Code Structure
Use Strict in JavaScript

Leave a Comment