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; 
    };
};
2
  • no, why would it be bad? it's a way to do private vars in JS Commented Jul 27, 2012 at 13:38
  • @Javier Thank God for local variables :) Commented Jul 27, 2012 at 14:00

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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...
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.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.