DEV Community

João Moraes
João Moraes

Posted on

Basic example of.. FP

Here is a basic example of using functional programming inside javascript language, a multiparadigm language that provides support for functional programming. In the first image, there is an imperative approach to manipulating a list of names. And in the second image, a functional approach is being used to manipulate the same list of names.

Alt Text

In the image above, dealing with the imperative approach, an empty list is created to be filled with the names in lower case. Subsequently, a temporary variable called "i" is created to iterate through the list. Then, each item modified from the list received as a parameter is added to the new list. In this approach, it is possible to see that the machine is being told how it should perform its work, in detail.

Alt Text

In the image above, dealing with the declarative / functional approach, the original list calls the javascript map method, which invokes a function in each item covered in the list, in this case a callback function, which in turn is a function that makes lowercase string letters. The map method returns a new list, without modifying the original list and thus guaranteeing the absence of side effects and the presence of immutability.

The code snippets of both images aim to create a new list with the names in lowercase letters, however, it is easy to see that the code of the second image is smaller, cleaner and more intuitive. Consequently, it is easier to be tested and reused.

technology #development #softwaredeveloper #javascript #javascriptdeveloper

Top comments (1)

Collapse
 
arvindpdmn profile image
Arvind Padmanabhan

For newbies, here's a high-level overview of FP: devopedia.org/functional-programming