7

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.

Community
  • 1
  • 1
Andrew Allbright
  • 3,721
  • 3
  • 20
  • 23
  • The value is knowing that all known paths out of the method will return something. It is a safety check. – epascarello Mar 24 '16 at 19:46
  • @epascarello Thanks for taking the time to leave a comment! Here's where I'm confused with your answer, though. Javascript compiler already always add "return undefined" if you don't specify. How does explicitly writing this improve the codebase? – Andrew Allbright Mar 24 '16 at 19:52

1 Answers1

4

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

georg
  • 211,518
  • 52
  • 313
  • 390