42

Here is the jsfiddle

The full code:

function foo1(){
    return {msg: "hello1"};
}
function foo2(){
    return
    {msg: "hello2"};
}

// output = "foo1 =  {"msg":"hello1"}"
console.log('foo1 = ' , JSON.stringify(foo1())); 

//output = " foo2 =  undefined "
console.log('foo2 = ' , JSON.stringify(foo2()));

The difference between the two is that in foo2, the {msg: 'hello'} is in its own new line. I was expecting the parser to ignore whitespaces?

4

2 回答 2

41

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).

于 2013-08-14T01:51:05.743 回答
1

Accepted Answer seems to be correct.

However I found this variant of a return line with line break at a function arg opening bracket DOES work:

myFunction(){
  return myOtherFucntion(
           myArg);
}

And this other variant with line break before '.' dot operator ALSO works:

myFunction(){
  return myObject
           .myObjectFunction();
}

(The style/readability of my examples are obviously a bit odd, but try to just pay attention to the conclusions they make, and exercise your own style as you find appropriate).

于 2018-05-31T23:40:11.310 回答