¿Qué es la programación funcional? Una guía de JavaScript para principiantes

JavaScript es un lenguaje de múltiples paradigmas y se puede escribir siguiendo diferentes paradigmas de programación. Un paradigma de programación es esencialmente un conjunto de reglas que se siguen al escribir código.

Estos paradigmas existen porque resuelven los problemas a los que se enfrentan los programadores y tienen sus propias reglas e instrucciones para ayudarlo a escribir mejor código.

Cada paradigma te ayuda a resolver un problema específico. Por eso es útil tener una descripción general de cada uno de ellos. Cubriremos la programación funcional aquí.

Al final de este artículo, hay algunos recursos que puede utilizar para ir más lejos si le gustó esta introducción.

También hay un glosario de GitHub que lo ayudará a decodificar parte de la jerga que usa la programación funcional.

Por último, encontrará un lugar para ensuciarse las manos codificando con ejemplos prácticos y un repositorio de GitHub lleno de recursos que puede usar para obtener más información. Así que vamos a sumergirnos.

Paradigmas de programación declarativos vs imperativos

Un ejemplo de estos paradigmas de los que hablé al principio es la programación orientada a objetos. Otro es la programación funcional.

Entonces, ¿qué es exactamente la programación funcional?

La programación funcional es un subparadigma del paradigma de programación declarativa , con sus propias reglas a seguir al escribir código.

¿Qué es el paradigma de programación declarativa?

Si está codificando en un lenguaje que sigue el paradigma declarativo, escribe código que especifica lo que quiere hacer, sin decir cómo.

Un ejemplo súper simple de esto es SQL o HTML:

SELECT * FROM customers

En los ejemplos de código anteriores, no está implementando SELECTo cómo representar un div. Simplemente le está diciendo a la computadora qué hacer, sin el cómo .

A partir de este paradigma, existen subparadigmas como la programación funcional. Más sobre eso a continuación.

¿Cuál es el paradigma de la programación imperativa?

Si está codificando en un lenguaje que sigue el paradigma imperativo / procedimental, escribe código que le dice cómo hacer algo.

Por ejemplo, si hace algo como a continuación:

for (let i = 0; i < arr.length; i++) { increment += arr[i]; }

Le está diciendo a la computadora exactamente lo que debe hacer. Itere a través de la matriz llamada arry luego incrementcada uno de los elementos de la matriz.

Programación declarativa vs imperativa

Puede escribir JavaScript en el paradigma declarativo o el paradigma imperativo. Esto es lo que la gente quiere decir cuando dice que es un lenguaje de múltiples paradigmas. Es solo que el código funcional sigue el paradigma declarativo .

Si te ayuda a recordar, un ejemplo de un comando declarativo sería pedirle a la computadora que te prepare una taza de té (no me importa cómo lo hagas, solo tráeme un poco de té).

Aunque es imperativo, tendrías que decir:

  • Ve a la cocina.
  • Si hay una tetera en la habitación y tiene suficiente agua para una taza de té, encienda la tetera.
  • Si hay una tetera en la habitación y no tiene suficiente agua para una taza de té, llénela con suficiente agua para una taza de té y luego encienda la tetera.
  • Y así

Entonces, ¿qué es la programación funcional?

Entonces, ¿qué significa esto para el código funcional?

Debido a que es un subparadigma del paradigma declarativo , esto afecta la forma en que escribe el código funcional. Generalmente conduce a menos código, porque JavaScript ya tiene muchas de las funciones integradas que normalmente necesita. Esta es una de las razones por las que a la gente le gusta el código funcional.

También te permite abstraer mucho (no tienes que entender en profundidad cómo se hace algo), simplemente llamas a una función que lo hace por ti.

¿Y cuáles son las reglas que conducen al código funcional?

La programación funcional se puede explicar simplemente siguiendo estas 2 leyes en su código:

  1. Diseña su software a partir de funciones puras y aisladas
  2. Evitas mutabilidad y efectos secundarios

Profundicemos en eso.

1. Diseñe su software a partir de funciones puras y aisladas

Empecemos desde el principio,

El código funcional hace un uso intensivo de algunas cosas:

Funciones puras

La misma entrada siempre da la misma salida ( idempotencia ) y no tiene efectos secundarios.

Una función idempotente es aquella que, cuando vuelve a aplicar los resultados a esa función nuevamente, no produce un resultado diferente.

/// Example of some Math.abs uses Math.abs('-1'); // 1 Math.abs(-1); // 1 Math.abs(null); // 0 Math.abs(Math.abs(Math.abs('-1'))); // Still returns 1 Math.abs(Math.abs(Math.abs(Math.abs('-1')))); // Still returns 1

Los efectos secundarios son cuando su código interactúa con (lee o escribe) un estado mutable externo.

El estado mutable externo es literalmente cualquier cosa fuera de la función que cambiaría los datos en su programa. ¿Establecer una función? ¿Establecer un booleano en un objeto? ¿Eliminar propiedades en un objeto? Todos los cambios de estado fuera de su función.

function setAvailability(){ available = true; }

Funciones aisladas

No hay dependencia del estado del programa, que incluye variables globales que están sujetas a cambios.

Discutiremos esto más a fondo, pero todo lo que necesite debe pasarse a la función como argumento. Esto hace que sus dependencias (cosas que la función necesita para hacer su trabajo) sean mucho más claras de ver y más detectables.

Ok, entonces, ¿por qué haces las cosas de esta manera?

Sé que esto parece un montón de restricciones que hacen que su código sea innecesariamente difícil. Pero no son restricciones, son pautas que intentan evitar que caiga en patrones que comúnmente conducen a errores.

Cuando no está cambiando la ejecución de su código, bifurcando su código con if's basado en Booleanel estado de', establecido por múltiples lugares en su código, hace que el código sea más predecible y es más fácil razonar sobre lo que está sucediendo.

Cuando sigue el paradigma funcional, encontrará que el orden de ejecución de su código no importa tanto.

Esto tiene bastantes ventajas - un solo ser, por ejemplo, que para replicar un error que no es necesario saber exactamente lo que cada uno Booleany Objectestado 's era antes de ejecutar sus funciones. Siempre que tenga una pila de llamadas (sabe qué función se está ejecutando / se ha ejecutado antes que usted), puede replicar los errores y resolverlos más fácilmente.

Reutilización mediante funciones de orden superior

Las funciones que se pueden asignar a una variable, pasar a otra función o devolver desde otra función como cualquier otro valor normal, se denominan funciones de primera clase .

In JavaScript, all functions are first class functions. Functions that have a first class status allow us to create higher order functions.

A higher order function is a function that either take a function as an argument, returns a function, or both! You can use higher order functions to stop repeating yourself in your code.

Something like this:

// Here's a non-functional example const ages = [12,32,32,53] for (var i=0; i < ages.length; i++) { finalAge += ages[i]; } // Here's a functional example const ages = [12,32,32,53] const totalAge = ages.reduce( function(firstAge, secondAge){ return firstAge + secondAge; }) 

The in-built JavaScript Array functions .map, .reduce, and .filter all accept a function. They are excellent examples of higher order functions, as they iterate over an array and call the function they received for each item in the array.

So you could do:

// Here's an example of each const array = [1, 2, 3]; const mappedArray = array.map(function(element){ return element + 1; }); // mappedArray is [2, 3, 4] const reduced = array.reduce(function(firstElement, secondElement){ return firstElement + secondElement; }); // reduced is 6 const filteredArray = array.filter(function(element){ return element !== 1; }); // filteredArray is [2, 3]

Passing the results of functions into other functions, or even passing the functions themselves, in is extremely common in functional code. I included this brief explanation because of how often it is used.

These functions are also often used because they don't change the underlying function (no state change) but operate on a copy of the array.

2. Avoid mutability and side-effects

The second rule is to avoid mutability – we touched on this briefly earlier, when we talked about limiting changes to external mutable state – and side effects.

But here we'll expand further. Basically, it boils down to this: don't change things! Once you've made it, it is immutable (unchanging over time).

var ages = [12,32,32,53] ages[1] = 12; // no! ages = []; // no! ages.push("2") // no!

If something has to change for your data structures, make changes to a copy.

const ages = [12,32,32,53] const newAges = ages.map(function (age){ if (age == 12) { return 20; } else { return age; } })

Can you see I made a copy with my necessary changes?

This element is repeated over and over again. Don't change state!

If we follow that rule, we will make heavy use of const so we know things wont change. But it has to go further than that. How about the below?

const changingObject = { willChange: 10 } changingObject.willChange = 10; // no! delete obj.willChange // no! 

The properties of changingObject should be locked down completely. const will only protect you from initializing over the variable.

const obj = Object.freeze({ cantChange: 'Locked' }) // The `freeze` function enforces immutability. obj.cantChange = 0 // Doesn't change the obj! delete obj.cantChange // Doesn't change the obj! obj.addProp = "Gotcha!" // Doesn't change the obj!

If we can't change the state of global variables, then we need to ensure:

  • We declare function arguments – any computation inside a function depends only on the arguments, and not on any global object or variable.
  • We don't alter a variable or object – create new variables and objects and return them if need be from a function.

Make your code referentially transparent

When you follow the rule of never changing state, your code becomes referentially transparent. That is, your function calls can be replaced with the values that they represent without affecting the result.

As a simple example of checking if your code is referentially transparent, look atthe below code snippet:

const greetAuthor = function(){ return 'Hi Kealan' }

You should be able to just swap that function call with the string it returns, and have no problems.

Functional programming with referentially transparent expressions makes you start to think about your code differently if you're used to object orientation.

But why?

Because instead of objects and mutable state in your code, you start to have pure functions, with no state change. You understand very clearly what you are expecting your function to return (as it never changes, when normally it might return different data types depending on state outside the function).

It can help you understand the flow better, understand what a function is doing just by skimming it, and be more rigorous with each function's responsibilities to come up with better decoupled systems.

You can learn more about referential transparency here.

Don't iterate

Hopefully, if you've paid attention so far, you see we aren't changing state. So just to be clear for loops go out the window:

for(let i = 0; i < arr.length; i++) { total += arr[i]; }

Because we are changing a variable's state there. Use the map higher order function instead.

More Features of Functional Programming

I hope at this point you have a good overview of what functional code is and isn't. But there's some final concepts used heavily in functional code that we have to cover.

In all the functional code I have read, these concepts and tools are used the most, and we have to cover them to get our foundational knowledge.

So here we go.

Recursion in Functional Programming

It's possible in JavaScript to call a function from the function itself.

So what we could always do:

function recurse(){ recurse(); }

The problem with this is that it isn't useful. It will run eventually until it crashes your browser. But the idea of recursion is a function calling itself from its function body. So let's see a more useful example:

function recurse(start, end){ if (start == end) { console.log(end) return; } else { console.log(start) return recurse(start+1, end) } } recurse(1, 10); // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

This code snippet will count from the start argument to the end argument. And it does so by calling its own function again.

So the order of this will look something like this:

Add a debugger inside the if blocks to follow this if it doesn't make sense to you. Recursion is one tool you can use to iterate in functional programming.

What makes the first example and the second example different? The second one has what we call "a base case". A base case lets the function eventually stop calling into itself infinitely. When start is equal to end we can stop recursing. As we know we have counted to the very end of our loop.

But each call of the functions is calling into its own function again, and adding on to the function argument.

The code example I just included for the counting example isn't a pure function. Why is that?

Because the console is state! And we logged string's to it.

This has been a brief introduction to recursion, but feel free to go here to learn more here.

Why use recursion?

Recursion allows us to stop mutating state variables, for one.

There are also certain data structures (tree structures) that are more efficient when solved with recursion. They generally require less code, so some coders like the readability of recursion.

Currying in Functional Programming

Currying is another tool used heavily in functional code. The arity of a function refers to how many arguments it receives.

// Let's talk arity function arity2(arg1, arg2){} // Function has an arity of 2 function arity0(){} // Function has an arity of 0 function arity2(arg1, arg2, arg3, arg4){} // Function has an arity of 4

Currying a function turns a function that has an arity of more than 1, to 1. It does this by returning an inner function to take the next argument. Here's an example:

function add(firstNum, secondNum){ return firstNum + secondNum; } // Lets curry this function function curryAdd(firstNum){ return function(secondNum){ return firstNum + secondNum; } }

Essentially, it restructures a function so it takes one argument, but it then returns another function to take the next argument, as many times as it needs to.

Why use currying?

The big benefit of currying is when you need to re-use the same function multiple times but only change one (or fewer) of the parameters. So you can save the first function call, something like this:

function curryAdd(firstNum){ return function(secondNum){ return firstNum + secondNum; } } let add10 = curryAdd(10); add10(2); // Returns 12 let add20 = curryAdd(20); add20(2); // Returns 22

Currying can also make your code easier to refactor. You don't have to change multiple places where you are passing in the wrong function arguments – just the one place, where you bound the first function call to the wrong argument.

It's also helpful if you can't supply all the arguments to a function at one time. You can just return the first function to call the inner function when you have all the arguments later.

Partial application in Functional Programming

Similarly, partial application means that you apply a few arguments to a function at a time and return another function that is applied to more arguments. Here's the best example I found from the MDN docs:

const module = { height: 42, getComputedHeight: function(height) { return this.height + height; } }; const unboundGetComputedHeight = module.getComputedHeight; console.log(unboundGetComputedHeight(32)); // The function gets invoked at the global scope // outputs: NaN // Outputs NaN as this.height is undefined (on scope of window) so does // undefined + 32 which returns NaN const boundGetComputedHeight = unboundGetComputedHeight.bind(module); console.log(boundGetComputedHeight(32)); // expected output: 74

bind is the best example of a partial application. Why?

Because we return an inner function that gets assigned to boundGetComputedHeight that gets called, with the this scope correctly set up and a new argument passed in later. We didn't assign all the arguments at once, but instead we returned a function to accept the rest of the arguments.

Why use partial application?

You can use partial application whenever you can't pass all your arguments at once, but can return functions from higher order functions to deal with the rest of the arguments.

Function composition in Functional Programming

The final topic that I think is fundamental to functional code is function composition.

Function composition allows us to take two or more functions and turn them into one function that does exactly what the two functions (or more) do.

// If we have these two functions function add10(num) { return num + 10; } function add100(num) { return num + 100; } // We can compose these two down to => function composed(num){ return add10(add100(num)); } composed(1) // Returns 111

You can take this further and create functions to compose any number of multiple arity functions together if you need that for your use case.

Why use function composition?

Composition allows you to structure your code out of re-usable functions, to stop repeating yourself. You can start to treat functions like small building blocks you can combine together to achieve a more complicated output.

These then become the "units" or the computation power in your programs. They're lots of small functions that work generically, all composed into larger functions to do the "real" work.

It's a powerful way of architecting your code, and keeps you from creating huge functions copied and pasted with tiny differences between them.

It can also help you test when your code is not tightly coupled. And it makes your code more reusable. You can just change the composition of your functions or add more tiny functions into the composition, rather than having all the code copied and pasted all over the codebase (for when you need it to do something similar but not quite the same as another function).

The example below is made trivial to help you understand, but I hope you see the power of function composition.

/// So here's an example where we have to copy and paste it function add50(num) { return num + 50; } // Ok. Now we need to add 30. But we still ALSO need elsewhere to add 50 still // So we need a new function function add30(num){ return num + 30; } // Ugh, business change again function add20(num){ return num + 20; } // Everytime we need to change the function ever so slightly. We need a new function //Let's use composition // Our small, reusable pure function function add10(num){ return num + 10; } function add50Composed(num){ return add10(add10(add10(add10(addNum(num))))); } function add30Composed(num){ return add10(add10(add10(num))); } function add20Composed(num){ return add10(add10(num)); }

Do you see how we composed new functions out of smaller, pure functions?

Conclusion

This article covered a lot. But I hope it has explained functional code simply, along with some of the repeating patterns you will see over and over again, in functional and even non-functional code.

Functional code isn't necessarily the best, and neither is object orientated code. Functional code is generally used for more math-based problems like data analysis. It's also very useful for high-availability real-time systems, like stuff written in Erlang (a functional language). But it genuinely does depend problem to problem.

I post my articles on Twitter. If you enjoyed this article you can read more there.

How to learn more

Start here, with freeCodeCamp's introduction to functional programming with JavaScript.

Look here for some libraries you can include and play around with, to really master functional programming.

Peruse this good overview of lots of functional concepts.

Finally, here's an excellent jargon-busting glossary of functional terms.