DEV Community

Marko V
Marko V

Posted on • Updated on

consistent-return

In the spirit of either learning something new every day or sharing/teaching someone something new, and in line with the theme of these past few days... Linting.

The first question today was to resolve the "consistent-return" error.

This happens when you have this kind of pattern;

function myFunc(item) {
  if (booleanCheck) { 
    // do something
    return false;
  }
  // do something but not returning anything or returning void or anything but a boolean.
}
Enter fullscreen mode Exit fullscreen mode

So the first thing you have to make sure is, is there a consumer of myFunc somewhere in your code that is expecting that false return state and enacting on it? Depending on what you find. If there is a consumer that enacts on the return of the function, then make sure that the function always does return a value of the same type.

If you used the return as a way to exit the function, then change it to being an if-else statement instead or if you don't really need to do anything in the block that returned false before, you can inverse the if-check.

function myFunc(item) {
  if (booleanCheck) { 
    // do something but not continue with normal operations
  } else {
    // do something as per normal operations.
  }
}
Enter fullscreen mode Exit fullscreen mode

alternatively

function myFunc(item) {
  if (!booleanCheck) { 
    // do something as per normal operations.
  }
}
Enter fullscreen mode Exit fullscreen mode

See: https://eslint.org/docs/rules/consistent-return

Top comments (0)