Application 2017-12-25

Modern JS Talk: Arrow Functions

Learn arrow function syntax, lexical this binding, and ES2015 function expressions for modern JavaScript development.

Read in: ja
Modern JS Talk: Arrow Functions

β€»This article is a reprint from the Innovator Japan Engineers’ Blog.

What are Arrow Functions?

In summary,

The big point of arrow function expressions, written with =>, is that they "lexically bind the value of this".

With arrow functions, what used to be written like this...

const foo = function() {
  console.log(this);
}

foo();

Can now be written like this.

const foo = () => {
  console.log(this);
}

foo();

By the way, if there are no arguments, parentheses () are required, and if there is only one argument, parentheses are optional.

// Parentheses are required when there are no arguments
const foo = () => {
  console.log(this);
}

foo();
// Parentheses are optional when there is only one argument
const foo = (value) => {
  console.log(value);
}

foo('Hello!');

If you want to make it an immediately invoked function, you can write it like this.

(() => {
  console.log('Hello!');
})();

This might be a bit confusing...

When to Use

I think it's a good approach to actively replace where you can with arrow functions, but you should be aware of what this refers to.

For example, how about in the following case?

const objA = {
  value: 'foo! foo!',
  sayHi: function() {
    console.log(this.value);
  }
}

objA.sayHi();

const objB = {
  value: 'bar! bar!',
  sayHi: () => {
    console.log(this.value);
  }
}

objB.sayHi();

The first this returns the value within the object, while the second this returns the global object. Looking at cases like this, there seem to be some situations where you need to differentiate between function expressions and arrow function expressions.

For more details on JavaScript's this, please refer to MDN - this. Understanding "what the value of this refers to" will deepen your understanding of arrow functions and JS.

Summary

When using frameworks like Vue.js or React, the code tends to get lengthy, and this can be scattered all over, making it hard to understand. If you can use arrow functions to simplify the function parts, the code will be more readable.

References

Tags: ES5 ES6 JavaScript
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
β˜• Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles