JonBlog
Thoughts on website ideas, PHP and other tech topics, plus going car-free
JavaScript gotcha: implicit semi-colon insertion
Categories: Technical

One of the ways in which my PHP coding style has evolved is the way in which long statements can be split over several lines. This takes advantage of the free-form nature of PHP, and saves the need to create intermediate variables that are only used once; it also encourages staying within reasonable character margins, so as to reduce the need for horizontal scrolling in an IDE. I suspect this approach been inspired by (or necessitated by!) using Propel, and recently more so after chainable Query objects were added in version 1.5.

However, this approach doesn’t operate quite so cleanly in JavaScript, as I discovered today. I thought I’d discovered a OSX/FF bug, but it turns out that this issue is uniform across all JS engines (that I tested, anyway). If there is a line break between a return statement and a return value, the engine returns the same (undefined) as if a return had been employed on its own.

<html>
  <head>
  <title>JS test</title>
  <script type="text/javascript">

  function getStringInline() {
    return 'This works';
  }

  /**
   * This fails, since the return value needs to be inline with the return
   *
   * Tested on Mac OSX/FF3.6.16
   * Tested on Mac OSX/Safari 5.0.4
   * Tested on WinXP/VirtualBox/Opera 11.01
   * Tested on WinXP/VirtualBox/Safari 5.0.4
   * Tested on WinXP/VirtualBox/IE8
   */
   function getStringFreeForm() {
   return
     'This fails';
   }

  // The free-form function comes back 'undefined'
  alert(
    getStringInline()
    + ', ' +
    getStringFreeForm()
  );

  </script>
</head>
<body>

</body>
</html>

Turns out that the engine is putting in a semicolon after the return statement because the statement would operate fine on its own – this is called implicit semicolon insertion. Thankfully JSLint catches this fine (note to self: must start using that properly).

A demo of this little gotcha can be found here.

Leave a Reply