This:
const myFn = () => item.id === currentTask.id
Is the same as this:
function myFn() {
return item.id === currentTask.id;
}
And, for completeness, is the same as this:
const myFn = () => {
return item.id === currentTask.id;
}
If the return value of an arrow function is a single expression, you can elide the curly brackets and the return
keyword.
This is useful because one of the main usecases for arrow functions is callbacks. Making callbacks less verbose to write is very nice.
Compare this:
const dataArrIndex = taskData.findIndex((item)=>
item.id ===currentTask.id
)
With how it would have been written before arrow functions were a thing:
const dataArrIndex = taskData.findIndex(function (item) {
return item.id === currentTask.id;
})
It’s a small thing, but when you have to type this stuff over and over and over again it’s nice to not have to have that extra crap to write.
This:
const myFn = () => {
item.id === currentTask.id
}
Is the same as this:
function myFn() {
item.id === currentTask.id
}
Neither of these functions actually return anything, so this isn’t a very good example; this isn’t actually what you want.
Sometimes you don’t want to return anything.
const myFn = () => {
console.log("just logging to the console!");
}
Or you’ve got more than one expression. ie you can’t just return a value straightaway, you need do some other stuff to get to that point.
const myFn = () => {
if (isValid(item) && isValid(currentTask) {
return item.id === currentTask.id;
} else {
return false;
}
}
In those cases, you’ll want the brackets.
Just for completeness, say you want to directly return an object from an arrow function.
Objects also use curly brackets. If you write this:
const myFn = () => { id: 1 }
It’s not going to work, because what you’d have written is the same as this:
function myFn() {
return id: 1
}
Which makes no sense.
The JS interpreter will always treat a curly brace after the arrow in an arrow function (=> {
) as the opening brace of a function body.
So in that case, to make sure the JS interpreter knows you want to return an object, wrap it in brackets:
const myFn = () => ({ id: 1 })
Which is the same as:
function myFn() {
return { id: 1 }
}