3

In ECMAScript 5 and below, var declarations at the top level of a script become globals, which is to say, properties of the global object (window in browsers.) In ECMAScript 6, we now have modules. Modules are in strict mode, so we won't automatically create a global by forgetting var, but if I declare a var at the top level of a module, does it become a global property of the window object? What if I use let or const or any of the new declaration forms added in ES6?

var foo = {};
console.log(window.foo === foo); // true or false?

let bar = {};
console.log(window.bar === bar); // what about this?
kangax
  • 38,898
  • 13
  • 99
  • 135
Sean McMillan
  • 10,058
  • 6
  • 55
  • 65
  • @Bergi: I don't think this is a duplicate. That questions asks about `let` in script context. This question asks about `var` in module context. – Sean McMillan Dec 14 '15 at 16:38
  • Is there a useful way I can edit this question to call out the distinction? I don't feel it's appropriate to just add "note, VAR in a MODULE context", (or something,) because that's basically just rude toward the moderators. But I'm not sure how to clarify that distinction harder in a way that makes it naturally part of the question. – Sean McMillan Dec 14 '15 at 16:53
  • 1
    This looks closer to a duplicate: http://stackoverflow.com/questions/32961255/is-there-an-es6-module-scope-equivalent-to-window?rq=1 though there are subtle differences. (I'm asking if they go on `window`; That question is asking if there's _something_ like `window` for modules. The answer to both is the same.) – Sean McMillan Dec 14 '15 at 17:02
  • Oh right, I'm sorry. Must have been tired :-/ – Bergi Dec 14 '15 at 18:33
  • No problem. It's a subtle difference. – Sean McMillan Dec 17 '15 at 21:54

1 Answers1

2

but if I declare a var at the top level of a module, does it become a global property of the window object? What if I use let or const or any of the new declaration forms added in es6?

The answer is no in both cases. Global properties are created (if CanDeclareGlobalVar returns true) only for declarations of script (section 15.1.8). But both VarDeclaredNames and VarScopedDeclarations within the module belong to that module (ModuleItem, to be precise) - not the whole script.

Be it otherwise, the whole idea of encapsulating data within the modules (so that each module would communicate with the rest of app via established export/import routines) would have been just wasted.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • 1
    I can't understand the spec-ese, I don't see where in 15.1.8 it checks for script vs module. I guess I need to level up first. Your plain English "if it did, modules would be worthless" makes a lot of sense though. – Sean McMillan Sep 12 '14 at 20:22