0

Possible Duplicate:
Difference between using var and not using var in JavaScript

What is the primary difference between these two approaches. Could someone help me understand. What does it mean if a variable is declared with "var" keyword inside a function?? in both the cases the timer is cleared in 3secs as expected..

Approach 1:
<html>
<body>
<script type="text/javascript">
function function2()
{
int=self.setInterval(function(){
alert(int);
clearInterval(alert("in clear"+ int));
},3000);
}
</script>
<button onclick="function2()">Start</button>
</body>
</html>

Approach 2


<html>
<body>
<script type="text/javascript">
function function2()
{
var int=self.setInterval(function(){
alert(int);
clearInterval(alert("in clear"+ int));
},3000);
}
</script>
<button onclick="function2()">Start</button>
</body>
</html>
Community
  • 1
  • 1
arjunv
  • 41
  • 3

1 Answers1

2

Without using var you are implicitly putting that variable in the global namespace. With var the variable is local to the function.

Anna Brenden
  • 3,837
  • 2
  • 21
  • 19
  • okay thanks.. but how in both cases the timer is cleared without any issues? – arjunv Apr 26 '12 at 01:30
  • As they are shown, there isn't a functional difference between the two approaches you described - they both do the same thing whether `int` is in the global namespace or local to `function2`. – Anna Brenden Apr 26 '12 at 01:57