4

When lsEstimator is an array with 2 elements, this function returns true:

function got_estimators() {
  var retval = 
   (typeof lsEstimator != 'undefined' &&
    lsEstimator != null &&
   lsEstimator.length > 0);
  return retval;
}

but this function doesn't (it returns undefined, I think, in Chrome and FF):

function got_estimators() {
   return 
      (typeof lsEstimator != 'undefined' &&
      lsEstimator != null &&
      lsEstimator.length > 0);
}

Why?

EML
  • 8,369
  • 6
  • 37
  • 72

1 Answers1

17

Because of the line break after return in the second example. The code is evaluated as:

function got_estimators() {
   return; // <-- bare return statement always results in `undefined`.
   (typeof lsEstimator != 'undefined' &&
    lsEstimator != null &&
    lsEstimator.length > 0);
}

JavaScript is not even evaluating the logical operators.

Why does this happen? Because JavaScript has automatic semicolon insertion, i.e. it tries to insert semicolons "where it makes sense" (more information here).

Put the return keyword and the return value in the same line:

return (typeof lsEstimator != 'undefined' &&
  lsEstimator != null &&
  lsEstimator.length > 0);
Community
  • 1
  • 1
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
  • The one and only reason for putting curly braces on the statement line ! – jAndy Mar 12 '13 at 12:51
  • That's pretty amazing. Just found Crockford's JavaScript 'awful parts' at http://oreilly.com/javascript/excerpts/javascript-good-parts/awful-parts.html, and this comes in at No. 3. – EML Mar 12 '13 at 13:15