DEV Community

Karen Molina
Karen Molina

Posted on

Guess the Number


It's me!

Remember my first post, Guess the Number with Python? Well, I decided to do the same exercise, now with Javascript.

Let's go.... hands on code!

const prompt = require("prompt-sync")({ sigint: true });
let guessesTaken = 0;

console.log("Hola crayola.... ¿Cómo te llamas?");
const name = prompt();

let number = Math.floor(Math.random() * 10) + 1;
console.log(`Hola ${name}.... Adivina el número en el que estoy pensando`);

while (guessesTaken < 6) {
  console.log("Dime un número");
  guess = prompt();
  guessesTaken = guessesTaken + 1;
  if( guess < number){
      console.log("Es un número más alto")
  } else if (guess > number) {
      console.log("Es un número menor")
  }else if (guess == number) {
    console.log(`Felicidades ${name}. ${number} es el número!!`);
  } else {
    console.log(`uy no ${name}, estaba pensando en ${number}`);
Enter fullscreen mode Exit fullscreen mode

At a first instance, we need to install prompt-sync node module to use it. Once time we have benn instaled the module, we can continue to code.

We have three variables, one of them we use to create a record or a counter as how many times we try to guess the number. The second variable are use to save the user name.
Then, we have a third variable, called number that we use the method math to get a randomly number between 1 to 10. And we have two console.log to create an interaction with the user, get the name and a number.

Next, we create a while loop. A while its a loop that execute the core over and over again. We create a loop that the conditional must be menor that 6. In that case, 6 is the number that the user got to try to guess.

Inside a while loop, we have a console.log and a varibale called guess. Then we have trhee conditional sentences. The first compare if the guess is menor that number. And the second if, gonna make a comparison if guess is mayor that number. Then we have anocher conditional that compare the guess and number varibales when the user knows the right number. In this block to code, we must return a succeful message as string, and we can brake the loop.

Finally, the four conditional statement will be retured an error message when the user fails the game.

Discussion (0)