0

I'm trying call a function, from a module, to build a HTML string. When the function is written in the below way, with a LF(Line Feed) between the return statement and the string declaration, the return is "undefined"...

exports.buildHtmlContent = function (content) {
    return
    "<!DOCTYPE html>                    \
    \n<html lang='en-US'>               \
    \n  <head>                          \
    \n  </head>                         \
    \n  <body>                          \
    \n      <h1>" + content + "</h1>    \
    \n  </body>                         \
    \n</html>";
};

However, when the function is written in this other below way, without the LF after return statement, it works properly!

exports.buildHtmlContent = function (content) {
    return "<!DOCTYPE html>             \
    \n<html lang='en-US'>               \
    \n  <head>                          \
    \n  </head>                         \
    \n  <body>                          \
    \n      <h1>" + content + "</h1>    \
    \n  </body>                         \
    \n</html>";
};

This is a bug in NodeJs? The NodeJs interpretation from the function 1 looks like it thinks the return is empty, even with the miss of ";", and didn't correlate the below string declaration with the return statement. Apparently NodeJs didn't check the miss of ";" before decide that is the interpretation end of the "return" statement.

Nipo
  • 131
  • 1
  • 9

1 Answers1

3

This has to do with JavaScript, and not Node.js specifically. Most JavaScript engines implement Automatic Semi-colon Insertion, meaning that it will try to automatically separate two clauses with a semi-colon. The statement return on its own is valid, as it will return undefined, and a string is a valid statement as well. For example:

"use strict";

The reason why ASI is triggered is due to both the line break, and return being a restricted production. Not a bug, but a feature.

0x8890
  • 425
  • 3
  • 11
  • Note: It's due to `return` statements being [restricted productions](http://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi) -- the few statements in JavaScript that limit the use of line-breaks. Other than these, ASI isn't so aggressive as to insert a semicolon with every line-break. – Jonathan Lonowski Oct 25 '14 at 20:10
  • Thanks for the clarification, edited my answer. – 0x8890 Oct 25 '14 at 20:13