0

This is my Javascript code:

function getRandomCard(){
        randomCard = Math.floor(Math.random()*13)+1
    
        if (randomCard === 1){
            return 11
        }
        
        else if (11 <= randomCard <= 13){
            return 10   
        }
    
        else{
            return randomCard
        }
    }
    
 console.log(getRandomCard())

I have linked it to an HTML file with a button to call this function on getting clicked. Every time it is, it only returns 10 or 11. What could be wrong with my code?

Ravi Makwana
  • 2,782
  • 1
  • 29
  • 41
  • 3
    `11 <= randomCard <= 13` doesn't work in JavaScript, use `11 <= randomCard && randomCard <= 13` – Nick is tired Jun 29 '22 at 06:49
  • @NickstandswithUkraine It [works](https://stackoverflow.com/questions/4089284/why-does-0-5-3-return-true) BUT not in a way one would expect. OP needs to use the `&&` operator like you suggested. – Yousaf Jun 29 '22 at 06:58
  • @Yousaf That depends on your definition of work :p, but yes, I'm aware, I was the one that voted to close. – Nick is tired Jun 29 '22 at 07:07
  • @NickstandswithUkraine Your comment suggested that `11 <= randomCard <= 13` is syntactically wrong. Anyways, I didn't notice that you had voted to close the question. – Yousaf Jun 29 '22 at 07:09
  • @Yousaf What is actually happening in my code then? If you could please let me know. – Afif Mohammed Varikkodan Jun 30 '22 at 07:06
  • 1
    `11 <= randomCard <= 13` - this expression is evaluated from left to right. FIrst `11 <= randomCard` is evaluated. It will evaluate to a boolean value (either true or false). So the expression is reduced to `true <= 13` or `false <= 13`. As you are comparing boolean value with a number, boolean value is converted into a number (true -> 1, false -> 0). At the end you are comparing either `1 <= 13` or `0 <= 13` which evaluates to true. – Yousaf Jun 30 '22 at 07:12

1 Answers1

1

Not sure maybe your if condition is wrong..

function getRandomCard(){
        randomCard = Math.floor(Math.random()*13)+1
    
        if (randomCard === 1){
            return 11
        }
        
        else if (11 <= randomCard && randomCard <= 13){
            return 10   
        }
    
        else{
            return randomCard
        }
    }
    
 console.log(getRandomCard())
Ravi Makwana
  • 2,782
  • 1
  • 29
  • 41