0

I don't understand why my code is not working. I am teaching myself JavaScript and here's the code I used. It is for a version of the blackjack game. I want the getRandomCard() function to return a number between 1 and 13. However, I want it to return 11 when the randomNumber is 1 and for it to return 10 when the randomNumbers are 11, 12 and 13.

Why isn't it working?

function getRandomCard() {
    let randomNumber = Math.floor(Math.random() *13) + 1
    if (randomNumber = 1) {
        return 11
    } else if (randomNumber = 11, 12, 13 ) {
        return 10
    } else {
        return randomNumber
    }
}

console.log(getRandomCard())

Here is what I did. But when I run it, all it returns is the number 11.

Your help would be appreciated.

lisa p.
  • 2,138
  • 21
  • 36
  • To compare numbers, use `==` instead of `=`, i.e. `if(randomNumber == 1)`. See [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness). To compare multiple number, use [||](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR) operator. i.e. `else if(randomNumber == 11 || randomNumber == 12 || randomNumber ==13)` – Ricky Mo Nov 22 '22 at 06:26

1 Answers1

1

There are two mistakes:

  1. if (randomNumber = 1) {

    This = is an assignment operator. If you wat to compare you need to use either == or ===

  2. else if (randomNumber = 11, 12, 13 ) {

    This should be something like

    randomNumber == 11 || randomNumber == 12 || randomNumber == 12

    or you can use includes function to check if the number is in array. Like this:

    [11, 12, 13].includes(randomNumber)

function getRandomCard() {
    let randomNumber = Math.floor(Math.random() *13) + 1
    if (randomNumber == 1) {
        return 11
    } else if ([11, 12, 13].includes(randomNumber)) {
        return 10
    } else {
        return randomNumber
    }
}
console.log(getRandomCard());
subodhkalika
  • 1,964
  • 1
  • 9
  • 15