The => operator in JavaScript

Question:

I study JavaScript, in Wikipedia I met an example of describing multidimensional arrays

the code is like this:

// Создание двумерного массива чисел: 
var array = [
    [11, 12, 13, 14, 15, 16], // Первая строка-массив
    [21, 22, 23, 24, 25, 26], // Вторая
    [31, 32, 33, 34, 35, 36]  // Третья
];

// Вывод массива на консоль:
array.forEach((subArray) => {   // Для каждого под-массива,
   subArray.forEach((item) => { // для каждого его элемента,
       console.log(item);       // — вывести этот элемент на консоль.
   });
});

Question: what does the => operator mean (is it an operator at all)? I am reading D. Flanagan's "JavaScript. A Detailed Guide", this operator does not appear in the text, I could not find a description on the network either.

Answer:

This operator is called an arrow function. Introduced since ECMA2015.
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Arrow functions help to significantly shorten the code, because

var a = a.map( s => s.length );

looks much better than

var a = a.map(function(s){ return s.length } );

Arrow functions solve another painful JavaScript problem: the need to pass this to the function's execution context. Each function has its own context, so you either have to assign this variable:

var that = this;
var filter1 = function(){
    // this != that
    return that.visible;
};

Or use bind to bind the context:

var filter1 = (function(){
        return this.visible;
    }).bind( this );

With an arrow function, everything is much simpler and more compact, because it does not create its own this context:

var filter1 = () => this.visible;
Scroll to Top