In order for an expression to be used as a statement, it must not be ambiguous with other statement syntaxes. Therefore, the expression must not start with any of the following tokens:
Therefore, all of the following are invalid:
function foo() {
console.log("foo");
}();
var let = [1, 2, 3];
let[0] = 4;
{
foo: 1,
bar: 2,
};
More dangerously, sometimes the code happens to be valid syntax, but is not what you intend.
var let = [1, 2, 3];
function setIndex(index, value) {
if (index >= 0) {
let[index] = value;
}
}
setIndex(0, [1, 2]);
console.log(let);
{ foo: 1 };
To avoid these problems, you can use parentheses, so that the statement is unambiguously an expression statement.
(function foo() {
console.log("foo");
})();