Mohsen
Mohsen

Reputation: 65835

Why do I get Unexpected token error for {}.toString() in browser but not in Node?

I am asking to understand what is exact correct syntax for . operator.

In browser:

{}.toString()
SyntaxError: Unexpected token .

In node:

> {}.toString()
'[object Object]'

Upvotes: 2

Views: 191

Answers (1)

Ry-
Ry-

Reputation: 225144

Node’s REPL does some things with your lines (trying it without parentheses if there’s a syntax error, if I recall correctly as seen in the source) that make life easier. { at the beginning of a statement will otherwise be treated as a code block, and not an object.

Wrap it in parentheses to force it to be treated as an object literal:

({}).toString()

or

({}.toString()) // This is what repl.js does

If you save the example to a file and run it with node, by the way, you’ll see that the error still occurs.

Upvotes: 5

Related Questions