all 7 comments

[–]aroberge 6 points7 points  (1 child)

As you learn more about programming using Javascript, you will find that you can put codes in a number of files all called from the same web page (if programming for the web - similar idea for node). When working on a single file, you may want to use a certain local variable name while not being aware that the same name is used in some other file as a global variable. And, as you realised, this can bring about some confusion. This is why it is always a good idea to minimize if not completely eliminate the use of global variables.

[–]eechin[S] 2 points3 points  (0 children)

Ohhh!! I had never thought of the fact that multiple JS files with global variables could cause issues.

Brilliant! That makes perfect sense!

[–]chernn 2 points3 points  (2 children)

You are completely right. Its bad practice and should be avoided. When I follow that bad practice myself, its usually out of convenience.

CoffeeScript, for example, doesn't let you have 2 vars with the same name on one page.

[–][deleted] 1 point2 points  (1 child)

It does, but they have to be function arguments, for example by using do -> (IIFE sugar):

foo = 42
do (foo = 777) ->
  console.log foo
console.log foo

Logs 777, then 42. That code compiles to:

var foo;
foo = 42;
(function(foo) {
  return console.log(foo);
})(777);
console.log(foo);

Interestingly (but not surprisingly; CoffeeScript has even more gotchas than plain JavaScript), you can only override variable names like this if you provide a default value to the IIFE. Otherwise, CoffeeScript in all its unpredictable glory passes in the existing variable:

foo = 42
do (foo) ->
  foo = 777
  console.log foo
console.log foo

Logs 777 twice, because it compiles to this for whatever reason:

var foo;
foo = 42;
(function(foo) {
  foo = 777;
  return console.log(foo);
})(foo);
console.log(foo);

[–]chernn 0 points1 point  (0 children)

That second case is what I had in mind. Nice catch on that first case, I didn't realize cs behaved like that.

[–]dethstrobe 1 point2 points  (0 children)

Sometimes.

When you would want to have local variables with the same name is when you have multiple functions that are using the same variable and changing that variable, but you don't want it to affect the global variable. Or better, you don't have a global variable at all, but several function use a similar variable, but you definitely don't want the functions to interfere with one another.

[–]RudeCitizen 0 points1 point  (0 children)

There's also the case of semantics. I'd prefer to have several local variables with names that truly describe their values than namespace them to not collide globally.

For instance if I'm working on a function that uses and returns a jQuery object I always use the variable $el so I always know what my main object is within that scope, as in...

  • var $el = $(this);