Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are these two JS functions different?

Tags:

javascript

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?

like image 375
EML Avatar asked Dec 03 '22 00:12

EML


1 Answers

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);
like image 69
Felix Kling Avatar answered Dec 14 '22 22:12

Felix Kling