Introduction
Converting Named Functions with at least one Parameter to Arrow Functions
Here, we’ve defined a simple function using the ECMAScript 5 (ES5) standardised syntax, employing the ‘function’ and ‘return’ keywords. It has at least ONE parameter meaning, one argument is passed into its function call:
Let’s apply the 6 steps to convert the greetUser
function to an arrow function:
-
- Omit the ‘function’ keyword, leaving just the name of the function:
-
- Replace the ‘function’ keyword with the ‘const’ keyword before the function name, treating it like a constant variable declaration:
- Add an ‘=’ after the constant name, followed by the remaining ‘( )’ parentheses containing the arguments:
- Use the ‘=>’ arrow after the parentheses:
- Add ‘{ }’ curly braces to encapsulate the body of your old function code:
- Place the actual function code inside these curly braces:
Now, considering the function body has a single expression, you can apply the optional 7th step to make it more concise:
-
- Omit the ‘return’ keyword and curly braces when there’s a single expression:
Above you can see ES5 syntax of the greetUser function followed by the final arrow function equivalent after applying the steps.
Converting Named Functions with two or more Parameters to Arrow Functions
Take a simple function that adds to numbers and returns the value:
In the above the body of the function takes up more than one line. When this is the case, we must retain the curly braces ‘ { } ‘ when we convert it into an arrow function:
We could shorten the above arrow function if we simply returned the sum of num1 and num2 without storing it in a variable, in doing so we could keep the entire expression one line:
As you can see in the above, we got rid of three things: the ‘function’ and ‘return’ keywords along with the curly braces ‘ { } ‘ as the body of the function was just one line.