Namespacing with IIFE in ES6?

Apparently, ES6 doesn’t need namespacing because each file is a separate module.

Not exactly. Each module does have its own scope, that is correct, but not every file is a module. There still are scripts in ES6 that work just like those from ES5, and are executed in the global scope.
In those scripts, you still need to avoid globals as much as you can, typically by not declaring/assigning any variables or by wrapping your “module” in an IEFE to give it a separate variable scope.

Is there a newer/nicer way of doing this in ES6?

You can use a block and lexical variable declarations (let, const, function):

{
    const msg = 'This line doesn\'t do anything.'
    window.alert(msg);
}
// msg is not defined here

Or you can use an arrow function in your IEFE, which allow you to use this to refer to the global object without needing to use .call(this)):

(() => {
    var msg = 'This line doesn\'t do anything.'
    window.alert(msg);
})();

But then, how do I avoid global namespace interference, or name collisions?

In ES6 modules, there is nothing global except the builtin objects and maybe the global object. Avoid modifying them.

And of course you will need to take care about collisions between module names – how to do that should be explained in the docs for the resolver mechanism of your module loader.

Leave a Comment