Something With this Code

I wanted to create a computer number guessing game, but it always outputs incorrect in chrome. Why?

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>
1 Like

Hi @ramutis! :slight_smile:

It seems like the code pasted only shows the first 3 lines of the document.

Try pasting the code again.

1 Like

how to make it show full?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
   <script>
    for(let i=0; i <= 6; i++) {
        const random_number = Math.floor(Math.random()*2);
        console.log(random_number)
        let guess = prompt("Enter a number from 0 to 10")
        if(guess === random_number) {
            console.log("Your guess is correct!");
            break;
            
        }
        else if(guess !== random_number){
            console.log("Your guess is incorrect!")
        }   
    }
    </script> 
</body>
</html>

Look at what it’s logging for random_number. Your prompt asks for a number from 1-10 but the random_number generator you wrote might not be doing what you think it does.

It doesn’t work either way. Please try it out.

The javascript works ok! (note: i took the prompt out to check it in the my text editor). You might want to add a ; at the end of those statements though.

here’s on a browser (with your code)

why both are incorrect?

0 and 1 are incorrect. But either of them should be.

To get to the bottom of this, you should also log what the prompt input is, and also console.log(guess === random_number).

You’ll be surprised! Why does this happen?

Try these

console.log(typeof random_number)
console.log(typeof guess)

@ramutis you’ll notice that the types don’t match! If you want things to be strictly equivalent (that’s what the 3 = are for) then you should add an operation that converts the types to match.

Got it. Thanks. I’ll know from now on.

1 Like

You could’ve also written guess == random_number to avoid conversion. But this is not necessarily a good habit to have.

@ramutis 2 = signs ignore type, while 3 = require a perfect match.