ES6 Standard JavaScript Arrow Function

Implementation guide for JavaScript ES6 Standard Arrow Function
A new function has been added to the ES6 standard: Arrow Function, why is it called Arrow Function? Because its definition uses an arrow.

Why is there an arrow function?

The traditional javascript function syntax does not provide any flexibility. Every time you need to define a function, you must enter function () {}, which will cause at least two problems, ES6 arrow functions have successfully solved it.

The first problem: the code input is too fast and it is easy to enter wrong or unnecessary input into the function, but in arrow(=>) function if you write this thing wrong, you can only say that it is a bit excessive.

The second problem: it saves a lot of code, the following ES6 code can achieve the same function, we intuitively feel the amount of code.

ES5 style:

function addFive(num) {
  return num + 5;
}
alert(addFive(10));

ES6 style:

var addFive = (num) => num + 5;
alert(addFive(5));
There is no function, no return, no (), no {}, these all become simple and easily understandable.

From the above, we can see that using arrow functions not only avoids errors but also allows us to lose a lot of code. Of course, the actual work is much more than this code.
On the one hand, it is because of the accumulation effect that each part is lost and put together, and on the other hand, it has more scenarios that can save code and greatly improve work efficiency.

Next we will talk about today's protagonist-arrow function.

ES6 Arrow Function allows using "arrow" (=>) to define a function is a shorthand function expression.

1. Arrow function syntax

In ES5 we implement a summation function:
var sum = function (x, y) {
  return x + y;
};
To use the arrow function, you can achieve the same function in two steps:

First use => to replace the keyword function
var sum = (x, y) => {
  return x + y;
};
Earlier we have said that using => to replace the keyword function means that the function will not be wrong. This is a wonderful design idea!

Secondly, when the function body has only one return statement, we can omit the bracket {} and return keywords:
var sum = (x, y) => x + y;
To exaggerate a little bit, if there is only one parameter, () can be omitted.

This is the most concise form of the arrow function, and is often used for simple processing functions, such as filtering:
// ES5
var array = ['1', '2345', '567', '89'];
array = array.filter(function (item) {
  return item.length > 2;
});
// ["2345", "567"]
// ES6
let array = ['1', '2345', '567', '89'];
array = array.filter((item) => item.length > 2);
// ["2345", "567"]
The main usage modes of arrow functions are as follows:
// a parameter corresponds to an expression
param => expression;
// For example
x => x + 2;
// Multiple parameters correspond to one expression
( ...param ) => expression;
// For example
( x, y ) => ( x + y );
// One parameter corresponds to multiple representations
param => { statements; }
// For example
x => { x++; return x; };
// Multiple parameters correspond to multiple expressions
( ...param ) => { statements }
// For example
( x, y ) => { x++; y++; return x * y; };
// There are no arguments in the expression
() => { statements; }
// For example
var flag = ( () => { return 1; } )(); //flag is equal to 1
// Pass in an expression and return an object
( [ param ] ) => ( { key: value } );
// For example
var fuc = ( x ) => ( { key: x } )
var object = fuc( 1 );
alert( object );//{key:1}
Don’t think it ’s a lot of trouble, but it ’s not complicated at all. You will get used to the new way of writing once or twice.

2. Use of this in the arrow function

The value of this within the arrow function is inherited from the outer scope. At runtime, it will first find its parent scope, if the parent scope is still an arrow function, then look up, until we find this keyword we want.

Let's first look at a classic problem about this:
var name = 'alpha';
var teacher = {
  name: 'beta',
  showName: function () {
    function showTest() {
      alert(this.name);
    }
    showTest();
  },
};
teacher.showName(); //The result is alpha
And we are looking forward to beta, here this keyword point to the window, we look forward to pointing to the teacher

As everyone knows, this in ES5 is nice to call "flexible". It is easy to make a mistake when the scope of this is not clear. But, using the arrow function to solve this problem is very handy.
var name = 'alpha';
var teacher = {
  name: 'beta',
  showName: function () {
    let showTest = () => alert(this.name);
    showTest();
  },
};
teacher.showName();
The keyword this in the arrow function is in the scope of the parent. The arrow function refers to the variable lexical scope of the parent, which means that the role of a variable is already defined when it is defined. When a variable is not found in this scope, it will always search in the parent scope until it is found.

Because this has been bound in the arrow function according to the lexical scope, when calling the arrow function with call or apply, this cannot be bound, that is, the first parameter passed is ignored:
var obj = {
  birth: 1996,
  getAge: function (year) {
    var b = this.birth; // 1996
    var fn = (y) => y - this.birth; // this.birth still is 1996
    return fn.call({birth: 1990}, year);
  },
};
obj.getAge(2020); // 24 ( 2020 - 1996)
Since this has already been bound at the lexical level, when calling a function through the call or apply method, only the parameters are passed in, which does not affect this. Therefore, this design saves developers time to think about context binding.

3. Characteristics of arrow functions

3.1 Arrow functions have no arguments

Not only does the arrow function not have this, but also the commonly used arguments. If you can get arguments, then it must come from the parent scope.
function foo() {
  return () => console.log(arguments);
}
foo(1, 2)(3, 4); // 1,2
In the above example, if the arrow function has arguments, it should output 3, 4 instead of 1,2.

The arrow function does not bind arguments and uses rest parameters instead. Solution
var foo = (...args) => {
  return args;
};
console.log(foo(1, 3, 56, 36, 634, 6)); // [1, 3, 56, 36, 634, 6]
To achieve an effect similar to a pure function, the arrow function must eliminate the external state. We can see that in addition to the parameters passed in, the arrow function does not have this keyword, arguments, and caller that are common in ordinary functions.

If you refer to variables other than this, arguments, or parameters in the arrow function, they must not be included in the arrow function itself but inherited from the parent scope.

3.2 New cannot be used in arrow functions

let Person = (name) => {
  this.name = name;
};
let one = new Person('person name');
Run the program, you will see TypeError: Person is not a constructor

3.3 Arrow functions can be used in conjunction with variable destructuring

const full = ({first, last}) => first + ' ' + last;
// Equivalent to
function full(person) {
  return person.first + ' ' + person.last;
}
full({first: 1, last: 5}); // '1 5'

3.4 Arrow functions have no prototype attributes

var foo = () => {};
console.log(foo.prototype); //undefined
It can be seen that the arrow function has no prototype.

Another mistake is to use arrow functions on the prototype, such as:
function A() {
  this.foo = 1;
}
A.prototype.bar = () => console.log(this.foo);
let a = new A();
a.bar(); //undefined
Similarly, this keyword in the arrow function does not point to A but traces back to the global scope according to the variable search rules. Similarly, there is no problem using ordinary functions. New cannot be added to the arrow function, which means that the arrow function cannot be used as a constructor.

3.5 Arrow functions cannot wrap

var func = () => 1; // SyntaxError: expected expression, got '=>'
If you really can't get a line in development, and there is a lot of logic, add {}, and you want to change the line.
var func = () => {
  return 'Come on';
  // 1.additional {} 2.additional return
};

4. Use scenarios of arrow functions

The story of this in JavaScript is very old, every function has its own context.

The purpose of the following example is to use jQuery to show a clock that updates every second:
$('.time').each(function () {
  setInterval(function () {
    $(this).text(Date.now());
  }, 1000);
});
When trying to use this in the callback of setInterval to refer to the DOM element, unfortunately, all we get is a callback function itself

The context of this. A common solution is to define a that or self variable:
$('.time').each(function () {
  var self = this;
  setInterval(function () {
    $(self).text(Date.now());
  }, 1000);
});
But when using arrow functions, this problem no longer exists. Because it does not produce this in its own context:
$('.time').each(function () {
  setInterval(() => $(this).text(Date.now()), 1000);
});
Another use of arrow functions is to simplify callback functions.
// Normal function writing
[1, 2, 3].map(function (x) {
  return x * x;
});
// Arrow function writing
[1, 2, 3].map((x) => x * x);
//Of course, it can also be used in the event monitoring function:
document.body.addEventListener('click', (event) => console.log(event, this));
// EventObject, BodyElement

5. Summary

5.1 Advantages of arrow functions

An arrow function is a short form of the function using => syntax. This is syntactically equivalent to C #, Java 8, Python (lambda function), and CoffeeScript. The relevant characteristics are very similar. It has very concise syntax, arrow functions have fewer verbs than ordinary functions, such as function or return.
() => {...} // Zero parameters are represented by ().
x => {...} // A parameter can be omitted ().
(x, y) => {...} // Multiple parameters cannot be omitted ().
If there is only one return, {} can be omitted.

It has a more intuitive scope and this binding, it allows us to deal well with the pointing problem of this. The arrow function plus the use of the let keyword will take us to the next level of JavaScript code.

5.2 arrow function usage scenarios

Arrow functions are suitable for pure function scenarios without complex logic or side effects. For example, they are used in the definition of callback functions for the map, reduce, and filter. Also, at present, libraries such as vue, react, and node all use arrow functions to directly define function functions. The situation is rare.

When writing new projects, you should constantly think about the use scenarios and characteristics of arrow functions, and enjoy the convenience brought by using arrow functions, so that they can grow faster.

Before continuing to use arrow functions, please test whether your browser supports ES6 Arrow Function.