Question:
I'm learning JavaScript, on Wikipedia I came across 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 is not found in the text, I could not find a description on the net either.
Answer:
This operator is called an arrow function. Introduced with ECMA2015.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Arrow functions help to significantly reduce 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 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
to a 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;