Search code examples
javascriptclosuresglobal-variables

Is, wrapping all code(including class definitions) inside a closure in order to avoid global variables an acceptable practice in Javascript?


Imagine the situation in which you have to deal with event listeners, animation frames, and all that stuff you might come across when playing with canvas. It's tough for me, try to make it work without any global variables at all(but that's what i'm trying to do), due to all the mess that comes around with scoping. So, I was wondering if such a solution would be acceptable:

(function(){
  //some class declaration

  //some other function declaration
  
  //some variable definitions

  //some procedural code

  //event listeners

})();


Solution

  • It's fine, although using modules (triggered with <script type="module"> in browsers) avoids the need to do that since it scopes top-level var variables and function declarations to the module instead of as globals.

    That also lets you more easily narrow the scopes of other self-contained chunks of code (like classes) by moving them into separate modules and importing them. (Something the revealing module pattern would be used for before JS had native modules).