Modern JS Talk: Arrow Functions
Source: Dev.to
Overview
- New syntax introduced in ES2015
- Shorter than regular function expressions
- Lexically binds the value of
this, making the context easier to understand - Always creates anonymous functions
The key feature of arrow function expressions, written with =>, is that they lexically bind the value of this.
Basic Syntax
Traditional function expression
const foo = function() {
console.log(this);
};
foo();Arrow function equivalent
const foo = () => {
console.log(this);
};
foo();Parameter Rules
- No arguments – parentheses are required.
- One argument – parentheses are optional.
// No arguments
const foo = () => {
console.log(this);
};
foo();
// One argument (parentheses optional)
const foo = value => {
console.log(value);
};
foo('Hello!');Immediately Invoked Arrow Function
(() => {
console.log('Hello!');
})();Caution: this Binding
Arrow functions inherit this from the surrounding lexical scope. This can lead to unexpected results when used as object methods.
const objA = {
value: 'foo! foo!',
sayHi: function() {
console.log(this.value);
}
};
objA.sayHi(); // → 'foo! foo!'
const objB = {
value: 'bar! bar!',
sayHi: () => {
console.log(this.value);
}
};
objB.sayHi(); // → undefined (or the global object's value)In objA, this refers to the object itself, while in objB the arrow function captures the outer this (typically the global object), so this.value does not refer to objB.value.
When using frameworks such as Vue.js or React, understanding how this is bound can help keep code clear and maintainable.
References
- MDN – this
- MDN – Arrow Functions