Home > Software design >  Why the Unnecessary 'else' after 'return' (no-else-return) error
Why the Unnecessary 'else' after 'return' (no-else-return) error

Time:05-25

I always use the else statement. And the data from the Data.js file. Is there something I might have overlooked?

import data from './Data'

function List(props){
  const filteredData = data.filter((el) => {
    if (props.input === '') {
      return el
    } else {
      return el.text.tiLowerCase().includes(props.input)
    }
  })

CodePudding user response:

That's just what the rule requires.

Disallows return before else.

If an if block contains a return statement, the else block becomes unnecessary. Its contents can be placed outside of the block.

If you think this rule is worth following, use instead (with correct spelling)

const filteredData = data.filter((el) => {
    if (props.input === '') {
        return el
    }
    return el.text.toLowerCase().includes(props.input)
})

or even better

const filteredData = data.filter((el) => {
    return props.input === ''
        ? el
        : el.text.toLowerCase().includes(props.input)
})

If el will alwys be truthy, then it would make more sense to return true instead.

const filteredData = data.filter((el) => {
    return props.input === ''
        ? true
        : el.text.toLowerCase().includes(props.input)
})

which allows for the simplification to

const filteredData = data.filter((el) => {
    return props.input === '' || !el.text.toLowerCase().includes(props.input)
})
  • Related