Master JavaScript Arrow Functions: Simplify Code and Manage ‘this’
This article explains how JavaScript arrow functions can make code more concise and simplify handling of the this keyword, covering syntax differences, implicit returns, logging, object returns, practical examples with map, promises, and refactoring techniques for modern web development.
Arrow functions are a fundamental building block for modern web applications. They provide a shorter syntax and make the this keyword easier to manage.
Basic Syntax Comparison
Traditional function declaration and expression:
// function declaration
function add(x, y) {
return x + y;
}
// function expression
var add = function(x, y) {
return x + y;
};Equivalent arrow function:
var add = (x, y) => {
return x + y;
};Implicit Return
If the function body consists of a single expression, the return keyword can be omitted and the value is returned implicitly:
var add = (x, y) => x + y;Practical Example with map
Using an arrow function inside Array.prototype.map makes the code more readable:
users.map(user => console.log(user));Refactoring a Promise Chain
Original getTweets function using regular functions:
function getTweets(uid) {
return fetch('https://api.users.com/' + uid)
.then(function(response) {
return response.json();
})
.then(function(response) {
return response.data;
})
.then(function(tweets) {
return tweets.filter(function(tweet) {
return tweet.stars > 50;
});
});
}Refactored with arrow functions and implicit returns:
function getTweets(uid) {
return fetch('https://api.users.com/' + uid)
.then(response => response.json())
.then(data => data)
.then(tweets => tweets.filter(tweet => tweet.stars > 50));
}If the function has a single parameter, the surrounding parentheses can be omitted:
function getTweets(uid) {
return fetch('https://api.users.com/' + uid)
.then(response => response.json())
.then(data => data)
.then(tweets => tweets.filter(tweet => tweet.stars > 50));
}Arrow Functions and this in React
Typical ES5 React component that binds this manually:
class Popular extends React.Component {
constructor(props) {
super();
this.state = { repos: null };
this.updateLanguage = this.updateLanguage.bind(this);
}
componentDidMount() {
this.updateLanguage('javascript');
}
updateLanguage(lang) {
api.fetchPopularRepos(lang)
.then(function(repos) {
this.setState(() => ({ repos }));
});
}
render() {
// Stuff
}
}The above code throws “Cannot read property 'setState' of undefined” because the regular function creates its own this. Using an arrow function preserves the lexical this and eliminates the need for .bind:
updateLanguage(lang) {
api.fetchPopularRepos(lang)
.then(repos => this.setState(() => ({ repos })));
}Returning an Object Implicitly
When an arrow function needs to return an object implicitly, wrap the object in parentheses to avoid being parsed as a block:
this.setState(nextState => ({ repos: nextState.repos }));Alternatively, combine logging with the logical OR operator to keep the code concise:
this.setState(nextState => console.log(nextState) || { repos: nextState.repos });Overall, arrow functions reduce boilerplate, improve readability, and simplify this handling in modern JavaScript development.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JD.com Experience Design Center
Professional, creative, passionate about design. The JD.com User Experience Design Department is committed to creating better e-commerce shopping experiences.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
