Arrow Functions
If you have been reading fetch code online, you have probably seen => and wondered what it is. That is an arrow function. It is just a shorter way to write a regular function.
The regular way
You already know how to write a function:
function double(n) {
return n * 2
}
double(5) // 10
The arrow way
Arrow functions do the same thing with less writing:
const double = (n) => n * 2
double(5) // 10
What changed:
- No
functionkeyword =>sits between the parameters and the body- If the body is a single expression, you skip the curly braces and
return- the result is returned automatically
Both versions of double work exactly the same. Arrow functions are not a different kind of function. They are just shorter to write.
When you need curly braces
If the function body has more than one line, you still need {} and return:
const greet = (name) => {
let message = "Hello " + name
return message
}
greet("Alice") // "Hello Alice"
Single line - no braces needed. Multiple lines - braces required.
One parameter vs many
// one parameter - brackets around it are optional
const square = n => n * n
// two parameters - brackets are required
const add = (a, b) => a + b
// no parameters - empty brackets required
const sayHello = () => "Hello!"
Where you will see this in fetch code
Arrow functions show up constantly inside .then(). Here is the same fetch call written both ways:
// regular function style
fetch("/patients")
.then(function(response) {
return response.json()
})
.then(function(patients) {
console.log(patients)
})
// arrow function style
fetch("/patients")
.then(response => response.json())
.then(patients => console.log(patients))
The arrow version is shorter and easier to scan. Both do exactly the same thing.
Challenge
Rewrite these three functions as arrow functions:
function triple(n) {
return n * 3
}
function fullName(first, last) {
return first + " " + last
}
function shout(text) {
return text.toUpperCase() + "!"
}
Test each one by calling it with a value and logging the result.