-1

I'm a novice python programmer with 1 day of JS experience trying to make a blackjack text game. My code is supposed to take a card from the deck and place it into the player's hand. When I run the code, it says:

index.js:19 Uncaught TypeError: playerHand.push is not a function
    at firstHand (index.js:19)
    at index.js:30

The error is at the 19th line which is the line where the player is drawn his second card. Can someone help me fix my code? I'd appreciate it.

Here's the whole JS code:

// initialize the deck of cards
let deck = [
    2,3,4,5,6,7,8,9,10,10,10,10,11,
    2,3,4,5,6,7,8,9,10,10,10,10,11,
    2,3,4,5,6,7,8,9,10,10,10,10,11,
    2,3,4,5,6,7,8,9,10,10,10,10,11
];
// shuffle the deck of cards
deck = deck.sort(() => Math.random() - 0.5);

function firstHand(){
    //initializing the hands as empty
    let playerHand = [];
    let dealerHand = [];

    //alternate drawing 2 cards for player and dealer
    playerHand = playerHand.push(deck.pop());
    dealerHand = dealerHand.push(deck.pop());
    playerHand = playerHand.push(deck.pop());
    dealerHand = dealerHand.push(deck.pop());

    //define the total sum in each players hand
    let playerSum = playerHand.reduce((a, b) => a + b, 0);

    //print the player's hand with first two cards in the hand and the player's total
    console.log(`Your hand: ${playerHand} = ${playerSum}`); //for example: "Your hand: [2, 6] = 8"

}

firstHand()
Jukku
  • 33
  • 4
  • Why are you assigning to `playerHand` or `dealerHand` (e.g. in `playerHand = playerHand.push(deck.pop());`)? – Sebastian Simon Apr 25 '21 at 05:51
  • 2
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+typeerror+after+push) of [Why do I get “.push not a function”?](https://stackoverflow.com/q/48394192/4642212). – Sebastian Simon Apr 25 '21 at 05:52
  • Do not shuffle the array like that! See: https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – RoToRa Apr 25 '21 at 06:42

2 Answers2

1

playerHand.push(deck.pop()) will return an integer and you are assigning that to playerHand. As a result, it will make playerHand also an integer. So, replace these lines:

    playerHand = playerHand.push(deck.pop());
    dealerHand = dealerHand.push(deck.pop());
    playerHand = playerHand.push(deck.pop());
    dealerHand = dealerHand.push(deck.pop());

with:

    playerHand.push(deck.pop());
    dealerHand.push(deck.pop());
    playerHand.push(deck.pop());
    dealerHand.push(deck.pop());
Back2Lobby
  • 534
  • 6
  • 12
1

Push method returns an integer . this is why the second time , you use push method with playerHand a bug occurs , playerHand is no longer an array but a simple integer . So you need to not assign the result of playerHand.push(deck.pop()) to playerHand . Try this one :

playerHand.push(deck.pop());
dealerHand.push(deck.pop());
playerHand.push(deck.pop());
dealerHand.push(deck.pop());
GNETO DOMINIQUE
  • 628
  • 10
  • 19