Reputation: 5449
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);
Upvotes: 519
Views: 423858
Reputation: 28666
Arrow functions which is denoted by symbol (=>) helps you to create anonymous functions and methods. That leads to more shorter syntax. For example, below is a simple “Add” function which returns addition of two numbers.
function Add(num1 , num2 ){
return num1 + num2;
}
The above function becomes shorter by using “Arrow” syntax as shown below.
Above code has two parts as shown in the above diagram: -
Input: — This section specifies the input parameters to the anonymous function.
Logic: — This section comes after the symbol “=>”. This section has the logic of the actual function.
Many developers think that arrow function makes your syntax shorter, simpler and thus makes your code readable.
If you believe the above sentence, then let me assure you it’s a myth. If you think for a moment a properly written function with name is much readable than cryptic functions created in one line using an arrow symbol.
The main use of arrow function is to ensure that code runs in the callers context.
See the below code in which have a global variable "context" defined , this global variable is accessed inside a function "SomeOtherMethod" which is called from other method "SomeMethod".
This "SomeMethod" has local "context" variable. Now because "SomeOtherMethod" is called from ""SomeMethod" we expect it to display "local context" , but it displays "global context".
var context = “global context”;
function SomeOtherMethod(){
alert(this.context);
}
function SomeMethod(){
this.context = “local context”;
SomeOtherMethod();
}
var instance = new SomeMethod();
But if replace the call by using Arrow function it will display "local context".
var context = "global context";
function SomeMethod(){
this.context = "local context";
SomeOtherMethod = () => {
alert(this.context);
}
SomeOtherMethod();
}
var instance = new SomeMethod();
I would encourage you to read this link ( Arrow function in JavaScript ) which explain all the scenarios of javascript context and in which scenarios the callers context is not respected.
You can also see the demonstration of Arrow function with javascript in this youtube video I made which demonstrates practically the term Context.
Upvotes: 8
Reputation: 4338
JavaScript arrow functions are roughly the equivalent of lambda functions in python or blocks in Ruby. These are anonymous functions with their own special syntax and operate in the context of their enclosing scope. This mean they do not have their own "this" but instead access the one from the immediate enclosing function.
From the ECMA standard:
An ArrowFunction does not define local bindings for arguments, super, this, or new.target. Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment. Typically this will be the Function Environment of an immediately enclosing function.
Often you can read "an arrow function expression is a compact alternative to a traditional function expression", this is not a correct. Arrow function are NOT a shorthand for traditional function, they behave differently that traditional function.
Syntax
// Traditional Function
// Create their own scope inside the function
function (a){
return a + 100;
}
// Arrow Function
// Do NOT create their own scope
// (Each step along the way is a valid "arrow function")
// 1. Remove the word "function" and place arrow between the argument and opening body bracket
(a) => {
return a + 100;
}
// 2. Remove the body braces and word "return" -- the return is implied.
(a) => a + 100;
// 3. Remove the argument parentheses (only valid with exactly one argument)
a => a + 100;
Upvotes: 1
Reputation: 8205
Also known as Fat Arrow Functions. They're a clean and consise way to write function expressions, e.g. function() {}
.
Arrow Functions can remove the need of function
, return
and {}
when defining functions. They are one-liners, similar to Lambda Expressions in Java or Python.
const queue = ['Dave', 'Sarah', 'Sharon'];
const nextCustomer = () => queue[0];
console.log(nextCustomer()); // 'Dave'
If multiple statements need to be made within the same Arrow Function, you need to wrap, in this example, queue[0]
in curley brackets {}
. In this case the return statement cannot be omitted.
const queue = ['Dave', 'Sarah', 'Sharon'];
const addCustomer = name => {
queue.push(name);
};
addCustomer('Toby');
console.log(queue); // ['Dave', 'Sarah', 'Sharon', 'Toby']
You can omit {}
from the above.
When there is a single parameter, the brackets ()
around the parameter can be omitted.
const addNumbers = (x, y) => x + y
console.log(addNumbers(1, 5)); // 6
const fruits = [
{ name: 'Apple', price: 2 },
{ name: 'Bananna', price: 3 },
{ name: 'Pear', price: 1 }
];
If we wanted to get the price of every fruit in a single array, in ES5 we could do:
fruits.map(function(fruit) {
return fruit.price;
}); // [2, 3, 1]
In ES6 with the new Arrow Functions, we can make this more concise:
fruits.map(fruit => fruit.price); // [2, 3, 1]
Additional information on Arrow Functions can be found here.
Upvotes: 29
Reputation:
Dissatisfied with the other answers. The top voted answer as of 2019/3/13 is factually wrong.
The short terse version of what =>
means is it's a shortcut writing a function AND for binding it to the current this
const foo = a => a * 2;
Is effectively a shortcut for
const foo = function(a) { return a * 2; }.bind(this);
You can see all the things that got shortened. We didn't need function
, nor return
nor .bind(this)
nor even braces or parentheses
A slightly longer example of an arrow function might be
const foo = (width, height) => {
const area = width * height;
return area;
};
Showing that if we want multiple arguments to the function we need parentheses and if we want write more than a single expression we need braces and an explicit return
.
It's important to understand the .bind
part and it's a big topic. It has to do with what this
means in JavaScript.
ALL functions have an implicit parameter called this
. How this
is set when calling a function depends on how that function is called.
Take
function foo() { console.log(this); }
If you call it normally
function foo() { console.log(this); }
foo();
this
will be the global object.
If you're in strict mode
`use strict`;
function foo() { console.log(this); }
foo();
// or
function foo() {
`use strict`;
console.log(this);
}
foo();
It will be undefined
You can set this
directly using call
or apply
function foo(msg) { console.log(msg, this); }
const obj1 = {abc: 123}
const obj2 = {def: 456}
foo.call(obj1, 'hello'); // prints Hello {abc: 123}
foo.apply(obj2, ['hi']); // prints Hi {def: 456}
You can also set this
implicitly using the dot operator .
function foo(msg) { console.log(msg, this); }
const obj = {
abc: 123,
bar: foo,
}
obj.bar('Hola'); // prints Hola {abc:123, bar: f}
A problem comes up when you want to use a function as a callback or a listener. You make class and want to assign a function as the callback that accesses an instance of the class.
class ShowName {
constructor(name, elem) {
this.name = name;
elem.addEventListener('click', function() {
console.log(this.name); // won't work
});
}
}
The code above will not work because when the element fires the event and calls the function the this
value will not be the instance of the class.
One common way to solve that problem is to use .bind
class ShowName {
constructor(name, elem) {
this.name = name;
elem.addEventListener('click', function() {
console.log(this.name);
}.bind(this); // <=========== ADDED! ===========
}
}
Because the arrow syntax does the same thing we can write
class ShowName {
constructor(name, elem) {
this.name = name;
elem.addEventListener('click',() => {
console.log(this.name);
});
}
}
bind
effectively makes a new function. If bind
did not exist you could basically make your own like this
function bind(functionToBind, valueToUseForThis) {
return function(...args) {
functionToBind.call(valueToUseForThis, ...args);
};
}
In older JavaScript without the spread operator it would be
function bind(functionToBind, valueToUseForThis) {
return function() {
functionToBind.apply(valueToUseForThis, arguments);
};
}
Understanding that code requires an understanding of closures but the short version is bind
makes a new function that always calls the original function with the this
value that was bound to it. Arrow functions do the same thing since they are a shortcut for bind(this)
Upvotes: 11
Reputation: 3294
As others have stated, regular (traditional) functions use this
from the object that called the function, (e.g. a button that was clicked). Instead, arrow functions use this
from the object that defines the function.
Consider two almost identical functions:
regular = function() {
' Identical Part Here;
}
arrow = () => {
' Identical Part Here;
}
The snippet below demonstrates the fundamental difference between what this
represents for each function. The regular function outputs [object HTMLButtonElement]
whereas the arrow function outputs [object Window]
.
<html>
<button id="btn1">Regular: `this` comes from "this button"</button>
<br><br>
<button id="btn2">Arrow: `this` comes from object that defines the function</button>
<p id="res"/>
<script>
regular = function() {
document.getElementById("res").innerHTML = this;
}
arrow = () => {
document.getElementById("res").innerHTML = this;
}
document.getElementById("btn1").addEventListener("click", regular);
document.getElementById("btn2").addEventListener("click", arrow);
</script>
</html>
Upvotes: 2
Reputation: 13596
That's known as an Arrow Function, part of the ECMAScript 2015 spec...
var foo = ['a', 'ab', 'abc'];
var bar = foo.map(f => f.length);
console.log(bar); // 1,2,3
Shorter syntax than the previous:
// < ES6:
var foo = ['a', 'ab', 'abc'];
var bar = foo.map(function(f) {
return f.length;
});
console.log(bar); // 1,2,3
The other awesome thing is lexical this
... Usually, you'd do something like:
function Foo() {
this.name = name;
this.count = 0;
this.startCounting();
}
Foo.prototype.startCounting = function() {
var self = this;
setInterval(function() {
// this is the Window, not Foo {}, as you might expect
console.log(this); // [object Window]
// that's why we reassign this to self before setInterval()
console.log(self.count);
self.count++;
}, 1000)
}
new Foo();
But that could be rewritten with the arrow like this:
function Foo() {
this.name = name;
this.count = 0;
this.startCounting();
}
Foo.prototype.startCounting = function() {
setInterval(() => {
console.log(this); // [object Object]
console.log(this.count); // 1, 2, 3
this.count++;
}, 1000)
}
new Foo();
For more, here's a pretty good answer for when to use arrow functions.
Upvotes: 88
Reputation: 44851
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).
Upvotes: 623
Reputation: 36650
ES6
Arrow functions:In javascript the =>
is the symbol of an arrow function expression. A arrow function expression does not have its own this
binding and therefore cannot be used as a constructor function. for example:
var words = 'hi from outside object';
let obj = {
words: 'hi from inside object',
talk1: () => {console.log(this.words)},
talk2: function () {console.log(this.words)}
}
obj.talk1(); // doesn't have its own this binding, this === window
obj.talk2(); // does have its own this binding, this is obj
{}
and the return
statementFor example:
let times2 = val => val * 2;
// It is on the same line and returns an expression therefore the {} are ommited and the expression returns implictly
// there also is only one argument, therefore the parentheses around the argument are omitted
console.log(times2(3));
Upvotes: 1
Reputation: 45140
Adding simple CRUD example with Arrowfunction
//Arrow Function
var customers = [
{
name: 'Dave',
contact:'9192631770'
},
{
name: 'Sarah',
contact:'9192631770'
},
{
name: 'Akhil',
contact:'9928462656'
}],
// No Param READ
getFirstCustomer = () => {
console.log(this);
return customers[0];
};
console.log("First Customer "+JSON.stringify(getFirstCustomer())); // 'Dave'
//1 Param SEARCH
getNthCustomer = index=>{
if( index>customers.length)
{
return "No such thing";
}
else{
return customers[index];
}
};
console.log("Nth Customer is " +JSON.stringify(getNthCustomer(1)));
//2params ADD
addCustomer = (name, contact)=> customers.push({
'name': name,
'contact':contact
});
addCustomer('Hitesh','8888813275');
console.log("Added Customer "+JSON.stringify(customers));
//2 param UPDATE
updateCustomerName = (index, newName)=>{customers[index].name= newName};
updateCustomerName(customers.length-1,"HiteshSahu");
console.log("Updated Customer "+JSON.stringify(customers));
//1 param DELETE
removeCustomer = (customerToRemove) => customers.pop(customerToRemove);
removeCustomer(getFirstCustomer());
console.log("Removed Customer "+JSON.stringify(customers));
Upvotes: 6
Reputation: 19725
just to add another example of what a lambda can do without using map:
a = 10
b = 2
var mixed = (a,b) => a * b;
// OR
var mixed = (a,b) => { (any logic); return a * b };
console.log(mixed(a,b))
// 20
Upvotes: 22
Reputation: 288580
As others have said, it's a new syntax to create functions.
However, this kind of functions differ from normal ones:
They bind the this
value. As explained by the spec,
An ArrowFunction does not define local bindings for
arguments
,super
,this
, ornew.target
. Any reference toarguments
,super
,this
, ornew.target
within an ArrowFunction must resolve to a binding in a lexically enclosing environment. Typically this will be the Function Environment of an immediately enclosing function.Even though an ArrowFunction may contain references to
super
, the function object created in step 4 is not made into a method by performing MakeMethod. An ArrowFunction that referencessuper
is always contained within a non-ArrowFunction and the necessary state to implementsuper
is accessible via the scope that is captured by the function object of the ArrowFunction.
They are non-constructors.
That means they have no [[Construct]] internal method, and thus can't be instantiated, e.g.
var f = a => a;
f(123); // 123
new f(); // TypeError: f is not a constructor
Upvotes: 14
Reputation: 26827
As all of the other answers have already said, it's part of ES2015 arrow function syntax. More specifically, it's not an operator, it's a punctuator token that separates the parameters from the body: ArrowFunction : ArrowParameters => ConciseBody
. E.g. (params) => { /* body */ }
.
Upvotes: 2
Reputation: 25892
I've read, this is a symbol of Arrow Functions
in ES6
this
var a2 = a.map(function(s){ return s.length });
using Arrow Function
can be written as
var a3 = a.map( s => s.length );
Upvotes: 8
Reputation: 8510
This would be the "arrow function expression" introduced in ECMAScript 6.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/arrow_functions
For historical purposes (if the wiki page changes later), it is:
An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value. Arrow functions are always anonymous.
Upvotes: 25