Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the arrow function have to always return a value?

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();
};
like image 662
p7adams Avatar asked Oct 16 '25 13:10

p7adams


1 Answers

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;
};
like image 61
Solo Avatar answered Oct 19 '25 07:10

Solo