The => operator in JavaScript


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

The code is as follows:

// Создание двумерного массива чисел: 
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 read D. Flanagan " JavaScript. Detailed guide", this operator is not found in the text, and I could not find a description on the network either.

Author: Kromster, 2016-05-29

4 answers

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

Arrow functions help to significantly reduce the code, because

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

It 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 context of the function execution. Each function has its own context, so you either have to assign this to the 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 the arrow function, everything is much simpler and more compact, because it does not create its own context this:

var filter1 = () => this.visible;
 17
Author: ReinRaus, 2016-06-02 08:02:39

This is a new (ECMAScript2015) type of function entry.
We read the description here, the specification here, and Google a bunch of examples to study so, for example is.


In short, this is, of course, less of a bookaf to write, does not have its own this, arguments and something else. Ideal for callback, torment with closure due to loss of context in the past. You already have an example of the work, I will not give it.

 7
Author: , 2016-05-30 00:09:27

() => {} - this is an arrow function. In fact, this is an analog of the usual anonymous function (function() {}), but with one important difference: this in the arrow function indicates the context in which this function is defined, while in the usual anonymous function this indicates the "object before the point".

It is enough to compare the 2 outputs of the following script:

let Namespace = {
    a: function() {
        return this;
    },

    b: () => {
        return this;
    },

    c: {
        a: function() {
            return this;
        },

        b: () => {
            return this;
        }
    }
}

console.log(Namespace.a(), Namespace.b());
console.log(Namespace.c.a(), Namespace.c.b());

The first console.log() will output the Namespace object first, and then the window object. The second console.log() will output the Namespace.c object first (the one the "object before the point"), and then again the object window (because the arrow functions in both cases are not defined inside a function, but directly in window, even though they are located inside the object Namespace (or Namespace.c in the second case)).

This property of arrow functions is extremely useful when using the functional style of OOP:

function ClassName() {
        function privateMethod() { // *
            console.log(this);
        }
    
        this.publicMethod = function() {
            privateMethod();
        }
    }
    
    let instance = new ClassName();
    instance.publicMethod();

Compare with:

function ClassName() {
        let privateMethod = () => { // *
            console.log(this);
        }
    
        this.publicMethod = function() {
            privateMethod();
        }
    }
    
    let instance = new ClassName();
    instance.publicMethod();

In the first case, this refers to the global object window (when using "use strict" this in general, it will be equal to undefined, which, in general, is much more logical), and in the second case-to the object itself instance (because this will be taken from scope'a level higher (which is what we are trying to achieve).

Previously, before arrow functions, similar behavior had to be achieved by "binding" the function to the context using .bind(), or using .call() and .apply() methods, or by saving this to a separate local a variable (usually called self) in the constructor body.

Will the notation style affect public methods? No. In the case of an ordinary anonymous function, this will be equal to the object before the point (and the object before the point is nothing but this), and in the case of the arrow function, this will be taken from scope'a level higher, in which it is the object we need.


As for the word "lambda", it seems to me that this is the way to call arrow functions (in in particular) is incorrect, because any anonymous function is usually called a lambda (and, as I pointed out above, an anonymous function can be not only an arrow function).

 7
Author: smellyshovel, 2017-09-14 17:51:23

This is the arrow function https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Here is some more information stackoverflow.com

// Basic syntax:
(param1, param2, paramN) => { statements }
(param1, param2, paramN) => expression
// equivalent to:  => { return expression; }

// Parentheses are optional when there's only one argument:
(singleParam) => { statements }
singleParam => { statements }

// A function with no arguments requires parentheses:
() => { statements }

// Advanced:
// Parenthesize the body to return an object literal expression:
params => ({foo: bar})

// Rest parameters are supported
(param1, param2, ...rest) => { statements }
 4
Author: jessez, 2017-05-23 12:39:15