Anthony N.
Anthony N.

Reputation: 395

why does window.data work and not data

I have an html file that has some inline JavaScript in the end of the body where a global variable data is defined. A JavaScript file is included in the head, and one of the functions inside the JavaScript file uses the value in the variable.

Since the file was included before the definition of the variable, the variable in the JavaScript file is returning undefined. but window.variable returns the variable. Is there any general rule I'm missing or this is just a coincidence in my case.

HTML simplified:

<script src='myFile.js' language='JavaScript' type='text/javascript'></script>
<script language="javascript">
    var inLine = "abcde"; 
</script>

myFile.js that does not work (returns undefine inLine):

var insideFile = inLine.length;

myFile.js that works:

var insideFile = window.inLine.length;

In sum I want to know why one of them works and not the other

Upvotes: 1

Views: 1112

Answers (2)

guest271314
guest271314

Reputation: 1

In sum I want to know why one of them works and not the other

One approach that could possibly return defined results , without error, would be if defer attribute was set at "myFile.js"

<script src="data:text/javascript,var insideFile = window.inLine.length;console.log(inLine, insideFile)" 
  type="text/javascript" defer></script>
<script type="text/javascript">
  var inLine = "abcde";
  console.log(window.inLine)
</script>

Upvotes: 0

Muhammad Umer
Muhammad Umer

Reputation: 18127

Your js file is included before variable is defined and which means code inside the file runs before this variable is defined, So you get the error.

The reason you dont get error for window.varname is also the reason you wont get error for this:

var obj = {};
console.log(obj.a);

when you look up property on object and it doesnt exists Javascript shows undefined.

Upvotes: 2

Related Questions