Cómo y por qué usar la programación funcional en JavaScript moderno

En este artículo, obtendrá una comprensión profunda de la programación funcional y sus beneficios.

Introducción a la programación funcional

La programación funcional (FP) es un tipo de paradigma o patrón en la informática. Todo se hace con la ayuda de funciones en FP y los bloques de construcción básicos son solo funciones.

Los lenguajes de programación que admiten programación puramente funcional son:

  1. Haskell
  2. Cierre
  3. Scala
  4. SQL

Algunos de los lenguajes de programación que admiten la programación funcional, así como otros paradigmas de programación son:

  1. Pitón
  2. Javascript
  3. C ++
  4. Rubí

Dado que el nombre dice funcional, la mayoría de los programadores piensan en funciones matemáticas. Ese no es el caso de FP. Es solo una abstracción para resolver problemas complejos del mundo real de una manera fácil y efectiva.

Antes de la era de la programación orientada a objetos, la industria del software dependía completamente de la programación funcional. Este paradigma sacudió la industria del software durante un par de décadas. Hay algunos problemas con la programación funcional y es por eso que cambiaron al paradigma Orientado a Objetos. Los problemas con FP se discutirán más adelante en este artículo.

Se trata de la introducción a la programación funcional. Ahora, antes que nada, necesitamos aprender qué es una función.

Funciones

Antes de revelar la definición real, quiero explicar una situación para saber dónde usar realmente FP. Suponga que está escribiendo código para construir una aplicación. En su viaje de desarrollo, desea reutilizar el código de unas pocas líneas (100) en diferentes lugares. Para su aplicación, las funciones son útiles. Podemos escribir funciones en un solo lugar y podremos acceder a esas funciones desde cualquier lugar del programa. La programación funcional tiene las siguientes características:

  1. Reduce la redundancia de código.
  2. Mejora la modularidad.
  3. Nos ayuda a resolver problemas complejos.
  4. Aumenta la mantenibilidad.

Veamos la definición real de una función:

Una función es un bloque de código específico que se utiliza para realizar una tarea específica en el programa.

Los tipos de funciones más populares son:

  1. Funciones generales
  2. Funciones de flecha
  3. Funciones anónimas

Funciones generales

Las funciones generales no son más que las funciones que el programador utiliza con bastante frecuencia para realizar una tarea específica. La sintaxis para declarar una función general en Javascript es:

function functionName(parameters) { // code to be executed}

función: es una palabra clave que es necesaria para declarar una función.

functionName: se puede nombrar en función del trabajo de la función.

parámetros: podemos pasar cualquier número de parámetros a una función.

Las funciones declaradas no se ejecutan inmediatamente. Se “guardan para su uso posterior” y se ejecutarán más tarde, cuando se invoquen (invoquen).

Necesitamos llamar a la función cuando queremos ejecutar ese fragmento de código que se devuelve dentro de una función.

Las funciones generales se clasifican de la siguiente manera:

Funciones sin argumentos

No necesitamos pasar ningún argumento a la función.

// Function Declaration
function sayHello(){ alert('Hello...!');}
// Calling the functionsayHello()

Cuando llamamos a la función para decir Hola (), producirá el mensaje de alerta como Hola.

Funciones de argumento

En este tipo de funciones, les pasaremos argumentos.

Ejemplo

// Declaring a Function
function add(num1, num2){ return num1 + num2;}
// Function Call
var result = add(7, 11);
console.log(result);

Los argumentos que se pasan al declarar una función, es decir (num1, num2) se llaman parámetros formales.

Los argumentos que se pasan al llamar a una función, es decir (7, 11) se llaman como parámetros reales.

Una función generalmente devuelve algún valor, y para devolver ese valor necesitamos usar la palabra clave return . Cuando una función devuelve algún valor, significa que no imprime ningún resultado, solo devuelve el resultado final. Es nuestra responsabilidad imprimir ese resultado. En el programa anterior, la función devuelve el valor y yo paso ese valor a un nombre de variable 'resultado'. Ahora la función pasará el resultado a la variable 'resultado'.

La especialidad de las funciones de Javascript

Si pasa más argumentos que el número declarado, no obtendrá ningún error. Pero en otros lenguajes de programación como Python, C, C ++, Java, etc… obtendremos un error. Javascript lo considerará en función de sus requisitos.

Ejemplo

// Calling the function with more number of arguments than the declared number
var result1 = add(2, 4, 6);console.log(result1);
var result2 = add(2);console.log(result2);

Salida

Si pasa menos argumentos que el número declarado, tampoco obtendremos ningún error. Pero no podemos predecir la salida del programa porque, según la funcionalidad de su función, se producirá la salida.

Función de argumento variable

La mayor ventaja de las funciones de Javascript es que podemos pasar cualquier número de argumentos a la función. Esta función ayuda a los desarrolladores a trabajar de forma más eficaz y coherente.

Ejemplo

// Creating a function to calculate sum of all argument numbers
function sumAll(){
let sum = 0;
for(let i=0;i
return sum;
}
// Calling the sumAll function
sumAll();
sumAll(1,2,3,12,134,3234,4233,12,3243);

Output

Original text


This is all about general functions that are used to perform our complex task in a simple manner. Now let’s discuss some advanced functions introduced in ES6 called Arrow Functions.

Arrow Functions

An arrow function expression is a syntactically compact alternative to a regular function expression. It doesn’t have its own bindings to the this, super, arguments or new.target keywords. Arrow function expressions are ill-suited as methods. They cannot be used as constructors.

One of the most loved features in Es6 are Arrow functions. This arrow function helps developers time and simplify function scope.

The syntax for the arrow function is:

const functionName = (parameters) => { // code to be executed}
 (OR)
var functionName = (parameters) => { // code to be executed}
 (OR)
let functionName = (parameters) => { // code to be executed}

Examples for Arrow Functions

Eg 1

Creating an Arrow function to say a welcome message to the users.

// Creating a Welcome function
let sayHello = () => { return 'Welcome to Javascript World...!';}
// Calling the function
console.log(sayHello())

Output

Eg 2

In this example, we are creating an Arrow function to generate the greatest of all numbers that are passed as an argument.

let maxNumber = (a,b,c,d) => {
 if(a > b && a > c && a > d) return a; else if(b > a && b > c && b>d) return b; else if(c > a && c > b && c > d) return c; else return d;}
// Calling the function
console.log(maxNumber(1,2,4,3));

Output:

Combination of Variable Arguments with Arrow Functions

Since we are working with an arrow function, it doesn’t support the arguments array by default like general function. It is our responsibility to declare explicitly that it supports the variable number of arguments

Eg 3

let varArgSum = (...args) => { let sum = 0;
 for(let i=0;i
return sum;
}
// Calling the Function
console.log(varArgSum());
console.log(varArgSum(1,2,3,4,5,6,7,8,9,10));

Output

This is how we can combine a variable number of arguments with arrow functions. Now let’s discuss Anonymous functions in JavaScript.

Anonymous Functions

An anonymous function is simply a function with no name. The purpose of using anonymous function is to perform a certain task and that task is no longer required to program. Generally, anonymous functions are declared dynamically at run time.

Anonymous functions are called only once in a program.

Example:

// Working with an Anonymous function
var a = 10; // Global Scope Variable.
// creating a function(function() {
 console.log("welcome to the world of Anonymous function");
 var b = 20; // b is a local scope variable.
 var c = a+b; // c is a local scope variable //a can be used because it is in the global scope
 console.log("Addition of two numbers value is: "+c);})();

Output

This is the concept of anonymous functions. I think I explained it in a simple and easy way.

Higher Order Functions

A higher-order function is a function that takes functions as an argument or that returns another function as a result.

The best example of higher-order functions in Javascript is that of Array.map(), Array.reduce(), Array.filter().

Example 1: Array.map()

// working with Array.map()
let myNumberArray = [4,9,16,25,36,49];
let mySquareRootArray = myNumberArray.map(Math.sqrt);
console.log(mySquareRootArray);

Output

Example 2: Array.reduce()

// working with Array.reduce()
let someRandomNumbers = [24,1,23,78,93,47,86];
function getSum(total, num){ return total + num;}
let newReducedResult = someRandomNumbers.reduce(getSum);
console.log(newReducedResult);

Output

Example 3: Array.filter()

// Working with array filter
let ages = [12,24,43,57,18,90,43,36,92,11,3,4,8,9,9,15,16,14];
function rightToVote(age){ return age >= 18;}
let votersArray = ages.filter(rightToVote);
console.log(votersArray);

Output

Recursion

This is one of the key topics in functional programming. The process in which a function calls directly or indirectly is called a recursive function. This concept of recursion is quite useful in solving algorithmic problems like the Towers of Hanoi, Pre-Order, Post-Order, In-Order, and some graph traversal problems.

Example

Let’s discuss a famous example: finding the factorial of a number using recursion. This can be done by calling the function directly from the program repeatedly. The logic for the program is

factorial(n) = factorial(n) * factorial(n - 1) * factorial(n - 2) * factorial(n - 3) * ….. * factorial(n - n);
// Finding the factorial of a number using Recursion
function factorial(num){ if(num == 0) return 1; else return num * factorial(num - 1);
}
// calling the function
console.log(factorial(3));
console.log(factorial(7));
console.log(factorial(0));

Output

Characteristics Of Functional Programming

The objective of any FP language is to mimic the use of mathematical concepts. However, the basic process of computation is different in functional programming. The major characteristics of functional programming are:

Data is immutable: The data which is present inside the functions are immutable. In Functional programming, we can easily create a new Data structure but we can’t modify the existing one.

Maintainability: Functional programming produces great maintainability for developers and programmers. We don’t need to worry about changes that are accidentally done outside the given function.

Modularity: This is one of the most important characteristics of functional programming. This helps us to break down a large project into simpler modules. These modules can be tested separately which helps you to reduce the time spent on unit testing and debugging.

Advantages Of Functional Programming

  1. It helps us to solve problems effectively in a simpler way.
  2. It improves modularity.
  3. It allows us to implement lambda calculus in our program to solve complex problems.
  4. Some programming languages support nested functions which improve maintainability of the code.
  5. It reduces complex problems into simple pieces.
  6. It improves the productivity of the developer.
  7. It helps us to debug the code quickly.

Disadvantages Of Functional Programming

  1. For beginners, it is difficult to understand. So it is not a beginner friendly paradigm approach for new programmers.
  2. Maintainance is difficult during the coding phase when the project size is large.
  3. Reusability in Functional programming is a tricky task for developers.

Conclusion

For some, it might be a completely new programming paradigm. I hope you will give it a chance in your programming journey. I think you’ll find your programs easier to read and debug.

This Functional programming concept might be tricky and tough for you. Even if you are a beginner, it will eventually become easier. Then you can enjoy the features of functional programming.

If you liked this article please share with your friends.

Hello busy people, I hope you had fun reading this post, and I hope you learned a lot here! This was my attempt to share what I’m learning.

I hope you saw something useful for you here. And see you next time!

Have fun! Keep learning new things and coding to solve problems.

Check out My Twitter, Github, and Facebook.