How To Code Blackjack Using JavaScript

Today I will be building a small BlackJack game in pure JavaScript in the hopes that you out there reading this can use it as a frame to build something much bigger. And if you're a beginner in the programming world, than perhaps this tutorial will help you get a much better idea of how function, objects and DOM manipulation works in JS.

While the following post won't be using any incredibly advanced topics in JavaScript, it is rather involved in what needs to go into a Blackjack game. I recommend the following book Web Design with HTML, CSS, JavaScript and jQuery for anybody that's somewhat relatively new to JavaScript and web development in general.

Separating the UI

In order to modularize the code more, I will be splitting each function into 2 parts. One will deal with data manipulation and logic, and the other will perform the UI functions, such as drawing the cards onto the screen and such.

BlackJack game rules

Most people should be familiar with the concept of the game BlackJack. But if not, here is a quick overview. Essentially, players are dealt a starting hand of 2 cards with the hopes of getting to the magical number of 21, or to get as close to 21 as possible. If a player gets 21 on his initial hand, it is called a "blackjack" or a "natural". The player wins, unless the house reaches blackjack as well. The other ways to win are to hold a higher sum of cards at the end of the play than the house, or to have the house go over 21.

The game area

How To Code Black Jack Using JavaScript

I'm going to be making as simple a game board as I can think of, in order to avoid an excessive amount of UI rendering code and such. And to keep everything focused on the logic as much as I can.

<div class="game">
    <input type="button" class="btn" value="start" onclick="start()" />
    <input type="button" class="btn" value="hit me" onclick="hitMe()" />
    <input type="button" class="btn" value="stay" onclick="stay()" />

    <div id="players" class="players">

    <div id="deck" class="deck">
        <div class="card" id="deckcount">52</div>
        <div class="status" id="status"></div>

    <div class="clear"></div>

Build your deck

The first thing we're going to need in order to make our card game, are cards. And if you don't know how to make them, feel free to check out my post on that process. But essentially, we'll be making a Deck array with 52 Card objects.

    var suits = ["Spades", "Hearts", "Diamonds", "Clubs"];
    var values = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];
    var deck = new Array();

    function createDeck()
        deck = new Array();
        for (var i = 0 ; i < values.length; i++)
            for(var x = 0; x < suits.length; x++)
                var weight = parseInt(values[i]);
                if (values[i] == "J" || values[i] == "Q" || values[i] == "K")
                    weight = 10;
                if (values[i] == "A")
                    weight = 11;
                var card = { Value: values[i], Suit: suits[x], Weight: weight };

The beauty of the Array is that it is stack by its nature. So we can pop cards off the top with the built in Array pop() method.


A very quick shuffle algorithm.

    function shuffle()
        // for 1000 turns
        // switch the values of two random cards
        for (var i = 0; i < 1000; i++)
            var location1 = Math.floor((Math.random() * deck.length));
            var location2 = Math.floor((Math.random() * deck.length));
            var tmp = deck[location1];

            deck[location1] = deck[location2];
            deck[location2] = tmp;

Create the players

For this example, I'll be working with 2 players only. The "House" and yourself. There are a few things that we'll want to keep track of for each player, such as an "Id" and their current "Score". An array for the players current Hand will also be added on to the player object.

    var players = new Array();
    function createPlayers(num)
        players = new Array();
        for(var i = 1; i <= num; i++)
            var hand = new Array();
            var player = { Name: 'Player ' + i, ID: i, Points: 0, Hand: hand };

That was the logic portion. And next up is the UI portion

        function createPlayersUI()
            document.getElementById('players').innerHTML = '';
            for(var i = 0; i < players.length; i++)
                var div_player = document.createElement('div');
                var div_playerid = document.createElement('div');
                var div_hand = document.createElement('div');
                var div_points = document.createElement('div');

                div_points.className = 'points';
       = 'points_' + i;
       = 'player_' + i;
                div_player.className = 'player';
       = 'hand_' + i;

                div_playerid.innerHTML = players[i].ID;

Start the game

Now we're ready to start the game. You can use the following function to begin the game and create all of the required objects.

        function startblackjack()
            document.getElementById('btnStart').value = 'Restart';
            // deal 2 cards to every player object
            currentPlayer = 0;
            document.getElementById('player_' + currentPlayer).classList.add('active');

Deal the hand

As mentioned above, the game starts with a quick shuffle. And then the hands are dealt.

    function dealHands()
        // alternate handing cards to each player
        // 2 cards each
        for(var i = 0; i < 2; i++)
            for (var x = 0; x < players.length; x++)
                var card = deck.pop();
                renderCard(card, x);


We'll be using the handy pop() method for this one, which returns to us the top most item in the stack. We'll push the cards to each players hands and then render the cards.

Render the cards

This is the UI portion of card dealing. Once a card is dealt to a particular it will need to be added to their 'hand'.

    function renderCard(card, player)
        var hand = document.getElementById('hand_' + player);

    function getCardUI(card)
        var el = document.createElement('div');
        el.className = 'card';
        el.innerHTML = card.Suit + ' ' + card.Value;
        return el;

Hit me

Now we're ready to start the game. This will pop a Card right out of our stack and will sum the Card value to the current users Total score.

    var currentPlayer = 0;
    function hitMe()
        // pop a card from the deck to the current player
        // check if current player new points are over 21
        var card = deck.pop();
        renderCard(card, currentPlayer);

    function check()
        if (players[currentPlayer].Points > 21)
            document.getElementById('status').innerHTML = 'Player: ' + players[currentPlayer].ID + ' LOST';

The check() method will run after each card is dealt in order to determine if the player has lost the game.


If a player chooses to keep his hand, then the stay method will check if there are any more players in action, and if so, will transfer control over to them by updating the currentPlayer variable. If however, there are no players left, then the end method is called and points will be tallied up.

    function stay()
        // move on to next player, if any
        if (currentPlayer != players.length-1) {
            document.getElementById('player_' + currentPlayer).classList.remove('active');
            currentPlayer += 1;
            document.getElementById('player_' + currentPlayer).classList.add('active');

        else {

    function end()
        var winner = -1;
        var score = 0;

        for(var i = 0; i < players.length; i++)
            if (players[i].Points > score && players[i].Points < 22)
                winner = i;

            score = players[i].Points;

        document.getElementById('status').innerHTML = 'Winner: Player ' + players[winner].ID;

A winner?

And as the game is so aptly titled, ye who gets closer to 21 without going over will be the victor. The gameplay logic itself is very straightforward and no more than a hundred lines of code. UI however is another story, which is why I broke the code up into elements of both. Feel free to keep the logic and update the UI to your liking. Down below is the game in action. Again, it's a very rudimentary example, but it gives a general idea of how a few method calls and objects can make for a quick card game.

In Action



Full Source

Walter G. is a software engineer, startup co-founder, former CTO of several tech companies and currently teaches programming for a coding bootcamp. He has been blogging for the past 5 years and is an avid BMX rider, bio-hacker and performance enthusiast.
Buy me a coffeeBuy me a coffee
If you read this far, then I hope you enjoyed this post and found it useful! Consider adding to my daily coffee funds to continue to provide better and more helpful articles in the future!
Maybe later

Add a comment

Send me your weekly newsletter filled with awesome ideas
Post comment