Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the value proposition for ESLint's "consistent return" rule?

What's the value of always returning a value ("undefined") for functions don't need to explicitly return anything?

Why is this a rule and what bugs does it catch?


You can read about ESLint's "consistent return" rule here (answers the "what", not the "why").

You can read a speculative analysis of why javascript functions implicitly returns undefined here on stack overflow.

like image 305
Andrew Allbright Avatar asked Mar 24 '16 19:03

Andrew Allbright


People also ask

What is consistent return?

This rule requires return statements to either always or never specify values. This rule ignores function definitions where the name begins with an uppercase letter, because constructors (when invoked with the new operator) return the instantiated object implicitly if they do not return another object explicitly.


1 Answers

Some languages draw distinction between functions and procedures. This isn't the case in C-alikes, but it's still a good idea to design subroutines this way.

The linter doesn't want you to "always returning something". It just tells you that if you design a function (as opposed to a procedure), it has to return something meaningful in any case (ideally, all returned values must be of the same type).

Example:

function is_visible(object)

is a function, it should return a value (a boolean in this case) and can be used in expressions. On the other side

function make_visible(object)

is a procedure, it shouldn't return anything and cannot be used in expressions - it's always a statement.

Such a design (and the related linter warning) greatly helps to prevent bugs like this (taken from some random internet page):

enter image description here

like image 110
georg Avatar answered Oct 01 '22 00:10

georg