Typically, programmers are always looking for ways to make their jobs easier and faster. Enter in: Arrow Functions. They put the FUN in function.
Arrow functions were introduced in ES6, with the intention to write shorter function syntax. Sign me up!
Example of Name Function vs Arrow Function
As you can see it is much shorter and simpler code. For arrow functions we don’t need to use the curly braces or a return statement, thanks to arrow functions feature of implicit returns. Arrow functions return the value implicitly ONLY if the function has a single expression. If that is the case, the result will be implicitly returned once the function is called. With name functions, if there is not a return statement present when the function is called it will return undefined. If you use an arrow function, they shall not be named! You can, however, put them in a variable.
Arrow Functions come in many different variations, each with their own set of rules.
Fun Fact in 2nd example: If there is an _(underscore) in arrow function it indicates that params are discounted or ignored (or in this case not present).
- Parentheses are optional if there is only one parameter.
In the console:
Multiline Arrow Functions
- Sometimes we need something a bit more complex, like multiple expressions or statements. If this is the case, we’ll need to use curly braces to open and close the expression, while also explicitly using the keyword return.
In summary, arrow functions are just another tool from your tool box that help you to create magic from behind the curtains. When first exposed to the arrow function it may take your brain a hot second to adjust to the syntax, but with a little more exposure and practice you’ll see how helpful arrow functions can be.