Tech Journal Back to Tech Journal

Why do I get Javascript warnings of the form "function does not always return a value"?

If you're like me, you may have thought this might be because all JavaScript functions are supposed to be functions in the Pascal-sense of the word, which means they must return a value. That's not quite what it says, does it? It's a warning that means that the function sometimes returns a value, and sometimes doesn't. This usually happens in cases like the following:

function example1() {
  if (some_condition) {
    return true;
  }
}
function example2() {
  if (some_condition) {
    return true;
  }
  return;
}

The two examples are actually identical from the compiler's point-of-view; when the programmer fails to explicitly tell the function when to return, it will return at the end of its definition (and in C compilers, the required assembly code is added to make this happen. I'm not sure how this works in JavaScript.)

The examples show that in some execution paths, the function will reach return true, but in others, will merely execute return. Which is exactly what the warning is trying to say! Namely, that sometimes the function will actually return some value, and other times it will encounter a non-value-returning return, and not return a value.

To fix this, make sure you functions either always return a value, or never return a value, and not a mix of both.

Last updated on 2008-03-20 02:26:44 -0700, by Shalom Craimer

Back to Tech Journal