Arrow functions in ES6

let someArray = [1,2,3,4,5,6],
= someArray.filter(function(elem){
return elem > 4;
console.log(filterArray); // [5,6]

Do such statements make you ask questions? I believe that no. This is kind of code we meet every day. The function is passed as an argument, for JavaScript is the same as strongly typed for Java.

We’ll rewrite the example above using the arrow functions in ES6.

let someArray = [1,2,3,4,5,6],
= someArray.filter(elem => elem > 4);
console.log(filterArray); // [5,6]

Not bad, right? The passed arguments are listed to the left of the operator =>.
If there are more than 1, then they turn into parentheses: (arg1, arg2, arg3) => … , If there are no arguments, then we write simply () => …

To the right of the sign of the arrow function is the body of the function itself.

someArray.filter(elem => elem > 4); // Arrow functions in ES6
someArray.filter(function(elem){return elem > 4;}); // ES5

If our entire function is a single expression — the arrow functions are what the doctor ordered! Nevertheless, we can write as many lines as you want, simply by wrapping them in {}.

The arrow functions are simply irreplaceable for me as a React developer, since 40% of all my functions are an enumeration of values, like:

const itemsList =, index) => 
<li key={index}>
Note that the functions of the arrows with the body as a block do not automatically return a value. In such cases, use the return statement.

The lexical meaning of “this” in arrow functions

So we came to the main reason for the appearance of arrow functions in JavaScript. Short syntax is, of course, good. But solving the problem with the dynamic value of this is better!

Prior to the ES6 standard, this was an actor who played all possible roles: (A new object in the case of a constructor, undefined in the strict mode of the function call, the context of the object when the function is called as an “object method”, etc.).

function Person() {
var self = this;
self.age = 0;

setInterval(function growUp() {
// this now points to a Global object
}, 1000);

Arrow functions capture the value of this surrounding context, so the following code works as intended:

function Person(){
this.age = 0;

setInterval(() => {
this.age++; // this now points to a object Person
}, 1000);

var p = new Person();

Pass through the context between multiple calls

Now I suggest a little trick) It is obvious that one arrow function can be placed into another, thereby «pass through» value this through them:

var obj = {
arr1: [1, 2, 3],
arr2: ['a', 'b', 'c'],
concatenate: function (a, b) {
return a + "|" + b
intersection: function () {
return this.arr1.reduce((sum, v1) => // arrow function 1
this.arr2.reduce((sum, v2) => { // arrow function 2
sum.push(this.concatenate(v1, v2));
return sum;
}, sum),
var arrSum = obj.intersection(); //['1|a', '1|b', '1|c', '2|a', '2|b', '2|c', '3|a', '3|b', '3|c']