Modular programming and global variables

Modular programming and global variables
0

#1

Hello everyone,

I’ve been trying to clean up the way I do code with modular programming using the revealing pattern.

I found links from free code camp’s help bot like:

https://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals

and

http://wiki.c2.com/?GlobalVariablesAreBad

I’ve realized I use way too many global variables. So I’m learning how to avoid them. I’m still confused as to why to avoid them. I understand thing like limiting scope to minimize overwriting globals now but here’s my particular question (I’m using jquery btw):

  1. I have a revealing modular pattern:

//first module
var loader = (function(){

var $dom1 = $("#dom1Element");

return(
    dom1:$dom1;

)


})();


//second module



var receiver =(function(){

   var $dom2 = $(dom2element);

    var dom1 = loader.dom1; //so it got the cached dom element from the loader module and I minimize touching the DOM too much

  //I write some function that manipultes dom2 with the cached data from dom1

render(dom1,dom2){

 // ...some function usig dom1 and dom2 as arguments...

};



})();


Now my actual question…

  1. I’ve coupled the 2 modules…
  2. I’ve lessened the ability of other functions to overwrite the variable $dom1.
  3. What about the memory leak? is revealing $dom1 as a property of loader (loader.dom) just the same as making $dom1 a global variable?
    –so basically what I did was to accomplish 1 and 2 but not necessarily to minimize memory consumption of the global variable am I correct? thanks…

#2

Yes, you coupled the 2 modules. I think on accident. You should pass loader as a dependency to receiver to uncouple them.

var loader = (function() { /* code */ })();
var receiver = (function( loader ) { /* code */ })( loader );

No, some js library you use could still overwrite $dom1. ex. $dom1 = null. If you wrapped both of the above functions into 1 single IIFE then you would have no global variable to overwrite.

(function() {
  // your code
})()

Only loader and receiver are global variables. You declared $dom1 as a local variable inside of loader. So $dom1 is not accessible globally. Try console.log( loader.$dom1 ); Also, your loader module is not returning an object.

var loader = (function() {
  //some code
  return (               <-- fix this part
    dom1:$dom1;
  )
})();

loader.dom1; // should not work

#3

oh sorry… by fixing this did you mean is should use

return {dom1:$dom1};

in the last line so that the return is an object (key value pair).

By doing so… back to my original question on memory leaks? so be revealing $dom1 as a propert of loader or specifically…
loader.dom1
is this the same as making a global variable and calling it
var x = $dom1
???

Thanks for the reply. Still trying to understand why I should use modular programming aside from keeping things organized. I usually wrap all the functions in one big

$(document).ready(function() {


});

using Jquery… so is that enough to close off the functions from other libraries?

thanks again!


#4

The variable $dom1 is a local variable scoped to loader. You can try

console.log( loader.$dom1 ) // returns undefined

If $dom1 was a global variable you would be able to access it globally. You do have access to the value $dom1 is holding which is accessible by loader.dom1.
You can create a memory leak by removing “#dom1Element” from the dom. There is no way to remove $dom1 reference to $("#dom1Element") which should create a memory leak.
I think there is a way to watch for memory leaks using chrome dev tool, profiler. I need to look it up. Guess I have homework now. :sweat:

Imagine working on a 3 person team where you are assigned a task to build a web app,that consists of a pomodoro timer, calendar widget and weather widget. To work simultaneously on the project and avoid global state issues every member creates their own separate module.


#5

This is the most useful link I found when learning this technique: revealing module pattern, if you have others I’d love to check them out.


#6

Learning JavaScript Design Patterns by Addy Osmani has a section about module pattern and revealing module pattern


#7

@Reggie01, thanks for answering and really sorry for giving you “homework…” I’ll try to look it up too and share what I can. I get the concept of separating modules to work on specific “parts or widgets (if I can call it that)” of a web page… What I sometimes don’t understand is how I’m exactly accomplishing that “efficiency” by the doing the modular approach. When am I:

  1. minimizing the overwriting of my variables?
  2. when am I properly decoupling my functions/modules? (I’m also currently studying pubsub)
  3. when am I really minimizing memory leaks? (I’ll try to check that out on chrome dev tools per your suggestions)

@Reggie01 and @yuzu-r,
I’m truly grateful for both your replies and your amazing links. Will check them out as soon as I can. My current work prevents me from going head on into coding but I’m totally loving it especially with the great community at freeCodeCamp! Free and open education FTW! :slight_smile:


#8

The efficiency in the modular approach isn’t necessarily in the initial development process. You’re right in that it may be easier in the beginning to have just a $(document).ready() that’s isn’t organized. It takes time and planning to get things working correctly with the modular approach. The efficiency part of it comes into play AFTER IT’S RELEASED.

After a project is released, you will still spend time maintaining it. This might be adding new features, going in to do bug fixes, or whatever changes might need to be made later down the road that may not be known at release. Ask yourself this question… Will it be easier to read the code and find what you’re looking for if it’s buried in thousands of lines of code in a single method or will it be easier and faster to find it when it’s within a section of code that has a nice descriptive name? Making your code modular is there to help the next person that goes in to work on the code. That “next person” could be future you. Right now you understand what you’re doing and how things are working. Think about things you’ve worked on a month ago, six months ago, a year ago. How much have you changed since then? Will you still understand what you wrote and why you wrote code that way? It’s much better to make things readable and understandable from the start and prevent future frustrations.


#9

@kblock-dev
Oh… I didn’t think about it that way. Actually, come to think of it… just writing that algorithm for the tic-tac-toe AI was a real challenge and finishing it felt great! Now however, I’m not sure if I can understand every single bit of code I put in there anymore haha… I did it before I learned about modular javascript programming (reveal pattern and pubsub)…hmm… I wonder of modular programming is now a part of the new improved beta curriculum of the new FCC…

Thanks for putting the future “me” into perspective in terms of modular programming…
:slight_smile: