openexchangerates / javascript-sandbox-console

a mini interactive javascript console for library/plugin demos and homepages
http://openexchangerates.github.io/javascript-sandbox-console/
MIT License
319 stars 58 forks source link

Object literals are not interpreted correctly #9

Closed davidchambers closed 12 years ago

davidchambers commented 12 years ago
{foo: 'bar'}
  => "bar"
{foo: 'bar', baz: 'quux'}
  => "SyntaxError: Unexpected token ':'"
davidchambers commented 12 years ago

Hmm…

> eval("{foo: 'bar'}")
"bar"

I can't explain this, but apparently parens are required:

> eval("({foo: 'bar'})")
Object
  foo: "bar"
wjcrowcroft commented 12 years ago

Very interesting JavaScript quirk there - for example:

{joss: 'hungover'}  // "hungover"
{joss: 'hungover', javascript: 'being a dick'}  // SyntaxError: Unexpected token :
var thismorning = {joss: 'hungover', javascript: 'being a dick'}  // assigns object

I may be wrong, but in the first two cases the curly braces {} are treated as block delimiters (hence the syntax error), but when used in assignment (=) it's creating a new object.

When you wrap it in brackets (e.g. ({joss: 'hungover'})) the output is the result of the expression contained in the parentheses - that returns an object. I can't remember why.... it just does.

Good catch!

davidchambers commented 12 years ago

Huh. It would appear that the “key” is being interpreted as a label (and the curly brackets as block delimiters, as you say). I've never used a label before, so it's no surprise that I didn't spot the ambiguity.