ocko
ocko

Reputation: 93

Quessing game by Object

I am trying to make simple guessing game by object method.I want to practice object method. Everything is working, except one condition. I want compare input with random num. I don't know why this condition ignore me. How can I fix it? Thank you


let game = {  
  quess: () => {
    const input = document.querySelector('.input').value
     return input
  },
  randomNumber: () => {
    //const x = Math.floor(Math.random() * 10) + 1
    const x = 3   // for testing
    return x
  },
  displayQuess: function() {
      const userNum = document.querySelector('.quess')
      return userNum.innerHTML = this.quess()
  },
 
  clearFields: function() {
    document.querySelector('.input').value = ''
  },
  result: function() {
     const output = document.querySelector('.output')
   
     const input = this.quess()
     const random = this.randomNumber()
     
     
     if(random === input) {         // this condition ignore me , why ? 
       output.innerHTML = ' Winner !!'
     } 

     if(input != random) {
       output.innerHTML = 'correct num was : ' + random
     }
  }
}

 const btn = document.querySelector('.btn')
 const output = document.querySelector('.output')
 const quesss = document.querySelector('.quesses')

 let quesses = 3

 btn.addEventListener('click', function() {
   //console.log( game.displayQuess())
      game.displayQuess()
      game.clearFields()
      game.result()

      quesses--
      quesss.innerHTML = quesses
      if(quesses < 1 ){
          output.style.color = 'red'
          output.innerHTML = 'game over'
          document.querySelector('.input').disabled = true;
          document.querySelector('.btn').disabled = true;
      }  
 })

Upvotes: 1

Views: 31

Answers (1)

Norman Breau
Norman Breau

Reputation: 2417

The === is a strict type equality check. It checks that both operands are of the same type and are equal. This is not passing the condition because you are comparing a number with a string. Even though they have the same value, they are of data types (a numeric type, and a text (string) type).

You can use == to do loose equality checks, which allows checking across different types, but it is better practice to use strict equality checks. So if you expect a number, it might be better to convert the string type to a number type

quess: () => {
    const input = document.querySelector('.input').value
     return parseFloat(input);
  },

Further Reading:

Upvotes: 1

Related Questions