Reputation: 136
I was trying something in the Chrome (and FF) console and realized that the JS REPL evaluates some expressions in a surprising way:
{} "123"
-> "123"
{} 123
-> 123
{} []
-> []
Etc.
Why is that? Also, somewhat inconsistent with the previous behavior:
{}{}
-> undefined
What's the logic behind the fact that these are valid expression?
Upvotes: 3
Views: 78
Reputation: 31712
{} "123"
is the same as {}; "123";
which yield the value of the last expression ("123"
).
{}
could be both an object literal or a block.If {}
is not implicitly taken as an object literal (no assignment or no key value pairs ...) then the interpreter will parse it as a block.
{}{}
is the same as:
{
// block with no expressions
};
{
// block with no expressions
};
yielding undefined
which is the value of an empty block.
Upvotes: 9