Javascript: implicit semicolon is NOT your friend

Today I spent several hours trying to find out why this code does not work:

function doit() {
return
someObject
.method1()
.method2();
}

but this one does:

function doit() {
let temp;
return temp =
someObject
.method1()
.method2();
}

It involved some rather complicated promises and what-not, so I was tossing them around, trying to figure out where it gets stuck. The answer, however, is rather simple: unfortunate code formatting. When return is on a line by itself, Javascript inserts an implicit semicolon after it, and completely ignores subsequent code, quietly returning undefined:

function doit() {
return ;
someObject;
.method1();
.method2();
}

Porting formatting habits from one language to another may be dangerous: not all whitespace is created equal. It is kind of obvious with Python, but Javascript may be tricky as well.

Of course, this happened before to other people. There is even a note in some coding conventions that reads “The return value expression must start on the same line as the return keyword in order to avoid semicolon insertion“. In fact, I knew about the implicit semicolon, but I did not connect the dots, I was too busy debugging my promises 🙂

That’s all folks 🙂

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *