DeadPixle
DeadPixle

Reputation: 19

How to add varible on to it self

In the code I'm trying to add plus on to a variable that it self can I can't see where I'm going wrong:

<!DOCTYPE html>
<html>
  <body>
    <h1>The * Operator</h1>
    <p id="demo"></p>
    <button onclick="myFunction()">Try it</button>
    
    <script>
      function myFunction() {
        var playerscore = playerscore + 1;
        document.getElementById("demo").innerHTML = playerscore;
      }
    </script>
  </body>
</html>

Upvotes: 0

Views: 58

Answers (3)

Leo
Leo

Reputation: 5235

You are trying to use the variable palyerscore before initializing it. As a result it will be undefined and incrementing a non-initialized variable is pointless and hence you won't be seeing anything on the screen.

So, replace

var playerscore = playerscore + 1;

before the myFunction() put:

var playerscore = 0;

then inside myFunction put:

playerscore = playerscore + 1; 

Upvotes: 0

Liam
Liam

Reputation: 29624

in your function playerscore only exists inside the function. So it will initally be undefined. The easiest (though not necessarily the best way) is to define the variable in the global scope.

//outside of function now in global scope (or window.playerscore)
//set it to a value (0) also. Otherwise it's undefined. undefined +1 is not going to work
var playerscore = 0;
function myFunction() {
   //no var, the varibale is declared above NOT in here Important!
   playerscore = playerscore + 1;
   document.getElementById("demo").innerHTML = playerscore;
}

and even better option is to use a closure:

var myModule = (function(document){
     //no longer in global scope. Scoped inside myModule so not publically accessible
     var playerscore = 0;

     function myFunction() {
        //no var, the varibale is declared above NOT in here Important!
        playerscore = playerscore + 1;
        document.getElementById("demo").innerHTML = playerscore;
     }

     //allow myFunction to be called externally
     return{myFunction:myFunction};
})(document);

HTML changed for the above:

<button onclick="myModule.myFunction()">Try it</button>

though this may be a little too advanced at the moment. If your interested in the above I reccmoend reading about the The Revealing Module Pattern

Upvotes: 1

Peter B
Peter B

Reputation: 24136

You need to declare playerscore and set it to an initial value, probably 0 in this case. Like this:

<p id="demo"></p>
<button onclick="myFunction()">Try it</button>
<script>
  var playerscore = 0;

  function myFunction() {
    playerscore = playerscore + 1;
    document.getElementById("demo").innerHTML = playerscore;
  }
</script>

Upvotes: 1

Related Questions