Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Variable' was used before it was defined

I am checking if a variable is defined or not, and if it is not defined explicitly I am going to define it by doing:

if ( typeof(aVariable) == 'undefined' ) {
  var aVariable = value;
}

Because the variable is not defined JSLint warns that it is used before it is defined, and that is exactly what I want.

How can I overcome this?

I want to enable defining those variables explicitly doing this:

<script>
  var aVariable = value;
</script>
<script src="myScript.js"></script>

So everyone who is going to include this script can customize some of the properties. And I am afraid I cannot change this logic because it is already being used in hundred of web sites this way.

Scroll down for the answers/solutions, because I have answered my own question Stack Overflow does not show it up. Be sure not to miss them.

like image 988
nimcap Avatar asked Feb 10 '10 07:02

nimcap


2 Answers

I think what JSLint is telling you is that you shouldn't use variables before they are defined. If you are happy that it is appropriate in your scenario - you can ignore that warning. If you aren't absolutely sure, have another think about why this variable isn't defined yet.

For example, do you really want to test if aVariable has a value set, rather than is or isn't defined?

var aVariable = null;

... (sometime later)

if (aVariable == null) {
  aVariable = value;
}
like image 84
Fenton Avatar answered Oct 23 '22 05:10

Fenton


I found more acceptable answers in JSLint mailing list, sorry about that Boldewyn :)

Solution 1

In IE, at a script level (i.e. per file, or per script block), if it sees a "var" declaration during its parse phase (before execution), it will reset the value of that variable if it already existed.

So better would be to simply do this:

/*global foo: true */
if (typeof foo === "undefined") {
foo = "some value";
}

By not declaring "var" and simply assigning foo, foo will automatically get global scope.

Solution 2 (special case)

If explicitly set variable is not zero or false

var foo = foo || "some value";
like image 22
nimcap Avatar answered Oct 23 '22 04:10

nimcap