0

{}.length throws in Chrome (and other browsers), while it returns undefined in Node.

I know something like Object.keys({}).length is the correct way to get the number of entries in an object, but I'm just more curious to understand why the browser API and the Node API are inconsistent here.

Maybe this has something to do with how parsing is performed? Both Chrome and Node use the V8 engine. My assumption was that this engine's parser is consistent between environments, but maybe it's not?

I wonder if it's intended, and has something to do with backwards compatibility, or unintended and might be rectified in the future.

SuperStormer
  • 4,997
  • 5
  • 25
  • 35
IliasT
  • 3,973
  • 1
  • 24
  • 26
  • You're looking for `({}).length` – Bergi Apr 12 '22 at 22:44
  • The engine is the same, the difference is where you enter the code to be executed. Different contexts will have different goal symbols for the parser, and then there's even ["helpful" tampering with the input](https://stackoverflow.com/q/36438034/1048572). The devtools console, the debugger, the node REPL, a script, … are all different. – Bergi Apr 12 '22 at 22:47
  • 1
    The JavaScript specification describes programs. I don't think it specifies the behavior of interactive environments like the browser console, so you can get different behaviors there. – Barmar Apr 12 '22 at 22:48
  • Read about strict mode – Konrad Apr 12 '22 at 23:37
  • 1
    The [related question](https://stackoverflow.com/questions/26347326/when-does-js-interpret-as-an-empty-block-instead-of-an-empty-object) seems to be the best answer that I can find here. Seemingly the browser is interpreting `{}` as an empty block while node is interpreting it as an empty object. – IliasT Apr 13 '22 at 00:22
  • @Barmar agreed, but this holds true inside a program as well, not just the console. – IliasT Apr 13 '22 at 00:23
  • @Bergi thanks, but the aim isn't for it to not throw, the aim is to understand the discrepancy. – IliasT Apr 13 '22 at 00:24
  • 1
    @KonradLinkowski strict mode doesn't seem to impact the behavior here. – IliasT Apr 13 '22 at 00:25
  • @IliasT Node.js will also parse `{}` as a block in a program. If you need a more detailed answer what was happening in your particular cases, you will need to provide more details about how you were executing the code in the respective environments. – Bergi Apr 13 '22 at 00:33
  • You said that it "returns undefined". That must mean you're using it in a place where an expression is allowed, like `console.log({}.length);` or `let len = {}.length;`. This should work the same in node.js and a browser. Can you update the question with the actual code that's working differently in Chrome? I just tried `let len = {}.length;` in Chrome and it didn't thrown. – Barmar Apr 13 '22 at 03:03

0 Answers0