Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - explanation request of a behaviour [duplicate]

Tags:

javascript

I witnessed this behaviour from JavaScript which I found interesting, but I don't know how to search for the reason of it so I have the following question.

As far as I know multi-line statements work in JavaScript, for example:

var text = "abc" + 
"xyz";

But when it is this:

// returns undefined
return 
"some text";

Noo! It returns undefined.
This is a basic statement which should return a string. But this version doesn't work as I expect.

So what are we experiencing here? I am just curious.

like image 380
Tolga Evcimen Avatar asked Dec 25 '22 00:12

Tolga Evcimen


2 Answers

The problem is the horror that is automatic semicolon insertion. JavaScript's rules for ASI will insert a ; after the return, giving you this:

return;
"some text";

That seems odd, but it's valid — it does a return with no value, and so the function call returns undefined, and then there's an expression lying around at the end of the function (which is valid, but does nothing).

You can fix it by doing what you did (putting it all on one line), which is what I'd recommend, or changing it so that the ASI rules won't kick in, for instance by using parens:

return (
    "some text"
);

(I'm not advocating using parens, just saying it that will fix the problem.)

In a comment you've asked what other situations come up where a newline might trigger ASI when you don't want it to. They're fairly rare, newline after return is by far the biggest one. Here's another example:

return
{
     result: "success"
};

There the author meant to return an object, but instead fell prey to the same ASI error that hit your code.

The take-away message here is: If you're returning something, put the beginning of it on the same line as the return. That wipes out the vast majority of the situations where ASI causes a problem.

Axel Rauschmayer has a good article about ASI and when/why it kicks in on his blog (which is worth following). The only non-return example from it is:

a
++
c

...which triggers ASI and becomes

a;
++
c

...but the original was pretty dodgy to begin with. :-)

like image 109
T.J. Crowder Avatar answered Jan 22 '23 03:01

T.J. Crowder


The return statement return/end the control of function or event handler of the program. So after that it does not execute next statement. Empty return statement undefined instead of string on next line.

like image 42
ahmad rabbani Avatar answered Jan 22 '23 03:01

ahmad rabbani