Learning JavaScript: Arrow Functions
Condense your function definitions with fat arrow functions
If you’ve dabbled in JavaScript for any length of time, you’ve probably come across the fat arrow notation => in some code and wondered what it means.
Looking at some examples carefully, it isn’t too hard to figure out that there are inputs, statements, and outputs. Considering it’s called an arrow function you can take that logical leap.const convertString = (s) => {
return s.replace(" ","_").toLowerCase();
}console.log(convertString("Hello World"));
// prints hello_world// convertString is the name
// (s)is the parameter list
// the curly braces define the body of the function
But how do arrow functions actually work? How did they come about? Why change from normal function definitions? And most importantly, how can I begin using them?
To answer these questions, let’s not talk about them as if we’re brand new to JavaScript, but rather as if we have existing code that we’d like to convert to the latest and greatest of ES6.
What Are Arrow Functions?
An arrow function is a condensed representation of an anonymous function, which is a function that does not have an independent declaration.
You’ve probably built the habit of defining functions, but if you’re like me and you’re not a developer in your day job, you may not realize there are efficiencies to be had while still writing organized and concise code.
So, let’s learn together! Our next step is to understand how anonymous functions work, then we’ll go about converting our traditional functions to anonymous, and finally to arrow notation.
How Do Anonymous Functions Work?
Anonymous functions are most commonly used when a method accepts a function as a parameter and that function is not intended to be used repeatedly.
Thus, it is most efficient and readable to define the function inline and without name as it can be discarded thereafter. You see this happen frequently with methods that accept a function as the argument.// the map method performs a function on each element in the arrayconst numbers = [1,2,3,4]
const squares = numbers.map((n) => {
return n ** 2;
});console.log(squares); // 1,4,9,16
If this code causes squinting, double-takes, or head scratching, here is the same example with a traditionally defined function:function calcSquare(n) {
return n ** 2;
}// the map method performs a function on each element in the arrayconst numbers = [1,2,3,4]
const squares = numbers.map(calcSquare);console.log(squares); // 1,4,9,16
So, why change if traditional functions still work?
Arrow Function Syntax Is Cleaner
Writing functions in this syntax requires less overhead (literal characters typed) and accommodates the reality that functions in JS are no longer written neatly at the top of every script and called below.
Beyond the deprecation of the function keyword, arrow functions have other syntactic efficiencies that may be confusing at first, but once explained are super cool.
Here’s a list of the syntax changes for your reference:
No function keyword
If your code block has inputs, statements, and (presumably) outputs then it sounds a lot like a function.
There is no need to further define what is taking place. The only other time the above conditions will be present is with class methods, but that is within a class so there is a clear distinction.
No function name, unless you want it
What is the difference between an anonymous function and a named one? Well, it’s the name.
Instead of juggling arrow syntax and traditional syntax, we can absorb traditional functions into the arrow syntax, reducing the number of necessary coding conventions. Simply assign the anonymous function to a variable whose name will be used to invoke the function.
Skip the parentheses for a single parameter
If your function only has one parameter then you can optionally skip the parentheses. This further condenses the code, perhaps making it harder to read as a novice, but easier to write and scan once understood.
Skip the curly braces and return for a single statement
If the body of your function is only a single statement then you can skip the curly braces and even the return statement.
Like the omission of skipping parentheses for a single parameter, this can be mind-bogglingly condensed at first, but is so much less syntax to type and read once proficient.
How Can I Begin Using Arrow Functions?
If you’re a brand new JavaScript learner then you simply use arrow notation to define functions. Falling into this camp, if you are struggling then the real questions you need to ask are: “What are functions and how do I use them?”
If you’ve written JS before and are trying to convert your code practices then it’s a matter of translating old to new.
Let’s demonstrate the translation by taking the calcSquare() function from before and optimizing it through arrow notation.function calcSquare(n) {
let result = n ** 2;
return result;
}let numbers = [1,2,3,4];
console.log(numbers.map(calcSquare));
So, our function is only being used one time to square each value in an array. We’ll remove the standalone definition and create an anonymous function within the .map() method.let numbers = [1,2,3,4];
console.log(numbers.map((n) => {
let result = n ** 2;
return result;
}));
But what if there are two data sets, meaning the function has to be used multiple times? We will pull the function back out from the .map() method; however, this time, it will be defined with arrow notation.const calcSquares = (n) => {
result = n ** 2;
return result;
};let numbers = [1,2,3,4];
console.log(numbers.map(calcSquares));let numbers2 = [5,6,7,8];
console.log(numbers2.map(calcSquares));
At this point, we’ve fully upgraded to arrow notation, but it’s not time to call it a day. We can remove the parentheses because our function has only one parameter.const calcSquares = n => {
result = n ** 2;
return result;
}
Furthermore, as we can condense the body into a single statement by returning the evaluation directly, we can remove the curly braces and return keyword.const calcSquares = n => n ** 2;
Pause for a second here and look at how much we condensed our function. Wow…
As we’ve taken an existing function and converted it to arrow notation, use this as a starting point for all future functions by remembering the boilerplate:const functionName = () => {};
- If your function is anonymous, skip the variable assignment.
- If your function has one parameter, remove the parentheses.
- If your function has one statement in the body, remove the curly braces and do not bother with the
returnkeyword.
Conclusion
Ultimately, I think arrow functions are probably easier to learn as a brand new learner, but for those of us who are mentally overwriting previous coding conventions, remember that arrow notation is a streamlined, condensed, and optimized method for defining functions in JavaScript.