JS Tip of the Day: The Return of ASI

The Return of ASI
Level: Intermediate

Earlier we covered how ASI may not automatically insert semicolons where you might expect them to be. The opposite can also be true, where ASI can insert them when you’d wish it wouldn’t. A good example of this is with the return statement.

Any return statement on its own line, without anything following it, will automatically be terminated with a semicolon from ASI.

return
// is always seen as
return;

Normally, if you’re returning something, this effect wouldn’t come into play because most of the time your return value would come immediately after the return keyword. However, if, for example, you’re a fan of the hanging indention style and are returning something like an object literal, you may be inclined to write a return statement such as the following:

return
{
    sailor: 'returning home... I hope'
}

Unfortunately, this is where ASI will come in and insert a semicolon after return causing the object below it to be ignored.

return; // due to ASI, returns undefined
{
    sailor: 'are we lost at sea?'
}

To correct this, always make sure a return value starts on the same line as return itself.

return {
    sailor: 'homeward bound!'
}

More info: