0

Is it bad to use local variable in the code below and if so, why?

var lib = new function () {

    var localVariable;

    this.publicCall = function (e) {
      localVariable = e.variable;
    };

    var privateCall = function (e) {
      localVariable = e.variable; 
    };
};
user1514042
  • 1,899
  • 7
  • 31
  • 57

2 Answers2

1

No, in fact I'd say that looks like good practice.

What alternative were you thinking of? A global variable? Now that would be bad practice.

SDC
  • 14,192
  • 2
  • 35
  • 48
  • hmm, most times I can pass variable by injecting it into the arguments of a function I'm calling, thus using arguments as a main transport, it just looks less readable than using local vars... – user1514042 Jul 27 '12 at 13:43
  • Injection is good if it's preventing a dependency (ie because it makes unit testing easier), but for simple variables, there's no dependency to worry about, so no real need to inject everything. A local variable is fine. – SDC Jul 27 '12 at 15:09
1

No, this is actually a preferred pattern. Local variables should always be defined in the scope in which they needed. You definitely shouldn't pollute your global scope with variables as this is considered a bad practice.

There are many resources on the web to help you understand variable scope. Check out this SO question.

Community
  • 1
  • 1
Kevin Babcock
  • 10,187
  • 19
  • 69
  • 89