DEV Community

The Vik
The Vik

Posted on

How to make a guessing game in JavaScript

So in this tutorial we are going to make a simple number guessing game which will generate a random number between 0 - 10 ( you can set the max number to whatever you want ) and then if the user guess the correct number it will show or else wrong answer will be shown.

Join my discord server and talk with many programmers in there
- First 25 people to join will get special role
<input type="text" placeholder="Your Guess" id="inputfield">
<button id="inputsubmit">Submit</button>
<!-- The results will be shown here -->
<div id="result"></div>
Enter fullscreen mode Exit fullscreen mode
const inputfield = document.getElementById('inputfield')
const inputsubmit = document.getElementById('inputsubmit')
const result = document.getElementById('result')

const random = Math.floor(Math.random() * 10)

inputsubmit.addEventListener('click', () => {
    const inputvalue = inputfield.value
    const input = parseInt(inputvalue)
    if ( random === input ) {
        result.innerText = "Correct answer"
    } else {
        result.innerText = "Wrong answer"
    }
})
Enter fullscreen mode Exit fullscreen mode
Play the upgraded number guessing game made by me

ok so in html we only make a input field for guessing the number, a button to submit that guess and a div to show the results.

in javascript we are getting all of those things in html using getElementById and then we generating a random number using Math.random() and multiplying it by 10 ( this is the max number change it to whatever you want.

now we adding a event listener to our button then making a const named inputvalue and passing inputfield.value in it then we are using parseInt to get the integer value of inputvalue.
now we just using a if statement so if random === input then we will write "Correct Answer" in our result div and else we will write "Wrong Answer" in our result div.

THANKS for reading this much :D

Discussion (0)