## A number guessing game in Javascript.

One sure way to tell when you’re making progress in learning a new programming language is being able to create a simple number guessing game. Here’s my Javascript version. It generates a random number between 1 and 100 and tells you if your guesses are too high or too low. Simple.

<!DOCTYPE html>
<html>
<body>
<p id=”demo1″>Last guess: </p>
<p id=”demo2″></p>
<button onclick=”myFunction(guess)”>Submit</button>
<script>
var x=Math.floor((Math.random()*100)+1);
function myFunction(guess)
{
document.getElementById(“demo1”).innerHTML=’Last guess: ‘+guess.value;
if (guess.value==x)
{
document.getElementById(“demo2”).innerHTML=’You guessed it!’;
}
else if (guess.value<x)
{
document.getElementById(“demo2”).innerHTML=’Too low.’;
}
else
{
document.getElementById(“demo2”).innerHTML=’Too high.’;
}
}
</script>
</body>
</html>

I couldn’t resist modifying the script to make it look like you’re can guess the correct number on the first try. Try it on your friends and make them think they’re psychic. Better hope they’re still your friends afterwards.

<!DOCTYPE html>
<html>
<body>
<p id=”demo1″>Last guess: </p>
<p id=”demo2″></p>
<button onclick=”myFunction(guess)”>Submit</button>
<script>
function myFunction(guess)
{
document.getElementById(“demo1”).innerHTML=’Last guess: ‘ +guess.value;
document.getElementById(“demo2”).innerHTML=’You guessed it on the very first try! You must be a psychic!’;
}
</script>
</body>
</html>

Have much fun.