Defining a JavaScript object in the console

When I print simple objects in the Chrome JavaScript console, I get this output:

>true true >1/3 0.3333333333333333 

And so on.

But when I type objects, a syntax error occurs:

 >{ a: 1, b: 2 } SyntaxError: Unexpected token : arguments: Array[1] 0: ":" length: 1 __proto__: Array[0] get message: function getter() { [native code] } get stack: function getter() { [native code] } set message: function setter() { [native code] } set stack: function setter() { [native code] } type: "unexpected_token" __proto__: Error 

Although I know for sure that this expression can be used correctly when initializing an object, because:

 >obj = { a: 1, b: 2 } Object a: 1 b: 2 __proto__: Object 

This may be a stupid question, but I really want to know the reason why this is happening?

+6
json javascript oop google-chrome v8
source share
6 answers

Because your statement is evaluated as a block , not an object literal declaration.

Please note that ExpressionStatement cannot start with an opening curly brace, because this can make it ambiguous with a block. Also, an ExpressionStatement expression cannot begin with the function keyword, as this can make it ambiguous with FunctionDeclaration.

For it to be evaluated as an expression, it must be the right part of the destination, enclosed in parentheses or preceding the statement. ( !{a:1,b:2} )

+8
source share
  { a: 1, b: 2 } 

is a block of code, with two incorrectly labeled variables.

To create an object, surround the code block with parentheses so that the curly braces are interpreted as object literals:

 ({ a: 1, b: 2 }) 
+7
source share

This is because opening { without context is interpreted as the start of a block. You can use parentheses:

 ({ a: 1, b: 2 }) 

Be that as it may, this is just a block of execution that can be found after if or for . So you can enter:

 {alert("Hello!");} 

Here's more about that. It also blocks return values, which is both surprising and disappointing.

+4
source share

Because { a: 1, b: 2 } not a valid expression to execute. JavaScript looks like a block of code since it starts and ends with curly braces.

If you try ({ a: 1, b: 2 }) , it will work.

+2
source share

Because your statement is evaluated as a block, not an object literal declaration.

True josh

If you want to be rated as an object, simply write:

 > ({a : 1, b : 2}) Object a: 1 b: 2 __proto__: Object 
+2
source share

Try this instead:

 ({ "a" : 1, "b" : 2 }) 
+1
source share

All Articles