0

I've started to check the toString method on nonprimitive values and mentioned one strange case

new Object().toString() // [object Object]

above code works properly

{}.toString() // Uncaught SyntaxError: Unexpected token '.'

I think the code is pretty the same , but in the second case it returns an error. Why is it? Could someone explain? Why no boxing there ?

Andrey Radkevich
  • 3,012
  • 5
  • 25
  • 57
  • 4
    `({}).toString()` otherwise it's interpreted as a code block, not an object literal – VLAZ Oct 20 '20 at 20:08
  • isn't it strange ?) the same with array works ok [].toString() – Andrey Radkevich Oct 20 '20 at 20:12
  • or it doesn't know is it block for code, or it is object ? – Andrey Radkevich Oct 20 '20 at 20:12
  • because there's no other meaning for `[`. How is it supposed to know if you want a object or a code block? Interpret what's inside and decide whatever would compile? – Adassko Oct 20 '20 at 20:14
  • No, it's not strange. `[]` only means an array literal *unless* you're trying array access. But if it's the first thing in the code, it's not array access, it's going to be an array. `{}` is used for code blocks and for object literals. There is no way to decisively tell which one you actually want at the start of the code, so it's just using code blocks. – VLAZ Oct 20 '20 at 20:14
  • @Adassko even interpreting what's inside isn't exactly foolproof `{foo: 1}` *might* be an array literal with property `foo` and value for it `1` or it *might* be a code block with [label](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label) `foo` and a lone `1` there. Both are syntactically correct and radically different. – VLAZ Oct 20 '20 at 20:16

0 Answers0