Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are globals bad?

Tags:

javascript

It totaly makes sense to me to use it here. What would be the alternative? How can i generaly avoid to use them and most of all why is it bad according to jsLint to make use of globals.

(function($){
  $(function(){
   $body = $('body'); //this is the BAD Global

   $.each(somearray ,function(){ $body.dosomething() });

   if (something){
     $body.somethingelse();
   }

  });
}(jQuery));

Can you help me understand this? And give me a better solution?

like image 377
meo Avatar asked Nov 22 '10 14:11

meo


2 Answers

Globals are bad because they don't cause problems right away. Only later, after you have used them all over the place, they will cause very ugly problems - which you can't solve anymore without writing your code from scratch.

Example: You use $body to define some functions. That works fine. But eventually, you also need a value. So you use $body.foo. Works fine. Then you add $body.bar. And then, weeks later, you need another value so you add $body.bar.

You test the code and it seems to work. But in fact, you have "added" the same variable twice. This is no problem because JavaScript doesn't understand the concept of "create a new variable once." It just knows "create unless it already exists." So you use your code and eventually, one function will modify $body.bar breaking another function. Even to find the problem will take you a lot of time.

That's why it is better to make sure that variables can only been seen on an as needed basis. This way, one function can't break another. This becomes more important as your code grows.

like image 181
Aaron Digulla Avatar answered Sep 19 '22 09:09

Aaron Digulla


you should define it with var $body, then it would be local in the scope of that function, without var it could be overwritten by everybody

(function($){
  $(function(){
   var $body = $('body'); //this is the local variable

   $.each(somearray ,function(){ $body.dosomething() });

   if (something){
     $body.somethingelse();
   }

  });
}(jQuery));
like image 31
mpapis Avatar answered Sep 22 '22 09:09

mpapis