3

If I have a javascript function, it is possible that I do not return a value from every code path, e.g:

function f()
{
  if (checkSomething())
  {
    return 42;
  }
  // no return statement here
}

Is this valid javascript or does it only work by chance (i.e. might there be problems when run in some browsers)?

M4N
  • 94,805
  • 45
  • 217
  • 260

3 Answers3

12

Yes, it is valid javascript. If checkSomething() evaluates to false, it will return undefined.

See http://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope for more details.

Althought, you should note that returning different types of data (In this case, an integer or undefined) is bad practice.

slaphappy
  • 6,894
  • 3
  • 34
  • 59
3

Since Javascript is a loose language compared to compiled ones, you can get away with things that most compiled languages will not allow. So yes, it can be done, it's just a matter of whether you want to do something like this. If you were to try to compile this code in a language such as C# or similar, the compiler would generate an error.

I am not trying to critique your code, just offering a suggestion on good design. Functions are intended to return values on all code paths and it is up to the calling code to check that return value and decide what to do. You could check the return value for undefined or whatever it is when checkSomething() returns false or you could set the value to something more meaningful that the calling code can check upon return. You may have return values that mean certain things to the caller. -1 means one thing, -2 means something else.

Hope this helps.

Moebius
  • 700
  • 7
  • 25
  • I agree that it's not good design (this was obvious to me, so it wasn't the question). – M4N Jul 25 '11 at 18:41
  • If my answer came off as condescending, I apologize. My intention was to help out any less experienced coders that may come across this post and need a little more background. – Moebius Jul 26 '11 at 14:05
2

This JavaScript will work, just keep in mind that if you try to read the return value of f it will be set to undefined if no return statement is executed.

Personally I think this code is a little weird. If you are going to return from one code path, I suggest returning from all other possible code paths as well. That way someone reading and working with your code knows exactly what to expect.

Justin Ethier
  • 131,333
  • 52
  • 229
  • 284