0

Why am I getting Uncaught ReferenceError: i is not defined in my javascript file?

So here's how I did it.

app.js

$(function() {
  var i = 1;
});

some.js

$(function() {
  alert(i);
});

and here's how I sequence my files.

// included jquery here
<script src="/app.js" type="javascript/text"></script>
<script src="/some.js" type="javascript/text"></script>

How can I execute or access variables from app.js or to other javascript files? I thought they should be listed in sequence. Where did I go wrong? Any help would be much appreciated. Thanks

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Boy Pasmo
  • 8,021
  • 13
  • 42
  • 67

1 Answers1

2

Problem is you are defining i in a local scope.

You should try like this

<script type="text/javascript">
  var i = 1; //i in a global scope.
</script>

<script>
  alert(i);
</script>

There can be conflicts if you will define i again somewhere. So there is a better way to define namespaces to avoid conflicts like bellow.

<script type="text/javascript">
  var firstScript = {}; //this will be namespace for first script
  firstScript.i = 1;
</script>
<script>
  alert(firstScript.i);
</script>
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
  • 1
    By far the better answer. FWIW, a fairly typical pattern here is `var MyApp; MyApp = MyApp || {}; MyApp.property = "value"; ...` That way, load order of the scripts becomes less important. (Either script creates the `MyApp` object, or uses it if it's already there; a `var` for a variable that already exists is ingored.) – T.J. Crowder Jul 27 '14 at 11:46