Arrow functions have become the standard syntax in modern JavaScript. They offer a concise way to write functions, making your code lighter and more readable. Let’s explore arrow functions and their various syntax options with code examples.
Basic syntax
Two things to note:
- Parentheses are required when using multiple function parameters.
- In a one-liner arrow function, the result of the expression is automatically returned.
Zero or One Parameter
If your function has only one parameter, parentheses become optional. If there’s no parameter, then you do need the parentheses:
Multiple instructions
If your function has multiple lines of code, then you need curly braces and a return statement:
Why use arrow functions?
Aside from the syntax improvements described above, arrow functions are helpful in classes because they preserve the context of this
. By default, in JavaScript, this
means “the current function,” not “the current class instance.” Arrow functions fix that scope for us: