Arrow functions
JavaScript is moving forward to his ES6
version. One of his new features introduces the arrow function syntax.
Functions are everywhere
Anonymous functions
Anonymous functions are one of the most common characteristics in JavaScript. It's a function declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation.
setTimeout(function() {
console.log('AnonFun called.');
}, 250);
Arguments to other functions is the most common use of the anonymous functions.
Referenced
// Function operator.
var fnKnowIt = function() {
console.log('I know how I am');
};
// Function declarator.
function fnKnowItToo() {
console.log('Me too.');
}
Methods
Functions could be constructors or methods. Declared in object literals definitions or by prototype extension. Nothing more than just properties that happens to contain functions.
var Car = {
run: function() {
console.log('This is exactly how cars works.');
}
};
How a function is called determines the value of this
.
Not quite simple. His behaviour changes between strict
mode and not-strict mode.
You should check out MDN documentation about this. This's kind of a ripoff for them.
function f1(){
return this;
}
f1() === window;
function f2(){
'use strict';
return this;
}
f2() === undefined;
Why? Because the object-oriented style that JavaScript may have, the fact that every new function defined its own this
value its wired.
Arrow functions in a nutshell
Two factors influenced the introduction of arrow functions: shorter functions and lexical this. – Mozilla.
Shorter functions and lexical this.
Shorter
Because there is no descriptive label like function
, the syntax of the arrow functions may look a little odd at first.
The most basic use is (params) => statement
.
A statement could be a block of statements using { statements }
.
Using block of statements.
// Without paramenters.
setTimeout(() => {
console.log('Testingo');
}, 250);
// With parameters.
.then((err, response) => {
if (!err) console.log(response.data);
});
With just one statement (act as there's a return
).
// Without parameters.
setTimeout(() => console.log('Testingo'), 250);
// With parameters.
.then((param) => console.log('The param is:', param));
// Return an object literal.
.then(() => ({ hello: 'world' });
So, in resume, how short is this?
// Instead of doing a map like this:
[1, 2, 3].map(function(elem) {
return elem * 2;
});
// You could write this:
[1, 2, 3].map((elem) => elem * 2);
Lexical this
The main reason for using arrow functions is without a doubt the lexical this. In short: Arrow functions doesn't have their own this
.
Example:
var Car = {
isRunning: false,
run: function() {
// In this scope, the value of `this` is the instance.
$.post('/car/', {running: true}, () => {
// In this scope, the value of this remain the same.
this.isRunning = true;
});
}
}
The most common alternatives to the previous example are:
// Declaring a context helper variable.
var self = this;
$.post('/car/', {running: true}, function() {
self.isRunning = true;
});
// Binding the this.
$.post('/car/', {running: true}, function() {
this.isRunning = true;
}.bind(this));
From MDN documentation:
The bind()
method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
When not to use arrow functions
You should try to use arrow functions everywhere, but be aware of the following cases.
- Global context.
- Declaring methods using
Object.prototype
. - Declaring methods with the object literal notation.
- Passing into third-party library callbacks, like in jQuery
.on('click', callback)
events handling wherethis
is probably the DOM object.
Subscribe to RECodes
Get the latest posts delivered right to your inbox