Thomas McDevitt

all about fat arrows in javascript

One of the great things that ES6 JavaScript brought is fat arrow functions (also known as lambda functions) into the fray. This article visits their usage and when it is and isn’t a good thing to use them.

about fat arrows and how to lambda

An arrow function is a shorthand for a statement that returns a function. For the most part, they can be used in a very similar way to anonymous function declarations (see later for caveats to this approach) and are just easier ways to declare functions with one statement. The two examples of function declaration below are identical.

var doubleFn = function(input) {
  return input * 2;
}

var doubleLambda = (input) => input * 2;

console.log(doubleFn(10) === doubleLambda(10)); // true

When only using a single statement without curly braces, the return value of said statement implicitly becomes the return statement for the whole function. The return needs to be explicit in the doubleFn declaration above.

Only one statement? Nah. They can take more but we’re back to needing explicit return statements and both function declarations end up looking pretty much the same. It’s probably worth going with the old school declaration in this case.

var getUrlInfo = () => {
  console.log(window.location.host);
  if (window.location.hash) {
    console.log(window.location.hash);
  }
  return window.location.protocol === 'https';
}

What if I want to immediately return an empty object? Ahh. Obviously the first function in the example below is ambiguous. In this case, curly braces immediately get interpreted as braces for function statements, per the above. To return an empty object, we need to wrap it in normal brackets.

var getNewObject = () => {};
var getNewObjectImproved = () => ({});

getNewObject(); // undefined
getNewObjectImproved(); // Object {}

Can they be rebound? In short: no. Their lexical ‘this‘ is taken from the context in which the function was defined. Check the ‘context’ section below for details.

why they’re awesome

Less verbose function declarations are great for keeping code clutter down, as long as they’re used carefully. They’re also pretty nifty for tweaking function callback references when the following is an issue. Imagine a promise chain where callbacks are passed in as function references:

getSomeData()
  .then(modifyTheData)
  ...

function modifyTheData(parameter, data) {
  // ... data is the second argument!
  console.log('param:', parameter);
  console.log('data:', data);
}

The data passed from the previous state always gets passed into the next method as the first argument. If the callbacks can be set up accordingly, this just works as a pretty neat promise chain. Should the signature of the required method not match up, then the arguments are going to get confused and data are going to be mishandled. We have a few ways around this…

// we could simply write out the function in full...
getSomeData()
  .then(function(data) {
    return modifyTheData('parameter', data);
  });

// we could bind the arguments into place...
getSomeData()
  .then(modifyTheData.bind(null, 'parameter'));

// or we could use an arrow function!
getSomeData()
  .then(data => modifyTheData('parameter', data));

The best method here is user’s choice. What do you think? 🙂

watch out for context

Arrow functions will simply take the context in which they were declared as their lexical ‘this’ and this can’t be modified. If context isn’t important, there’s nothing to worry about. Lambda to your heart’s content. However, if setting up object properties for which ‘this’ is important, lambdas are not going to work.

var rectangle = {
  height: 10,
  width: 5,
  getArea: () => this.height * this.width
}

This method was declared in the window context and thus tries to access window.height and window.width which isn’t what we want. Here, an old school function declaration is the way to go. For a full list of when not to use fat arrow functions, check out this article.

always stay creative

Lambdas in JavaScript bring some great syntactic flexibility to the table. They’re a bit of a mixed blessing but, when used carefully, can still be very useful. Let us know what you think!

If you enjoyed the read, drop us a comment below or share the article, follow us on Twitter or subscribe to our #MetaBeers newsletter. Before you go, grab a PDF of the article, and let us know if it’s time we worked together.

blog comments powered by Disqus