What is really needed turnouts function in JavaScript

Hello, Habr! I present to your attention the translation of the article "The real reason why JavaScript has arrow functions" by Martin Novák.





* meme phrase from the game Skyrim



If you still don’t use arrow functions, then don’t blame yourself — that’s your parents’s job; instead, think about the benefits you can get from using them as a diligent student. Today all my code is written using arrow functions.



This is an example of the same code, written in the traditional style as well:



const arrowFunction = (arg1, arg2) => arg1 + arg 2;

const traditionalFunction = function(arg1, arg2) {
  return arg1 + arg2;
};


You may notice that the code is much shorter when written using an arrow function. Everything written before the arrow is the arguments, after the arrow is the returned result.

If you need a function that contains multiple actions, you can write it like this:



const arrowFunction = (arg1, arg2) => {
  const result = arg1 + arg2;
  return result;
};


Arrow functions are also often referred to as lambda functions, and they are used not only in JavaScript. Python is a good example of where lambda functions also occur.



In Python, their syntax is as follows:



lambdaFunction = lambda a, b : a + b


Simplify



Using arrow functions motivates you to simplify your code according to the KISS principle (Keep-it-simple-stupid) and the principle of single responsibility (each function is responsible for only one specific action).



In general, I write them without curly braces {}. If a function is hard to read or you need to use several expressions in it, I advise you to break it down into several smaller ones.

This code is easier to write, easier to reuse and test. Also, functions can be given more descriptive names to accurately represent the work they are doing.



First class functions



JavaScript has first class functions. These are functions that are used like ordinary variables. They can act as arguments to other functions or return them as a result. Example with whom you are most likely familiar with:



document.querySelector('#myButton').addEventListner('click', function() {
  alert('click happened');
});


Shown here is an anonymous function passed as an argument to addEventListener. This method is often used in Javascript for callbacks.



An example of returning a function is different - shown below:



const myFirstClassFunction = function(a) {
  return function(b) {
    return a + b;
  };
};

myFirstClassFunction(1)(2); // => 3


However, with the arrow function, everything looks much cleaner:



const myFirstClassArrow = a => b => a + b;

myFirstClassArrow(1)(2); // => 3


Everything is simple here: what is written before the last arrow is the arguments, and after it is the calculation. In fact, we are working with several functions, and we can also use multiple calls fn (call1) (call2);



Partial application



You can start using arrow functions to compose, like Lego bricks, partially applicable functions. This will allow you to create custom functions by passing specific arguments to them. Let's break it down in the example below:



const add = a => b => a + b;

const increaseCounter = counter => add(1)(counter);
increaseCounter(5); // => 6

const pointFreeIncreaseCounter = add(1);
pointFreeIncreaseCounter(5); // => 6


This is similar to using functions with default variables, but partial application gives more flexibility.



These functions are called curried. They are a sequence of unary functions and monads that are common in functional programming.



Functional programming



As you might have guessed, the main reason for arrow functions is functional programming. It is a declarative style paradigm based on composition of simple functions.



Functional programming is an alternative to OOP preferred by many developers (including the author of the article). You can argue for any style, but I think functional programming is cool and it should make you uncomfortable just thinking that you once thought differently.



Pure functions rely only on input and always return some value. They never change (mutate) other variables and do not depend on external data outside of the input values. This results in referential transparency, which makes programming easier.



And yes, it is always possible to write a huge amount of code without changing a single variable.



As you might have noticed, arrow functions are designed to transform data between inputs and outputs. They don't even need to return a shorthand expression without curly braces.



Arrow functions - conclusion



Arrow functions make your syntax shorter, reducing the time to write, read, and test your code, and simplify it. Think about it, because most likely you are an advanced developer, and using these tips will make you more advanced and increase your relevance. Functional programming is really cool. It turns you into an artist who makes elegant short functions out of code.



Real functional example



To understand what is hidden in the rabbit hole, let's take a look at an example of using the open-source library @ 7urtle / lambda



import {trim, upperCaseOf, lengthOf, lastLetterOf, includes, compose} from '@7urtle/lambda';

const endsWithPunctuation = input =>
  includes(lastLetterOf(input))('.?,!');

const replacePunctuationWithExclamation = input =>
  substr(lengthOf(input) - 1)(0)(input) + '!';

const addExclamationMark = input =>
  endsWithPunctuation(input)
    ? replacePunctuationWithExclamation(input)
    : input + '!';

const shout = compose(addExclamationMark, upperCaseOf, trim);

shout(" Don't forget to feed the turtle.");
// =>    !


Using arrow functions and learning functional programming is very addictive. This allows you to write shorter code with better performance and reusability.



JavaScript can be tricky in its inconsistency between using C-like syntax and functional programming features. To help people understand better and provide access to learning materials, I developed the @ 7urtle / lambda library. You can master functional programming at your own pace and www.7urtle.com will help you learn this paradigm by providing you with all the tools you need.



All Articles