While I was testing saw a behavior of console(Chrome). if i type console.log({key:'value'}) is printing Object {key: "value"} which was expected by me. But when I directly typed {key:'value'} in console it printing 'value' only while I expected Object {key: "value"}.
Saw same behavior in IE10 and FF.
What is the reason behind this behavior?
It’s because your object is instead being interpreted as a block statement with a single statement within consisting of a string literal preceded by a label.
For the console to interpret it as object literal syntax, it needs to be part of an expression. If you wrap in parens, you’ll get the expected result.
Side note:
Here’s the really weird part. A statement is a statement because it doesn’t return anything. So why does it return
"value"?In JavaScript, statements have something like a final value. (I don’t remember exactly what it’s called.) It isn’t anything that’s useful or reachable in program code, but when a program is evaluated, that final value will be returned to whatever evaluated it.
The same goes when you use
eval()to evaluate a program. Its final statement value will be returned. Since code in a console iseval‘d, it gets that final value and prints it.