Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a JavaScript object in console

When I type simple objects to Chrome JavaScript Console, I get an output like this:

>true
true
>1/3
0.3333333333333333

And so on.

But a syntax error occurs when I type objects:

>{ 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

While I know for sure that this expression could be correctly used in initializing an object, because:

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

Maybe it's a silly question, but I really want to know the reason why is this happening?

like image 616
Sergey Avatar asked Jan 31 '12 15:01

Sergey


People also ask

How do you define an object in JavaScript?

In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc.

How do you console an object in JavaScript?

Console object In JavaScript, the console is an object which provides access to the browser debugging console. We can open a console in web browser by using: Ctrl + Shift + I for windows and Command + Option + K for Mac. The console object provides us with several different methods, like : log()

How do you console log objects?

Answer: Use console. log() or JSON. stringify() Method You can use the console. log() method, if you simply wants to know what's inside an object for debugging purpose. This method will print the object in browser console.


1 Answers

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

Note that an ExpressionStatement cannot start with an opening curly brace because that might make it ambiguous with a Block. Also, an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.

To make it evaluate as an expression, it needs to be the right-hand side of an assignment, wrapped in parentheses or preceded by an operator. (!{a:1,b:2})

like image 57
josh3736 Avatar answered Oct 14 '22 03:10

josh3736