ES6 introduced/arrow function syntax/, a shorter way to write functions by using the special “fat arrow” (=>
)
Instead, you first include the parameters inside the ()
and then add an arrow =>
that points to the function body surrounded in { }
like this:
const getArea = (width, height) => {
const area = width * height
return area
}
console.log(getArea(9, 8))
Functions that take only a single parameter do not need that parameter to be enclosed in parentheses.
However, if a function takes zero or multiple parameters, parentheses are required
const functionName = () => {}
const sayHello = () => { console.log("Hello") }
const functionName = param => {}
const squareMe = num => {
return num * num
}
const functionName = (paramOne, paramTwo) => {}
const getArea = (width, height) => {
return width * height
}
A function body composed of a single-line block does not need curly braces or a return keyword
Without the curly braces, whatever that line evaluates will be automatically returned
This is referred to as implicit return
Examples
const squareMe = number => number * number
const verifyVotingEligibility = age => {
if (age > 18 ) {
return true
} else {
return false
}
}
Convert the following function to an arrow function
Store the arrow function in a variable named areaOfCircle
using const
function areaOfCircle(radius){
return Math.PI * (radius**2)
}