3

In chrome devtools, when I input

> {a:1}

I got { a: 1 } object as the return value, which is understandable.

But when I add a comment after it

> {a:1}//

The return value becomes 1.

screenshot

It might be a trivial question but it does make me scratch my head for a long time.

I assume the devtool interprets the {} as a code block and a as a tag name. But why adding a comment // would make such a difference? Is it the intended behavior?

Hao Wu
  • 17,573
  • 6
  • 28
  • 60
  • 1
    I imagine their command line tools look for a simple expression. The second one doesn't match the pattern for a simple expression. Remember that the dev tools command line is just a debug tool. What you're doing will never happen in real web code. Having said that, you could argue this is a bug and file a bug report. – Tim Roberts Aug 16 '23 at 01:33
  • I also tried this in node.js and Safari, the result remains the same. So I guess it is actually a global phenomenon with a consistent rule? – Hao Wu Aug 16 '23 at 02:01
  • This is pretty interesting. I could understand if the output of the second one was a string serialized version of the object, but not sure why if grabs the value of the "a" key and outputs that. I also find this pretty interesting: `var temp="hello";{b:42}`. It outputs "42". So seems anything apart from giving just the object has this behavior. – Adam Harte Aug 16 '23 at 02:03
  • And having more than one key/value i.e. `{a:3,b:7}//` results in "Uncaught SyntaxError: Unexpected token ':'" – Adam Harte Aug 16 '23 at 02:07
  • 1
    In statement mode it's a block and `a` is a *label*, `1` is just a literal number, which is the last expression in the block so it becomes the result of the block's evaluation. When you add a second label it becomes invalid syntax because labels can't be inside an expression (`1` starts the expression, the comma is a part of it). – wOxxOm Aug 16 '23 at 07:33

0 Answers0