I read some posts here on using var keyword when defining a new variable. The posts mentioned how using var within a function creates a variable with local scope, whereas not using var keyword creates a variable with global scope. Most posts recommend that var should always be used. I have a few questions:
I am learning JS and I was trying to write a script that counts the number of times a button has been clicked (see below for the code). If in the
elsepart of the functiontotalClicksI usevar numclicks = 1;then the code below does not wor. If I omit thevarkeyword, it works. Is this because for the code to worknumclicksneeds to be a global variable, or is there some other reason? Is this an exception to the rule thatvarshould always be used, or is there another way to program this.The first time the button is clicked, the output is
NaN. It is not clear to me why it is not 1? Following the logic of the code it appears that the variable is set to 1 before it is written to the document. I know this problem gets solved if I addnumclick = 0;before the function statement. But it is not clear to me why this solves the problem.
Thanks very much for your help.
CODE
<html>
<head>
<title>Count number of clicks</title>
</head>
<body>
<form>
<input type="button" value="click here" onclick="totalClicks();">
</form>
Total clicks: <span id="numclicks"></span>
<script type="text/javascript">
function totalClicks(){
if (window.numclicks) {
numclicks++;
}
else {
numclicks = 1;
}
document.getElementById("numclicks").innerHTML = numclicks;
}
</script>
</body>
</html
<span id="numclicks"></span>can be (but should NOT be) accessed viawindow.numclicks. In other words, the first time you run, you get NaN because you are doing(the span)++which isNaNwhich evaluates to false the second time and you finally get what you are trying to achieve.