JavaScript Automatic Semicolon Insertion - ASI Avoid semicolon insertion on return statements

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

The JavaScript coding convention is to place the starting bracket of blocks on the same line of their declaration:

if (...) {

}

function (a, b, ...) {

}

Instead of in the next line:

if (...)
{

}

function (a, b, ...) 
{

}

This has been adopted to avoid semicolon insertion in return statements that return objects:

function foo() 
{
    return // A semicolon will be inserted here, making the function return nothing
    {
        foo: 'foo'
    };
}

foo(); // undefined

function properFoo() {
    return {
        foo: 'foo'
    };
}

properFoo(); // { foo: 'foo' }

In most languages the placement of the starting bracket is just a matter of personal preference, as it has no real impact on the execution of the code. In JavaScript, as you've seen, placing the initial bracket in the next line can lead to silent errors.



Got any JavaScript Question?