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