Avoid semicolon insertion on return statements
suggest changeThe usual JavaScript convention is to place the opening brace of a block on the same line as its declaration:
if (...) {
}
function (a, b, ...) {
}
rather than on 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents