Reputation: 41
I'm trying to solve a problem and I quote: "A game needs to be created in which the user attempts to guess a random whole number between 1 and 100. Upon Guessing, the game will tell the user if they need to go higher or lower. If the user guesses the number, the game will tell them they’re right, and how many attempts it took"
I'm trying to attempt this by having a webpage with a prompt asking for the guess, and then if loops deciding if the guess is the same, higher or lower than the random number. However! I've got the prompt to show up, but no matter what number it will always say the numbers correct! Please help!
Here's my html:
<!DOCTYPE html>
<html lang="en">
<script src="Assignment%20Task%202.js"></script>
<body>
PLAY THE GUESSING GAME:
Guess a number between 0 and 1000!
</body>
<br>
<button onclick= "Guessing_game()" >play</button>
<br>
<p>
You have guessed this many times:
</p>
<p id="num_guesses"></p>
</html>
here's my javascript:
var number = Math.floor(Math.random() * 1000) + 1;
var num_guesses = 1;
function Guessing_game() {
var guess;
guess = prompt("what is your guess?");
if (guess = number) {
alert("Good Job! You got the number correct!");
}
if (guess < number) {
num_guesses = +1;
alert("Bad luck! You need to guess lower");
}
if (guess > number) {
num_guesses = +1;
alert("Bad luck! You need to guess higher");
}
document.getElementById("num_guesses").innerHTML = num_guesses;
}
Upvotes: 2
Views: 74
Reputation: 29453
As others have pointed out, in javascript (and in many other languages):
=
is the assignment operatorBut the best operator to use (especially in javascript) is not ==
.
==
indicates that two values are equivalentInstead, the best operator to use is ===
:
===
indicates that two values are identical.In this case, this is, ideally, what you ought to be using in your script:
if (guess === number) {
[... CODE HERE...]
}
Upvotes: 0
Reputation: 3074
=
is assignment operator.
For e.g var a = "foo";
==
is used for value comparison.
For e.g
if(a == "foo") {
// Do something if above condition is true
}
===
is strict comparison, that means value and type should be same .
Upvotes: 0
Reputation: 5069
The problem is with your if (guess = number)
line of code.
Using guess = number
assigns the number to the guess variable here. If you want to check whether guess is equal to number use guess==number
in the if condition like:
if (guess == number)
For more information, you can read it out here.
Upvotes: 1