Javascript function fails to return object when there is a line-break between the return statement and the object?

tl;dr The line break is causing the ‘undefined’ in the second function. JavaScript doesn’t require semicolons in a lot of cases and just assumes them in certain contexts (Automatic Semicolon Insertion).


In certain cases, to avoid this ASI problem and for aesthetic reasons, I use the so-called grouping operator. For example, with the hoquet templating DSL (it compiles Arrays as s-expressions into HTML), I like to group the Arrays so that they clearly show the HTML structure:

return (
  ["ul"
  , ["li"
    , ["span", {class: "name"}, this.name]
    , ["span", {id: "x"}, "x"]
    ]
  ]
);

which seems somewhat clearer, or more consistent to me than

return [
  "ul",
  [
    "li",
    ["span", {class: "name"}, this.name],
    ["span", {id: "x"}, "x"]
  ]
];

and they end up with the same number of lines. But it’s a matter of aesthetics, really.


The grouping operator just evaluates whatever expression is inside of it. You see this commonly with Immediately Invoked Function Expressions, where you need to turn what would normally be a function declaration into an expression, which can then be immediately invoked (hence, the name). However, a perhaps lesser known feature of the grouping operator is that it can also take a comma-delimited list of expressions, e.g.

function() {
  return (
    doSideEffects(),
    console.log("this is the second side effect"),
    1 + 1
  );
}

In this case it evaluates each of these expressions and returns only the last one (1 + 1).

Leave a Comment