// Get a random index ranging from 0 (inclusive) to max (exclusive).
const getRandomIndex = (max) => Math.floor(Math.random() * max);
// Shuffle an array of cards
const shuffleCards = (cards) => {
// Loop over the card deck array once
for (let currentIndex = 0; currentIndex < cards.length; currentIndex += 1) {
// Select a random index in the deck
const randomIndex = getRandomIndex(cards.length);
// Select the card that corresponds to randomIndex
const randomCard = cards[randomIndex];
// Select the card that corresponds to currentIndex
const currentCard = cards[currentIndex];
// Swap positions of randomCard and currentCard in the deck
cards[currentIndex] = randomCard;
cards[randomIndex] = currentCard;
// Return the shuffled deck
// Initialise an empty deck array
// Initialise an array of the 4 suits in our deck. We will loop over this array.
const suits = ["hearts", "diamonds", "clubs", "spades"];
// Loop over the suits array
for (let suitIndex = 0; suitIndex < suits.length; suitIndex += 1) {
// Store the current suit in a variable
const currentSuit = suits[suitIndex];
// Loop from 1 to 13 to create all cards for a given suit
// Notice rankCounter starts at 1 and not 0, and ends at 13 and not 12.
// This is an example of a loop without an array.
for (let rankCounter = 1; rankCounter <= 13; rankCounter += 1) {
// By default, the card name is the same as rankCounter
let cardName = `${rankCounter}`;
// If rank is 1, 11, 12, or 13, set cardName to the ace or face card's name
} else if (cardName === "11") {
} else if (cardName === "12") {
} else if (cardName === "13") {
// Create a new card with the current name, suit, and rank
// Add the new card to the deck
// Return the completed card deck
const deck = shuffleCards(makeDeck());
// Use let for player1Card object because player1Card will be reassigned
const player1Button = document.createElement("button");
player1Button.innerText = "Player 1 Draw";
document.body.appendChild(player1Button);
const player2Button = document.createElement("button");
player2Button.innerText = "Player 2 Draw";
document.body.appendChild(player2Button);
// Create game info div as global value
// fill game info div with starting instructions
const gameInfo = document.createElement("div");
gameInfo.innerText = "Its player 1 turn. Click to draw a card!";
document.body.appendChild(gameInfo);
// Create a helper function for output to abstract complexity
// of DOM manipulation away from game logic
const output = (message) => {
gameInfo.innerText = message;
// Add an event listener on player 1's button to draw card and switch
player1Button.addEventListener("click", () => {
player1Card = deck.pop();
// Add event listener on player 2's button to draw card and determine winner
// Switch back to player 1's turn to repeat game
player2Button.addEventListener("click", () => {
const player2Card = deck.pop();
if (player1Card.rank > player2Card.rank) {
} else if (player1Card.rank < player2Card.rank) {