Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does arrow function '() => {}' mean in Javascript? [duplicate]

I was reading the source for ScrollListView and in several places I see the use of () => {}.

Such as on line 25,

this.cellReorderThreshold = () => {
    var ratio = (this.CELLHEIGHT*this.cellsWithinViewportCount)/4;
    return ratio < this.CELLHEIGHT ? 0 : ratio;
};

line 31,

this.container.addEventListener('scroll', () => this.onScroll(), false);

line 88.

resizeTimer = setTimeout(() => {
    this.containerHeight = this.container.offsetHeight;
}, 250);

Is this a shorthand for function and if it differs in any way, how so?

like image 747
cnotethegr8 Avatar asked Mar 13 '15 11:03

cnotethegr8


People also ask

What is the meaning of => in JavaScript?

What It Is. This is an arrow function. Arrow functions are a short syntax, introduced by ECMAscript 6, that can be used similarly to the way you would use function expressions. In other words, you can often use them in place of expressions like function (foo) {...} .

How are arrow functions () => {} different than traditional function expressions?

Unlike regular functions, arrow functions do not have their own this . The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.

What is the arrow function in JavaScript?

Arrow function is one of the features introduced in the ES6 version of JavaScript. It allows you to create functions in a cleaner way compared to regular functions. For example, This function // function expression let x = function(x, y) { return x * y; }

What does fat arrow mean in JavaScript?

Arrow functions allow us to use the fat arrow => operator to quickly define JavaScript functions, with or without parameters. We are able to omit the curly braces and the function and return keywords when creating a new JavaScript function to write shorter function syntax.


2 Answers

This is the new arrow syntax of ES6. It differs by the treatment of this: function gets a this according to the calling context (traditional semantics), but the arrow functions keep the this of the context of definition.

see http://tc39wiki.calculist.org/es6/arrow-functions/

like image 86
thriqon Avatar answered Nov 01 '22 14:11

thriqon


ECMAScript 6 arrow function introduce, Arrow (=>) part of the arrow function syntax.

Arrow functions work differently from traditional JavaScript functions. I'm found this article explain how is different from traditional function: http://www.nczonline.net/blog/2013/09/10/understanding-ecmascript-6-arrow-functions/

like image 27
Jaykumar Patel Avatar answered Nov 01 '22 14:11

Jaykumar Patel