Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do variable declarations become properties of window in ecmascript 6 modules?

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?
like image 894
Sean McMillan Avatar asked Dec 08 '25 20:12

Sean McMillan


1 Answers

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.

like image 70
raina77ow Avatar answered Dec 10 '25 09:12

raina77ow