In Mac Chrome JS console, I experience the following results:
{} evaluates to Object()
{}; evaluates to undefined
How does the semicolon affect what comes before it?
Is this related to ASI, or another rule of parsing?
In Mac Chrome JS console, I experience the following results:
{} evaluates to Object()
{}; evaluates to undefined
How does the semicolon affect what comes before it?
Is this related to ASI, or another rule of parsing?
This is because JS interprets {} as an object literal, while {}; turns to a code block.
This can be avoided by putting that in a pair of parentheses: ({}); will return an object.
Chrome actually evaluates {} as if you've written ({}), thus forcing the interpreter to treat is as object literal as opposed to an empty block;
{
console.log("the line starts with { so it's treated is an empty block, not an object");
}
({}) //this is an object that is discarded after the line is read
To illustrate that it's actually an empty block, see this code:
{} == {} //syntax error because the effective code is "== {}"
And compare with this code
({}) == {} //force the left side to be an object
In the above, the there is no error because it's evaluated correctly and then the result is dropped.
The following, however is a syntax error, so in that case Chrome silently drops the braces
({};)