0

Why does !{}.length evaluate to true in JavaScript if {}.length throws the error Uncaught SyntaxError: Unexpected token '.'. In fact, !{}.definitelyNotAMethod also evaluates to true.

Objects don't possess length methods, but if you were expecting the object to be an array and didn't perform the proper validations, this could cause a hard-to-spot bug in your code base.

Thanks for taking a look!

Jason Sears
  • 429
  • 1
  • 7
  • 18
  • https://stackoverflow.com/questions/9032856/what-is-the-explanation-for-these-bizarre-javascript-behaviours-mentioned-in-the – epascarello Jul 23 '20 at 16:13
  • @epascarello nice find! Didn't see that post – Jason Sears Jul 23 '20 at 16:14
  • Should be `!{}` is false and it will be `false.toString().length`. Now other one `{}` is seen as a block (not object) – epascarello Jul 23 '20 at 16:15
  • It's just the empty object literal syntax is treated as [a block](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block) when you do `{}.length`.If you do `const a = {}; a.length` doesn't throw any error. So, you don't have to worry about this throwing an error during validtion. – adiga Jul 23 '20 at 16:20

0 Answers0