Fixing 'consistent-return' linter issue with simple arrow function

As title, I have an arrow function with the error. How can I refactor it so the error goes away?

Expected to return a value at the end of arrow function consistent-return

This is my code:

// Disable default form submission when user hits enter.
const $facetInput = $('.facet-input');
const $submitButton = $('.facet-submit');

$facetInput.on('keydown', (event) => {
  if ((event.key === 'enter' || event.keyCode === 13) && event.target !== $submitButton) {
    event.preventDefault();
    return false;
  }
});

Thanks!

35 thoughts on “Fixing 'consistent-return' linter issue with simple arrow function”

  1. By always explicitly returning a value under all code branches:

    $facetInput.on('keydown', (event) => {
      if ((event.key === 'enter' || event.keyCode === 13) && event.target !== $submitButton) {
        event.preventDefault();
        return false;
      }
      return <something else>; // false, true, 'whatever' - up to you
    });
    

    Assuming this is eslint (but really regardless of the linter), there is an implicit return undefined if your if (condition) does not evaluate to true.

    One of the confusing aspects of JavaScript is that any function may or may not return a value at any point in time. When a function exits without any return statement executing, the function returns undefined. Similarly, calling return without specifying any value will cause the function to return undefined. Only when return is called with a value is there a change in the function’s return value.

    Reply

Leave a Comment