I know that the >=
operator means more than or equal to, but I've seen =>
in some source code. What's the meaning of that operator?
Here's the code:
promiseTargetFile(fpParams, aSkipPrompt, relatedURI).then(aDialogAccepted => {
if (!aDialogAccepted)
return;
saveAsType = fpParams.saveAsType;
file = fpParams.file;
continueSave();
}).then(null, Components.utils.reportError);
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) {...}
. But they have some important differences. For example, they do not bind their own values of this
(see below for discussion).
Arrow functions are part of the ECMAscript 6 specification. They are not yet supported in all browsers, but they are partially or fully supported in Node v. 4.0+ and in most modern browsers in use as of 2018. (I’ve included a partial list of supporting browsers below).
You can read more in the Mozilla documentation on arrow functions.
From the Mozilla documentation:
An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the
this
value (does not bind its ownthis
,arguments
,super
, ornew.target
). Arrow functions are always anonymous. These function expressions are best suited for non-method functions and they can not be used as constructors.
this
Works in Arrow FunctionsOne of the most handy features of an arrow function is buried in the text above:
An arrow function... lexically binds the
this
value (does not bind its ownthis
...)
What this means in simpler terms is that the arrow function retains the this
value from its context and does not have its own this
. A traditional function may bind its own this
value, depending on how it is defined and called. This can require lots of gymnastics like self = this;
, etc., to access or manipulate this
from one function inside another function. For more info on this topic, see the explanation and examples in the Mozilla documentation.
Example (also from the docs):
var a = [
"We're up all night 'til the sun",
"We're up all night to get some",
"We're up all night for good fun",
"We're up all night to get lucky"
];
// These two assignments are equivalent:
// Old-school:
var a2 = a.map(function(s){ return s.length });
// ECMAscript 6 using arrow functions
var a3 = a.map( s => s.length );
// both a2 and a3 will be equal to [31, 30, 31, 31]
You can use arrow functions in Node, but browser support is spotty.
Browser support for this functionality has improved quite a bit, but it still is not widespread enough for most browser-based usages. As of December 12, 2017, it is supported in current versions of:
Not supported in:
You can find more (and more current) information at CanIUse.com (no affiliation).