Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

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

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...