Alex Oswald
Alex Oswald

Reputation: 33

JavaScript variable scope in Google Chrome

I've got the following code :

<!DOCTYPE html>
<html>

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>

<body>

<p id="p"></p>

<script>

var top = 9;
( function () {  top += 1;  document.getElementById( "p" ).innerHTML = top;  } )()

</script>

</body>

</html>

It works fine in Internet Explorer ( prints 10 ), but in Google Chrome it prints [object Window]. But if i change it like this:

( function () {  var top = 9; top += 1; document.getElementById( "p" ).innerHTML = top; } )()

it works in Chrome fine too. The only change is that the variable is now local. Does it mean that in Chrome i can't access global variables? Whatever i do i can't get the right result..

Upvotes: 3

Views: 441

Answers (1)

Sterling Archer
Sterling Archer

Reputation: 22395

Change your variable name, as it's conflicting with the Window.top global object. See the MDN doc page

Upvotes: 2

Related Questions