Rewriting a Regular Function with ES6 Arrow Syntax
Here’s a standard way to declare a function and then call it in JavaScript:
// function declaration
function sayHiStranger() {
return 'Hi, stranger!'
}
// call the function
sayHiStranger()
You can also write the same function as a function expression, like this:
const sayHiStranger = function () {
return 'Hi, stranger!'
}
JavaScript arrow functions are always expressions. Here’s how you could rewrite the function above using the fat arrow notation:
const sayHiStranger = () => 'Hi, stranger'
The benefits of this include:
- just one line of code
- no function keyword
- no return keyword
- and no curly braces {}
when you have more than one paremeter:
const getNetflixSeries = (seriesName, releaseDate) => `The ${seriesName} series was released in ${releaseDate}`
// call the function
console.log(getNetflixSeries('Bridgerton', '2020') )
// output: The Bridgerton series was released in 2020
With just one parameter:
const favoriteSeries = seriesName => seriesName === "Bridgerton" ? "Let's watch it" : "Let's go out"
// call the function
console.log(favoriteSeries("Bridgerton"))
// output: "Let's watch it"
--------
// with parentheses: correct
const bestNetflixSeries = (seriesName = "Bridgerton") => `${seriesName} is the best`
// outputs: "Bridgerton is the best"
console.log(bestNetflixSeries())
// no parentheses: error
const bestNetflixSeries = seriesName = "Bridgerton" => `${seriesName} is the best`
// Uncaught SyntaxError: invalid arrow-function arguments (parentheses around the arrow-function may help)
--------------------------
const greeter = greeting => name => `${greeting}, ${name}!`
What’s going on there? Try using the regular function syntax:
function greeter(greeting) {
return function(name) {
return `${greeting}, ${name}!`
}
}