4

This reminds me of Gary Bernhardt's "Wat" talk, but why is {} || 3 a syntax error?

> 3 || {}
3
> {} || 3
VM2330:1 Uncaught SyntaxError: Unexpected token '||'
> {} + 3
3
> a = {}
{}
> a || 3
{}
Jason S
  • 184,598
  • 164
  • 608
  • 970
  • [Block statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block) vs Object – epascarello Dec 11 '19 at 18:26
  • `{}` is interpreted as a code block. So you evaluate (essentially) `|| 3` – VLAZ Dec 11 '19 at 18:26
  • I'm assuming `{}` is interpreted as a block. Try `({} || 3)`. – connexo Dec 11 '19 at 18:27
  • Also, related to Wat - this is essentially [the same behaviour that was demonstrated there](https://stackoverflow.com/questions/9032856/what-is-the-explanation-for-these-bizarre-javascript-behaviours-mentioned-in-the). Check 3. and 4. – VLAZ Dec 11 '19 at 18:29

1 Answers1

2

You need to make an expression with patentheses.

({} || 3)

Oterwise you take a block statement and this is not an expression for use with an operator.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 2
    You can also just wrap the object in parentheses to let the interpreter know this is an object instance rather than an execution context. `({}) || 3` – Jacob Penney Dec 11 '19 at 18:29