0

Im working through a quick blackjack game to learn some basics in javascript and I don't understand why my code isn't working correctly. Clearly something I don't understand about the fundamentals of JavaScript

const types = [
  "1",
  "2",
  "3",
  "4",
  "5",
  "6",
  "7",
  "8",
  "9",
  "10",
  "J",
  "Q",
  "K",
  "A"
];
const suite = ["Hearts", "Spades", "Clubs", "Diamonds"];
const draw = () => Math.floor(Math.random() * 52);
let cards = makeDeck(suite, types);
let score = 0;

//creates the card object
function Card(type, rank) {
  this.type = type;
  this.rank = rank;
}

//creates an array with every card
function makeDeck(suite, types) {
  let cards = [];
  let value = 0;
  for (let i = 0; i < suite.length; i++) {
    for (let j = 0; j < types.length; j++) {
      cards.push(new Card(types[j], suite[i]));
    }
  }

  return cards;
}


function determine(Card, score) {
  let test = 11;
  if (/^\d+$/.test(Card.type)) {
    test = parseInt(Card.type);
    console.log(test);
    return test;
  } else {
    if (Card.type === "J" || "Q" || "K") {
      test = 10;
      return test;
    } else {
      if (score > 11) {
        test = 2;
        return test;
      }
    }

    return test;
  }
}

function game() {
  let gameDeck = cards;
  let card1 = gameDeck[draw()];
  let card2 = gameDeck[draw()];
  let card3 = gameDeck[draw()];
  let card4 = gameDeck[draw()];
  let scorePlayer = determine(card1, score) + determine(card2, score);
  let scoreDealer = determine(card3, score) + determine(card4, score);

  console.log(scoreDealer);
  console.log(scorePlayer);
  console.log(card1, card2, card3, card4);
}


game();

So my concern is the determine function which seems to not work the way I intend it to. I have yet to implement a real scoring function but that shouldn't make a major difference at this point. Is there something incorrect with my usage of let and const?

  • In Javascript, this doesn't work the way you might hope: `if (Card.type === "J" || "Q" || "K") `. You need independent tests: `if (Card.type === "J" || Card.type === "Q" || Card.type === "K")` Another option is `if (["J", "Q", "K"].includes(Card.type)` – Mark Dec 11 '18 at 03:41

1 Answers1

1
if (Card.type === "J" || "Q" || "K") {
      test = 10;
      return test;
    }

This block is true always, irrespective of the value of "Card.type". Because when the Card.type is not equal to "J", javascript checks for if("Q") which is always true. Similarly if("K") is also true. All these are truthy values in Javascript. Javascript has 7 falsy conditions, except which all other conditions are true. Try this code snippet in your browser console.

    if("Q") {
        console.log("This statement is true always")
    }
Shiva
  • 543
  • 1
  • 6
  • 20