Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority!
Code is a way to communicate with developers reading it. Functions with intention-revealing names are easier to read. We read the function name and can understand its purpose. The function name is our tool for expressing intent on a piece of code.
Let’s look at a list of operations done in a functional style with the use of anonymous functions.
function getTodos(users){
return todos
.filter(todo => !todo.completed && todo.type === "RE")
.map(todo => ({
title : todo.title,
userName : users[todo.userId].name
}))
.sort((todo1, todo2) =>
todo1.userName.localeCompare(todo2.userName));
}
Now check the same functionality refactored using functions with intention-revealing names.
function isTopPriority(todo){
return !todo.completed && todo.type === "RE";
}
function ascByUserName(todo1, todo2){
return todo1.userName.localeCompare(todo2.userName);
}
function getTodos(users){
function toViewModel(todo){
return {
title : todo.title,
userName : users[todo.userId].name
}
}
return todos.filter(isTopPriority)
.map(toViewModel).sort(ascByUserName);
}
Function names give clarity to the code. With a good function name, you just have to read the name — you don’t need to analyze its code to understand what it does.
It’s widely estimated that developers spend 70% of code maintenance time on reading to understand it.
Kyle Simpson in Functional-Light JavaScript
Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority!
For more on applying functional programming techniques in React take a look at Functional React.
Learn functional React, in a project-based way, with Functional Architecture with React and Redux.