0% found this document useful (0 votes)
105 views3 pages

JavaScript While Loops Explained

The document describes how to use a while loop to guess a randomly generated number. It will generate a random number between 1-6 and assign it to the variable x. It then compares x to the user's input number. The loop will repeat, incrementing the guesses variable, until it matches the input number. Once matched, it will alert how many guesses it took to get the right number.

Uploaded by

Ania Neal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
105 views3 pages

JavaScript While Loops Explained

The document describes how to use a while loop to guess a randomly generated number. It will generate a random number between 1-6 and assign it to the variable x. It then compares x to the user's input number. The loop will repeat, incrementing the guesses variable, until it matches the input number. Once matched, it will alert how many guesses it took to get the right number.

Uploaded by

Ania Neal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

While Loops: whileloops.

html
!
!

<!doctype html>
<html>
<head>
<title>Learning Javascript</title>

<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />



</head>

<body>

<p>How many fingers are you holding up?</p>

<input id="myNumber" />

<button id="guess">Guess!</button>


<script type="text/javascript">


document.getElementById("guess").onclick=function() {

var gotit=false; var guesses=1; var x;

while (gotit==false) {

x=Math.random();

x=6*x;

x=Math.floor(x);

if (document.getElementById("myNumber").value==x) {

gotit=true;

} else {

guesses++;

}

}

alert("Got it! It was a "+x+". It only took me "+guesses+"
guesses!");

}


</script>

</body>
</html>

You might also like