Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using var keyword when defining a variable in Javascript

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:

  1. 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 else part of the function totalClicks I use var numclicks = 1; then the code below does not wor. If I omit the var keyword, it works. Is this because for the code to work numclicks needs to be a global variable, or is there some other reason? Is this an exception to the rule that var should always be used, or is there another way to program this.

  2. 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 add numclick = 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
like image 205
Curious2learn Avatar asked Aug 12 '26 05:08

Curious2learn


1 Answers

  1. The first time you define numclicks, it needs to be outside of any functions so it becomes global. Using var while still defining a variable inside a function does not make it global. Using var on a global variable inside a function will make it a local variable.

  2. You have an element with the id of numclicks, so window.numclicks points to that element by default.

like image 78
John Stimac Avatar answered Aug 13 '26 19:08

John Stimac