Many times when using Eslitn or other linting tools I was getting an error like this:
Err: // Expected to return a value at the end of arrow function
Does arrow functions always have to return a value? If the arrow function has to return a value, what's the reason for this?
For example, in this particular piece of code, I don't need to return anything if a condition is not passed. Anyway my linter yiels at me with the mentioned error.
const getCookie = name => {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length == 2)
return parts
.pop()
.split(';')
.shift();
};
No, (arrow) functions don't have to return anything but when function is not supposed to be void (i.e return value is expected), it's a good practice to return from every path/return some kind of default value if every other path fails.
const getCookie = name => {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length == 2) {
return parts
.pop()
.split(';')
.shift();
}
// default return, for example:
return false;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With