I\'m learning javascript and I decided to create simple Rock, Paper, Scissors game. I want to make it controllable by buttons. So I made this in html:
var
is used for declaring a variable. You don't need to declare user
variable again in user
function. You just need to assign a value to declared one.
var user; //declaration
function user(choice) {
user = choice; //assignment
}
The selections should be encased in the quotes, javascript is looking for the variables named paper etc.
<button onClick="user(rock)">Rock</button>
<button onClick="user(paper)">Paper</button>
<button onClick="user(scissors)">Scissors</button>
The var keyword used in the scope of a function will declare a new local variable.
Hence, in the global scope, user
retains the value "none"
.
One problem:
var user = "none";
function user(choice){
var user = choice;
}
One variable of user is hiding the other variable of user.
And having a function and variable with the same name is a BAD idea.
<div id="game">
<button onClick="choose('rock')">Rock</button>
<button onClick="choose('paper')">Paper</button>
<button onClick="choose('scissors')">Scissors</button>
<div id="result"></div>
<br>
<br>
<button onClick="test()">DEBUG</button>
</div>
and
var user;
function choose(choice){
user = choice;
}
function test(click){
alert("You chose " + user);
}
Seems like a scoping issue. Try removing the var inside the function.