Arrow functions
Arrow functions are pretty cool. They help you make code shorter, which gives less room for errors to hide. They also help you write code that’s easier to understand once you get used to the syntax.
We’ll be using a lot of arrow functions in this course.
The basic syntax
An arrow function is denoted by the fat arrow (=>
). It is a new way to make anonymous functions in ES6.
Here’s what it looks like:
// Normal Function (with Function expression)
const normalFunction = function (arg1, arg2) {
// Do something
}
// Arrow Function
const arrowFunction = (arg1, arg2) => {
// Do something
}
See the similarity? Basically, you remove the function
keyword from a normal function, then add a =>
after the parenthesis to get an arrow function.
But that’s not everything. The syntax of an arrow function can change depending on two factors:
- The number of arguments required
- Whether you’d like an implicit return
The number of arguments
If you supply zero arguments to your arrow function, you can substitute the parenthesis with an underscore (_
).
const zeroArgs = () => {/* do something */}
const zeroWithUnderscore = _ => {/* do something */}
If you supply only one argument, you can remove the parenthesis.
const oneArg = arg1 => {/* do something */}
const oneArgWithParenthesis = (arg1) => {/* do something */}
If you supply two or more arguments, you need to use the basic arrow function syntax.
const twoOrMoreArgs = (arg1, arg2) => {/* do something */}
This flexibility in deciding whether to omit parenthesis and replacing parenthesis with underscores allows you to declare a function with less code compared to typing function functionName () {}
.
Whether you’d like an implicit return
Arrow functions automatically create a return
statement if two conditions are present:
- You write only one line of code in the function
- That line of code is not enclosed in curly braces (
{}
)
This implicit return feature lets you reduce three lines of code into a single line.
// 3 lines of code with a normal function
const sumNormal = function (num1, num2) {
return num1 + num2
}
// Can be replaced with one line of code with an arrow function
const sumArrow = (num1, num2) => num1 + num2
Exercise
Arrow functions are important. You’ll see more and more arrow functions in the future. We’re also going to use them a lot in this course. Make sure you’re familiar with them.
For this lesson, do the following:
- Make a function named
ten
that takes in zero arguments and return the value 10. Try using both ()
and _
syntax.
- Make a function named
logger
that takes in one argument. It logs the argument you passed into it. Try it with and without parenthesis ()
.
- Make a function called
add
that adds two numbers together. Try it with and without implicit returns.
- Make a function called
multiply
that multiplies two numbers together. Try it with and without implicit returns.