As you advance in your experience with JavaScript, you will undoubtedly come across, and hopefully use, more and more "shortcuts". As new versions of JavaScript get released, more shortcuts are created allowing for developers to do the same thing but with less code. This might not seem like much, but if you are developing an app that runs tens of thousands of lines of code, every shortcut counts towards better performance.
The 2015 revision of JavaScript (ES6) introduced many new features including one of the most frequently used shortcuts in all of JavaScript: the "arrow function".
Arrow Function Syntax
Arrow functions operate almost like standard functions, just with a different syntax. Let's compare a standard function expression with an arrow function:
const greet = function() {
return "Hello"
}
const greet = () => "Hello"
Key differences in arrow function syntax:
- Omit the word "function" but keep the parentheses if there are no parameters
- Add the arrow function symbol "=>" after the parameters
- The "return" keyword is implied if no curly brackets are used (one-liner)
With Parameters
When using a single parameter, you can optionally remove the parentheses:
const printArg = function(arg) {
console.log(`What is the arg? It is ${arg}`)
}
const printArg = arg => console.log(`What is the arg? It is ${arg}`)
When you need multiple parameters, parentheses are required:
const multiply = (a, b) => a * b
Multiline Arrow Functions
When using curly brackets to wrap multiple lines of code, the keyword "return" is no longer implied and needs to be explicitly included:
const exampleFunction = () => {
const year = new Date().getFullYear()
return `The current year is: ${year}`
}