What does F = or F = a => mean in Javascript?
I have been working on the codegolf site lately , focusing on Javascript. I keep seeing things that I do not understand and cannot find the answer. Check this answer . The first line starts with . I am assuming this is a shorthand function declaration, but I cannot find a link to it elsewhere on the internet. Can someone explain or point me to a good document about this syntax? F=a=>
Feel free to bookmark this question. It's hard to tag when I don't know what I'm looking for.
source to share
If you look at the ES6 definition document, this is the arrow function symbol
Looking at the MDN documentation , this is just shorthand for anonymous function
An interesting difference is that the arrow function syntax provides a closure like so (quoting from MDN)
In ECMAScript 3/5, this issue was fixed by assigning a value in this to a variable that can be closed.
function Person() {
var self = this; // Some choose `that` instead of `self`.
// Choose one and be consistent.
self.age = 0;
setInterval(function growUp() {
// The callback refers to the `self` variable of which
// the value is the expected object.
self.age++;
}, 1000);
}
Alternatively, a bound function can be created, this value will be passed to growUp.
The arrow functions capture this enclosing context value, so the following code works as expected.
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // |this| properly refers to the person object
}, 1000);
}
var p = new Person();
You can see the difference very clearly in these two examples.
function() {
console.writeline('es5');
}
against
() => {
console.writeline('es6');
}
source to share
Yes, this is a shorthand expression for a function declaration.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
source to share