ES6 - A beginners guide - Arrow Functions

Stefan Wright - Aug 31 '21 - - Dev Community

Hello! Welcome back to the next part in my series as I work through training resources refreshing (and in some cases learning more) my understanding of ES6. In this post I'll be covering ES6's implementation of Arrow Functions 😍

Arrow Functions are probably one of my favourite additions because visually I feel it makes a HUGE difference when reading the code on the screen. We can make function declarations shorter and more concise, making it easier when a new developer comes to inspect your code to make amendments or reviews.

So... What are they?

Let's imagine we wrote a function using the "old" way of working, it might look something like this:

function someFunkyFunction(param1, param2) {
  var retValue;
  retValue = param1 + param2;
  return retValue;
}
someFunkyFunction(1,2); // Returns: 3
Enter fullscreen mode Exit fullscreen mode

With this way of working there are certain things I feel are inefficient:

  • The code is 115 characters, we can make that smaller!
  • We must always use a return statement at the end of the function
  • We have to write the word function everytime

Let's make it into an arrow function:

someFunkyFunction = (param1, param2) => {
  var retValue;
  retValue = param1 + param2;
  return retValue;
}
someFunkyFunction(1,2); // Returns: 3
Enter fullscreen mode Exit fullscreen mode

With this way of working there are still some things I feel can be improved (and they can be):

  • The code is 112 characters, it is a bit smaller, but we can lose more weight!
  • We must always always use a return statement at the end of the function still

But wait!!! There is a way to make this smaller, take a look:

someFunkyFunction = (param1, param2) => param1 + param2;
someFunkyFunction(1,2); // Returns: 3
Enter fullscreen mode Exit fullscreen mode

With this way of working you can see the following:

  • The code is now only 56 characters in length! that's a massive saving!
  • There is no return statement

WAIT!! No return statement??

That's right, when using this final version of an ES6 arrow function we can remove the arrow function. But why? Well, if you are performing a single JS expression as part of your ES6 Arrow Function the it's output and inherently be the return value. In doing this we can remove the surrounding curly braces from the function, aswell as the word return.

Extra

If you create an arrow function that only takes a single parameter then you can make things even smaller because you can also remove the brackets from the parameters of the Arrow Function. Let's have a look at an example:

someFunkyFunction = param1 => param1 * 2;
someFunkyFunction(1) // Returns: 2
Enter fullscreen mode Exit fullscreen mode

Now that's tidy!

. . . . . . . . . . . . .
Terabox Video Player