Arrow Functions

Arrow functions are a newer feature in JavaScript that changes the way you can write functions...in a good way.


Shortcut

let square = function(a) {
   return a * a
}
console.log(square(2))
//4

Arrow functions are shortcuts for anonymous functions, which are also called a function expressions. We've been using those in some of our examples.

Let's see how we can make this example shorter by converting it to an arrow function.

First, you can get rid of the function keyword.

You'll need to add the arrow before the curly braces

If, and only if the function takes only one parameter, then you can get rid of the parenthesis around the parameter.

Arrow functions have implicit returns, so if the function returns only one expression, then you can get rid of the returns. If it has more than one line of code, you'll need to reintroduce the return.

Again, if it's only one line of code, then you can also remove the curly braces.

let square = a => a * a

You can see that arrow functions can be way shorter than traditional functions, but you can't just use them everywhere.


Arrows and Objects

info = {
  social: {
    youtube: 'https://youtube.com/planetoftheweb',
  },
  logSocial: function() {
    return console.log(this.social.youtube)
  }
}
info.logSocial();

You may be tempted to use arrow functions with method definitions, but the problem is that arrows do not have their own bindings to the this keyword, so you'd get an error if you try.

logSocial: () => console.log (this.social.youtube)

Object Shortcut

info = {
  social: {
    youtube: 'https://youtube.com/planetoftheweb',
  },
  logSocial() {
    return console.log(this.social.youtube)
  }
}
info.logSocial();

Here's a bonus tip, you can get rid of the function keyword when creating a method and get rid of the colon.


Arguments

function add(...theArgs) {
  let argSum = theArgs.reduce((sum, val) => sum + val)
  return argSum;
}
output = add(1,2,3,4,5);
console.log(output) //15

The arguments array like object is not available with Arrow functions, but you can use the rest parameters to get to arguments as well.

Here I rewrote a previous internal function as an arrow function and used theargs rest variable to pass things along.


Destructuring

function add(...theArgs) {
  let argSum = theArgs.reduce((sum, val) => sum + val)
  return argSum;
}
output = add(1,2,3,4,5);
console.log(output) //15

Try It

Once you understand arrow functions, you'll start to go nuts using tricks to really make them small.

I'm going to show you how to to take this further to make this entire thing a single line. Let's check it out.

console.log([1,2,3,4,5].reduce((sum, val) => sum + val))