Error unnecessary else after return no else return

A pluggable and configurable linter tool for identifying and reporting on patterns in JavaScript. Maintain your code quality with ease.

Disallow else blocks after return statements in if statements

🔧 Fixable

Some problems reported by this rule are automatically fixable by the --fix command line option

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

function foo() {
    if (x) {
        return y;
    } else {
        return z;
    }
}

Rule Details

This rule is aimed at highlighting an unnecessary block of code following an if containing a return statement. As such, it will warn when it encounters an else following a chain of ifs, all of them containing a return statement.

Options

This rule has an object option:

  • allowElseIf: true (default) allows else if blocks after a return
  • allowElseIf: false disallows else if blocks after a return

allowElseIf: true

Examples of incorrect code for this rule:

/*eslint no-else-return: "error"*/

function foo() {
    if (x) {
        return y;
    } else {
        return z;
    }
}

function foo() {
    if (x) {
        return y;
    } else if (z) {
        return w;
    } else {
        return t;
    }
}

function foo() {
    if (x) {
        return y;
    } else {
        var t = "foo";
    }

    return t;
}

function foo() {
    if (error) {
        return 'It failed';
    } else {
        if (loading) {
            return "It's still loading";
        }
    }
}

// Two warnings for nested occurrences
function foo() {
    if (x) {
        if (y) {
            return y;
        } else {
            return x;
        }
    } else {
        return z;
    }
}

Examples of correct code for this rule:

/*eslint no-else-return: "error"*/

function foo() {
    if (x) {
        return y;
    }

    return z;
}

function foo() {
    if (x) {
        return y;
    } else if (z) {
        var t = "foo";
    } else {
        return w;
    }
}

function foo() {
    if (x) {
        if (z) {
            return y;
        }
    } else {
        return z;
    }
}

function foo() {
    if (error) {
        return 'It failed';
    } else if (loading) {
        return "It's still loading";
    }
}

allowElseIf: false

Examples of incorrect code for this rule:

/*eslint no-else-return: ["error", {allowElseIf: false}]*/

function foo() {
    if (error) {
        return 'It failed';
    } else if (loading) {
        return "It's still loading";
    }
}

Examples of correct code for this rule:

/*eslint no-else-return: ["error", {allowElseIf: false}]*/

function foo() {
    if (error) {
        return 'It failed';
    }

    if (loading) {
        return "It's still loading";
    }
}

Version

This rule was introduced in ESLint v0.0.9.

Resources

  • Rule source
  • Tests source

Содержание

  1. Name already in use
  2. jslint-error-explanations / message-articles / unnecessary-else.md
  3. Else after return: yea or nay?
  4. The problem #
  5. Guard clauses #
  6. Symmetric conditions #
  7. Conclusion #
  8. Ненужное «else» после «return». (Нет возврата)
  9. Error unnecessary else after return no else return
  10. When do I get this error?
  11. Why do I get this error?
  12. About the author
  13. “No-else-after-return” considered harmful

Name already in use

jslint-error-explanations / message-articles / unnecessary-else.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

This warning has existed in two forms in JSLint and ESLint. It was introduced in the original version of JSLint and has remained in both tools ever since. It is not present in JSHint.

In JSLint versions dated later than April 2013 the warning given is «Unnecessary ‘else’ after disruption»

In older versions of JSLint and in all versions of ESLint the message used is «Unexpected ‘else’ after ‘return’»

The situations that produce the warning have not changed despite changes to the text of the warning itself.

When do I get this error?

The «Unnecessary ‘else’ after disruption» error (and the alternative «Unexpected ‘else’ after ‘return’» error) is thrown when JSLint or ESLint encounters an else block following an if block that contains a disruptive statement such as return or throw . Here’s some example code:

ESLint will only raise this error when it encounters a return statement and not a throw statement:

Why do I get this error?

This error is raised to highlight a completely pointless piece of code. If execution enters the if block, the flow of execution will be disrupted (it could for example return or throw an exception). There will be no way execution can enter the else block. Therefore, you can simply omit the else block and place its contents directly after the if block. Here’s the above snippet again, without the error:

In ESLint the rule that generates this warning is named no-else-return . You can disable it by setting it to 0 , or enable it by setting it to 1 .

Источник

Else after return: yea or nay?

As you may know, I use pylint for most of my Python projects.

A few weeks ago, I upgraded pylint and a new warning appeared. This tends to happen when you have a pretty large code base: new checks are added to pylint all the time, so new warnings are bound to show up.

Here’s a minimal example of the kind of code that triggered the new warning:

Indeed, the code after the first return will never execute if bar is true, so there’s no need for the else .

In other words, the code should be written like this:

Well, the code is shorter. But is it better?

The problem #

If you think about it, the question about whether the code is better in the first form (let’s call it explicit else) or in the second form (let’s call it implicit else) is hard to answer because you have no clue about the meaning of the foo function, or the bar , baz and qux variables.

So let’s try to come up with better examples.

Guard clauses #

Sometimes you’ll find code written this way:

In other words, you are trying to do something but that’s only possible if a condition is true. If the condition is false, you need to display an error.

The else is explicit here.

The version with an implicit else looks like this:

So far, it’s not very clear what version is better.

Note there’s a third way to write the same code, by using if not precondition() instead:

Now, watch what happens when we add several preconditions:

I hope you’ll agree the second version is better.

There’s one less level of indentation, and the line that displays the error is right after the line that checks for the error.

Clear win for the implicit else here.

Symmetric conditions #

Let’s take an other example.

Suppose you are writing a script that will check all the links in documentation written as a set of HTML pages.

You’ve got a list of all the possible pages, and then you need to check both internal links (with a href looking like ../other-page ) and external links like (with a href like http://example.com ).

Let’s take a look at the two variants:

This time, I hope you’ll agree the explicit else is better.

There are two things to be done, and visually they are at them at the same level of indentation.

The symmetry between the type of the link and the check that needs to be done is preserved.

We could say that the algorithm I’ve described as text in the last paragraph is better expressed in the second version.

Conclusion #

Pylint is a great tool, but be careful before deciding whether you want to follow its refactoring pieces of advice.

Second, make sure your code is easy to read and reveal your intention. Conciseness is not the only factor here.

Last, be careful with code samples that are too abstract 🙂

Thanks for reading this far 🙂

I’d love to hear what you have to say, so please feel free to leave a comment below, or read the contact page for more ways to get in touch with me.

Источник

Ненужное «else» после «return». (Нет возврата)

Я использую es-lint для устранения ошибок в моем коде. Я столкнулся с этой ошибкой:

Unnecessary ‘else’ after ‘return’. (No-else-return)

Я всегда использовал операторы else после возврата. Могу я что-то упустить?

По сути, это означает, что часть else оператора if не нужна, если return в этой if части есть a . Примерно это то, что он ожидает:

После оператора if with return нет необходимости в else части, так как код ниже if будет запускаться только в том случае, если указанное условие не выполняется.

Это предпочтение стиля кода. Вам не нужен, else и вместо этого вы можете поместить else код непосредственно под if . Это потому, что в случае if успеха это конец функции, поэтому else код в любом случае не будет достигнут.

Этот стиль, кажется, различается в разных сообществах программистов. Разработчики Go почти всегда пропускают else , хотя я видел, как другие разработчики JS включают его.

Хотя я предпочитаю не использовать else , это опять же чисто вопрос предпочтений. Не позволяйте этому слишком вас беспокоить. Люди могут относиться к подобным вещам категорично, но на самом деле это не так уж важно.

Хотя правило правильно указывает, что else блок не нужен, и это предпочтение стиля, я бы добавил дополнительные соображения для удобочитаемости и, что наиболее важно, возможности сканирования .

Для разработчика, пишущего этот код, и для машины, интерпретирующей его, это может быть точка стиля, и все. Но для разработчика, которому нужно исправить ошибку, улучшить функцию, выполнить обзор кода и т. Д., Возможность быстро сканировать код и видеть else блоки помогает идентифицировать ветви логики.

В нескольких строках изолированного кода легко увидеть намерение, но среди сотен строк кода if else блоки могут служить полезными идентификаторами, как и другие распространенные визуальные практики, такие как отступы, разрывы строк и соглашения об именах.

Источник

Error unnecessary else after return no else return

This warning has existed in two forms in JSLint and ESLint. It was introduced in the original version of JSLint and has remained in both tools ever since. It is not present in JSHint.

In JSLint versions dated later than April 2013 the warning given is «Unnecessary ‘else’ after disruption»

In older versions of JSLint and in all versions of ESLint the message used is «Unexpected ‘else’ after ‘return’»

The situations that produce the warning have not changed despite changes to the text of the warning itself.

When do I get this error?

The «Unnecessary ‘else’ after disruption» error (and the alternative «Unexpected ‘else’ after ‘return’» error) is thrown when JSLint or ESLint encounters an else block following an if block that contains a disruptive statement such as return or throw . Here’s some example code:

ESLint will only raise this error when it encounters a return statement and not a throw statement:

Why do I get this error?

This error is raised to highlight a completely pointless piece of code. If execution enters the if block, the flow of execution will be disrupted (it could for example return or throw an exception). There will be no way execution can enter the else block. Therefore, you can simply omit the else block and place its contents directly after the if block. Here’s the above snippet again, without the error:

In ESLint the rule that generates this warning is named no-else-return . You can disable it by setting it to 0 , or enable it by setting it to 1 .

This article was written by James Allardice, Software engineer at Tesco and orangejellyfish in London. Passionate about React, Node and writing clean and maintainable JavaScript. Uses linters (currently ESLint) every day to help achieve this.

This project is supported by orangejellyfish, a London-based consultancy with a passion for JavaScript. All article content is available on GitHub under the Creative Commons Attribution-ShareAlike 3.0 Unported licence.

Have you found this site useful?

Please consider donating to help us continue writing and improving these articles.

Источник

“No-else-after-return” considered harmful

(Update below)

At the time of writing this, the Mozilla Coding Style guidelines have this recommendation under “General C/C++ Practices”:

Don’t put an else right after a return. Delete the else, it’s unnecessary and increases indentation level.

I can appreciate this in some circumstances, such as when checking for an error case early in a long function:

But as a blanket guideline I think it’s misguided because it promotes an impure style of programming. And by “impure” here I mean the opposite of “pure” in this sense, i.e. “free from side-effects and other such error-prone junk”. Let’s consider a simple example: the max() function. Here’s a way to write it that is quite sensible, in my opinion:

But this violates the no-else-after-return guideline. The Mozilla way to write this is like so:

(I’m not exaggerating, see this comment and this comment from Mozilla’s VP of Engineering and CTO respectively, about an example very similar to this.)

Urk. That’s horrible. Any time you’re using an ‘if’ without a corresponding ‘else’, you’re relying on an impure feature — you must be doing something with a side-effect in the ‘then’ branch, or some kind of impure control flow. Mozilla’s coding guidelines insist that we write max(), a pure function, in an impure way. Also, it’s just harder to read because the two return statements have different indentation levels despite the fact that they are closely related.

In this case there’s a way around the problem:

Even though C’s if-then-else expression syntax is awful, it’s a better way to do it.

In general, statements suck, expressions rule. Even in a language like C/C++ you can do something approaching functional programming by avoiding statements where possible. In a tiny example like max() the difference may seem trivial, but in bigger examples the difference becomes more important. Consider the following code from Nanojit’s register allocator which picks a register by looking at the free registers, the registers that are allowed to be used, and possibly the preferred registers. You don’t have to understand it closely, but it helps to know that RegisterMask is just a bitfield with one bit per register.

I find this code incredibly hard to understand. There are three ‘ifs’ that lack ‘elses’, so it relies heavily on state updates to do its work. In fact, in order to understand it, I ended up rewriting it in a more pure style, by using a sequence of small refactorings:

There’s now only a single ‘if’ lacking an ‘else’, and it turns out even that can be removed by putting the “… more code here …” part into an else branch, and then the ‘return r;’ can be moved to the end of the function.

The code is now comprehensible — it picks a register that is free and allowed, and preferred as well if possible.

Part of the art of programming involves knowing when to avoid using a language feature. Everybody knows that ‘goto’ is occasionally highly useful, but should be avoided whenever something less dangerous (a for-loop, a while-loop, a ‘break’ statement) can be used. And everybody knows it because everybody is taught it. But programmers aren’t taught to avoid unnecessary side-effects… at least, I wasn’t, certainly not via examples such as those I’ve given above. I’ve only come to realise these things as I’ve switched several times between using C/C++ and some pure functional languages over the years, and come to appreciate how purity helps make programs more readable and less error-prone.

To come full circle, I’d like to see the no-else-after-return guideline removed from the Mozilla style guide, or at the very least, be qualified in a way that allows the cases I’ve argued for. I’d also love to see a guideline (with examples) added such as “prefer expressions to statements”.

Update:

(The arguments had the wrong names in the initial post, I’ve fixed them now.)

All three versions of max() are pure, because it’s possible to combine impure pieces of code (such as an else-less if) into a pure piece of code. So I’ll augment my recommendation: pure code is preferable, and furthermore, given that C/C++ makes it so easy to write impure code, it’s preferable that pure code be obviously pure. I argue that the 3rd version of max() with the ?: operator is the most obviously pure, because a ?: is pure if its operands are pure. In comparison, it’s harder to tell if an if-then-else is pure (although this case is still pretty easy thanks to the matching return statements). And an if-without-else almost never results in pure code; the max() example above is a rare exception.

I also omitted a fourth formulation of max:

For this very simple case, such a formulation is overkill. But if the ‘then’ and ‘else’ cases are more complicated it makes more sense. (Furthermore, much of this discussion should be thought of in more complex cases, as these kinds of small decision can make a bigger difference then.) This version also doesn’t violate the no-else-after-return rule. So perhaps that rule isn’t as bad as I thought, if only because it’s easier to work around than I thought… but I still think rewriting the 1st version of max() into the 2nd version is a bad idea.

Источник

Николай Тюнис

Здравствуйте, моя программа работает, но проверка ее почему-то не принимает.

// removed

И не пойму ошибку в линтере

24:10  error  Unnecessary 'else' after 'return'  no-else-return

✖ 1 problem (1 error, 0 warnings)
1 error and 0 warnings potentially fixable with the --fix option.


6


0

Nikita Mikhaylov

Добрый вечер. Покажите вывод тестов. Из них станет понятно, на каком именно значении ваша программа отрабатывает не так, как следует.

По поводу линтера: он говорит, что не стоит использовать конструкцию

if (….) {
return ….
} else {
return ….
}

В этом нет особо смысла, так как вы используете return до этого, а значит при выполнении условий выше return внутри else никогда не сработает, так что не опасаясь можно вынести этот return за блок else. То есть код будет выглядеть так:

if (…) {
return …
}

return ….

Подробнее можете почитать тут: https://eslint.org/docs/rules/no-else-return


1

Николай Тюнис

Вывод тестов:

status:finished → Code has been running for too long. Infinite loop or recursion. Check terminating conditions.

если убрать условие:

else if (str === ») {
return »;
}

то вывод тестов будет таким:

Expected: «»
Received: null

Difference:

  Comparing two different types of values. Expected string but received null.

  4 |   expect(dnaToRna('ACGTGGTCTTAA')).toBe('UGCACCAGAAUU');
  5 |   expect(dnaToRna('CCGTA')).toBe('GGCAU');
> 6 |   expect(dnaToRna('')).toBe('');
    |                        ^
  7 |   expect(dnaToRna('ACNTG')).toBeNull();
  8 | });


0

Nikita Mikhaylov

Обратите внимание на следующий 7 тест. Именно при нём ваш код уйдёт в бесконечный цикл. Попробуйте расписать на листочке все действия, которые будут, если на вход вашей программе передать строку ACNTG

А тот else, который был пока оставьте. С ошибками линтера советую поработать уже после прохождения тестов


1

Николай Тюнис

Понял, благодарю, буду разбираться.


0

Сергей К.

Николай, как успехи?


0

Николай Тюнис

Все работает! поместил условие при котором выдает null внутрь цикла:

// removed


0

Introduction #

As you may know, I use pylint for most of my Python projects.

A few weeks ago, I upgraded pylint and a new warning appeared. This tends to happen when you have a pretty large code base: new checks are added to pylint all the time, so new warnings are bound to show up.

Here’s a minimal example of the kind of code that triggered the new warning:

def foo():
    if bar:
        return baz
    else:
        return qux
$ pylint foo.py
...
Unnecessary "else" after "return" (no-else-return)

Indeed, the code after the first return will never execute if bar is true, so there’s no need for the else.

In other words, the code should be written like this:

def foo():
    if bar:
        return baz
    return qux

Well, the code is shorter. But is it better?

The problem #

If you think about it, the question about whether the code is better in the first form (let’s call it explicit else) or in the second form (let’s call it implicit else) is hard to answer because you have no clue about the meaning of the foo function, or the bar, baz and qux variables.

So let’s try to come up with better examples.

Guard clauses #

Sometimes you’ll find code written this way:

def try_something():
    if precondition():
         result = compute_something()
         return result
    else:
        display_error()
        return None

In other words, you are trying to do something but that’s only possible if a condition is true. If the condition is false, you need to display an error.

The else is explicit here.

The version with an implicit else looks like this:

def try_something():
    if precondition():
         result = compute_something()
         return result
    display_error()
    return None

So far, it’s not very clear what version is better.

Note there’s a third way to write the same code, by using if not precondition() instead:

# Implicit else, inverted condition
def try_something():
    if not precondition():
        display_error()
        return None

    result = compute_something()
    return result

Now, watch what happens when we add several preconditions:

# Explicit else
def try_something():
    if precondition_one():
        if precondition_two():
            result = compute_something()
            return result
        else:
            display_error_two()
            return
    else:
        display_error_one()
# Implicit else, inverted condition
def try_something():

    if not precondition_one():
        display_error_one()
        return

    if not precondition_two():
        display_error_two()
        return

    result = compute_something()
    return result

I hope you’ll agree the second version is better.

There’s one less level of indentation, and the line that displays the error is right after the line that checks for the error.

Clear win for the implicit else here.

Symmetric conditions #

Let’s take an other example.

Suppose you are writing a script that will check all the links in documentation written as a set of HTML pages.

You’ve got a list of all the possible pages, and then you need to check both internal links (with a href looking like
../other-page) and external links like (with a href like http://example.com).

Let’s take a look at the two variants:

# Implicit else
def check_link(link) -> bool:
    if is_internal_link(link):
        return check_internal_link(link)
    return check_external_link(link)
# Explicit else
def check_link(link) -> bool:
    if is_internal_link(link):
        return check_internal_link(link)
    else:
        return check_external_link(link)

This time, I hope you’ll agree the explicit else is better.

There are two things to be done, and visually they are at them at the same level of indentation.

The symmetry between the type of the link and the check that needs to be done is preserved.

We could say that the algorithm I’ve described as text in the last paragraph is better expressed in the second version.

Conclusion #

Pylint is a great tool, but be careful before deciding whether you want to follow its refactoring pieces of advice.

Second, make sure your code is easy to read and reveal your intention. Conciseness is not the only factor here.

Last, be careful with code samples that are too abstract :)

Cheers!


Thanks for reading this far :)

I’d love to hear what you have to say, so please feel free to leave a comment below, or
read the contact page

for more ways to get in touch with me.

Note that to get notified when new articles are published, you can either:

  • Subscribe to the RSS feed or
    the newsletter
  • Or follow me on
    Mastodon,
    dev.to, or
    twitter.

Cheers!

Disallow else blocks after return statements in if statements

🛠 Fixable

Some problems reported by this rule are automatically fixable by the --fix command line option

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

function foo() {
if (x) {
return y;
} else {
return z;
}
}

Rule Details

This rule is aimed at highlighting an unnecessary block of code following an if containing a return statement. As such, it will warn when it encounters an else following a chain of ifs, all of them containing a return statement.

Options

This rule has an object option:

  • allowElseIf: true (default) allows else if blocks after a return
  • allowElseIf: false disallows else if blocks after a return

allowElseIf: true

Examples of incorrect code for this rule:

/*eslint no-else-return: "error"*/

function foo() {
if (x) {
return y;
} else {
return z;
}
}

function foo() {
if (x) {
return y;
} else if (z) {
return w;
} else {
return t;
}
}

function foo() {
if (x) {
return y;
} else {
var t = "foo";
}

return t;
}

function foo() {
if (error) {
return 'It failed';
} else {
if (loading) {
return "It's still loading";
}
}
}

// Two warnings for nested occurrences
function foo() {
if (x) {
if (y) {
return y;
} else {
return x;
}
} else {
return z;
}
}

Examples of correct code for this rule:

/*eslint no-else-return: "error"*/

function foo() {
if (x) {
return y;
}

return z;
}

function foo() {
if (x) {
return y;
} else if (z) {
var t = "foo";
} else {
return w;
}
}

function foo() {
if (x) {
if (z) {
return y;
}
} else {
return z;
}
}

function foo() {
if (error) {
return 'It failed';
} else if (loading) {
return "It's still loading";
}
}

allowElseIf: false

Examples of incorrect code for this rule:

/*eslint no-else-return: ["error", {allowElseIf: false}]*/

function foo() {
if (error) {
return 'It failed';
} else if (loading) {
return "It's still loading";
}
}

Examples of correct code for this rule:

/*eslint no-else-return: ["error", {allowElseIf: false}]*/

function foo() {
if (error) {
return 'It failed';
}

if (loading) {
return "It's still loading";
}
}

Version

This rule was introduced in ESLint v0.0.9.

Resources

  • Rule source
  • Tests source

Понравилась статья? Поделить с друзьями:
  • Error unmounting dev sda1 target is busy udisks error quark 14
  • Error unmounting dev nvme0n1p3
  • Error unmarshalling return nested exception is
  • Error unmarshaling return header nested exception is
  • Error unmarshaling json