Coding A Card Deck In JavaScript

Written by
Published on
Modified on
Category

In this post, I will be going over how to build a deck of cards in JavaScript. The deck can be used for future projects or future games, such as this JavaScript Blackjack  game which I made a while back.

This is a super quick implementation, and can typically be done with less than 100 lines of code. I will be implementing other card related functions/features as well, such as shuffling the deck, grabbing a card from the top or bottom and creating multiple decks of cards.

If you are brand new to JavaScript, then I recommend the following book Web Design with HTML, CSS, JavaScript and jQuery, which can get you up and running pretty quickly with JavaScript.

Overview

A traditional deck of playing cards is composed of 4 sets of 13 sequential numbered cards. A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, and K. Each card in the set belongs to a particular suit: Hearts, Spades, Clubs and Diamonds. In total that consists of 52 different cards.

The deck in this tutorial will consist of an Array of card objects which we will create dynamically.

Variable declarations

Declare the following variables in order to get started.

var suits = ["spades", "diamonds", "clubs", "hearts"];
var values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];

The variable suits is an array of card suites that we will use as a lookup table. And the 2nd variable values will hold all the possible values that a card can have.

Create The Deck

In order to create the deck, we're going to pair up each suit from the array above, with each possible value also from the array declared above. We're going to create a new card Object with the corresponding value and suit and that object will be added that to the deck array.

The getDeck() function will return this brand new deck to the caller.

function getDeck()
{
	let deck = new Array();

	for(let i = 0; i < suits.length; i++)
	{
		for(let x = 0; x < values.length; x++)
		{
			let card = {Value: values[x], Suit: suits[i]};
			deck.push(card);
		}
	}

	return deck;
}

This function will populate the deck array with 52 card objects in total, which will resemble the following at the end.

var deck = [{Value: 'A', Suit: 'Spades'}, {Value: 'A', Suit: 'Diamonds'}, {Value: 'A', Suit: 'Clubs'}...]

Shuffling the card deck

Next up we need a function to shuffle the deck. For this, we will need to come up with a shuffling algorithm. We are going to pick 2 random locations on the deck, and then switch their values around. We will be doing this about 1000 times per shuffle, which should be good enough to generate a seemingly random deck.

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

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

At this point, the deck array should contain 52 objects in a random order. But it's funner to see it than to hear me talk about it, so my next trick, I'm going to make the cards appear.

The render function will iterate through each card object in the deck Array and will create the DOM elements on the webpage using the createElement function.

All of the card elements will get added to a primary <div id="deck"> root node on the page.

function renderDeck(deck)
{
      document.getElementById("deck").innerHTML = "";

	for(let i = 0; i < deck.length; i++)
	{
		let card = document.createElement("div");
		let value = document.createElement("div");
		let suit = document.createElement("div");
		card.className = "card";
		value.className = "value";
		suit.className = "suit " + deck[i].Suit;

		value.innerHTML = deck[i].Value;
		card.appendChild(value);
		card.appendChild(suit);

		document.getElementById("deck").appendChild(card);
	}
}

For this example, our card will simply be a <div> element with a particular class specifying its suit. It will use the following sprite image to actually render the proper suit.

The following CSS will render the design accordingly.

.deck .card
{
    border: solid 1px #aaa;
    border-radius: 9px;
    width: 95px;
    height: 150px;
    float:left;
    background-color: white;
    padding: 3px 3px 3px 3px;
    margin: 5px;
}

.card2
{
    width: 50px;
    padding: 10px;
    border: solid 1px #808080;
    background-color: white;
    display: inline-block;
    border-radius: 10px;
    font-size: 22px;
    text-align: center;
    margin: 3px;
    border:solid 3px;
}

.card .value{
    font-size:15pt;
    font-family: sans-serif;
}

.card .suit
{
	background-image: url('https://www.thatsoftwaredude.com/images/post/0f631eeb-6c4a-4bfd-9f86-e0a08ae8584b.png');
	height: 100px;
	width: 90px;
}

.card .diamonds
{
	background-position-y: 100px;
}

.card .hearts
{
	background-position-x: 90px;
}

.card .clubs
{
	background-position-x:90px;
	background-position-y:100px;
}

And you can use the following standard HTML boilerplate as well.

<html>
<head>
    <link rel="stylesheet" href="main.css">
    <script type="text/javascript" src="main.js"></script>
</head>

<body>
    <div class="deck">
        <h1>A Deck of Cards</h1>

        <a href="javascript:void(0)" class="btn" onclick="shuffle()">Shuffle</a>
        <div id="deck"></div>
    </div>
</body>
</html>

At this point, we have the functions to create a new deck of cards, shuffle them, and draw them out onto the screen. It looks something like the following.

2
4
K
J
2
Q
K
3
5
9
6
5
8
6
K
A
7
10
A
4
4
2
Q
9
8
10
J
9
8
9
10
7
3
4
8
Q
5
3
Q
A
J
3
A
2
10
6
K
7
7
J
6
5

Version 2: Rendering

Another way to render the cards is a method that I used in my blackjack game, in which I use HTML entities instead of images.

 function renderDeck(deck)
{
	document.getElementById('deck').innerHTML = '';

	for(var i = 0; i < deck.length; i++)
	{
		var card = document.createElement("div");
		var icon = '';
		if (deck[i].Suit == 'hearts')
		icon='&hearts';
		else if (deck[i].Suit == 'spades')
		icon = '&spades';
		else if (deck[i].Suit == 'diamonds')
		icon = '&diams';
		else
		icon = '&clubs';

		card.innerHTML = deck[i].Value + '' + icon;
		card.className = 'card';
	document.getElementById("deck").appendChild(card);
	}
}
6
?
K
?
A
?
9
?
Q
?
7
?
7
?
10
?
4
?
3
?
10
?
5
?
A
?
9
?
6
?
10
?
Q
?
4
?
Q
?
K
?
2
?
7
?
6
?
7
?
Q
?
6
?
3
?
3
?
2
?
2
?
A
?
4
?
5
?
8
?
J
?
5
?
8
?
3
?
A
?
10
?
8
?
8
?
J
?
K
?
5
?
J
?
4
?
9
?
J
?
2
?
9
?
K
?
2
?
4
?
K
?
J
?
2
?
Q
?
K
?
3
?
5
?
9
?
6
?
5
?
8
?
6
?
K
?
A
?
7
?
10
?
A
?
4
?
4
?
2
?
Q
?
9
?
8
?
10
?
J
?
9
?
8
?
9
?
10
?
7
?
3
?
4
?
8
?
Q
?
5
?
3
?
Q
?
A
?
J
?
3
?
A
?
2
?
10
?
6
?
K
?
7
?
7
?
J
?
6
?
5
?

Creating multiple decks

The getDeck() function created above will return a brand new 52-card deck whenever you need one. You can store that in a local variable (or global) depending on your project.

var deck1 = getDeck();
var deck2 = getDeck();

Once the decks are created they can be passed into the remaining helper functions as needed.

var deck1 = getDeck();
shuffle(deck1);
renderDeck(deck1);

Now that the decks are created, we can work at dealing cards out.

Deal a card

Once shuffled, most decks are dealt from the top down, like a stack. And that means that we can levarage the Array's pop() method in order to deal cards.

function dealCard(deck){
    return deck.pop();
}

let card = dealCard(deck1);
console.log(card);

The pop() method in JavaScript will remove the last item added to an Array and will return that item back to the caller, which is the exact scenario we have here.

Full source and downloads

Download full source code

Fork on Codepen.io

Walter Guevara is a software engineer, startup founder and currently teaches programming for a coding bootcamp. He is currently building things that don't yet exist.

Comments

M
Mads Bøtker Andersen
10/23/2017 11:24:00 AM
Thanks for this! It helped me get started on a small (potentially, big and fun) project! I Have run into a problem where the cards render twice.. which is weird.. :D
Walt
10/23/2017 8:45:11 PM
Many thanks! If you have any questions on it, feel free to shoot me a message and I'll gladly help out!
c
chris
11/28/2018 3:33:23 AM
can you send me the source code?
J
Jourdan
3/7/2021 5:28:46 AM
Walt, this is random but I am attempting to build a deck for a school project and have hit a major wall!! If you are feeling generous would love some help! [email protected]
k
kaye
1/22/2018 11:18:01 AM
what do I do if I need 4 decks?
Walt
1/24/2018 11:58:23 PM
Hey there Kaye!

You can definitely do it without too much extra effort. The getDeck() function returns a whole deck, so essentially you can keep calling it for as many decks as you may need.


var deck1 = getDeck();
var deck2 = getDeck();

And if you are going to do that, then you should definitely pass in the 'deck' object that you are targeting to the shuffle() and to the render methods().

The code will be updated to reflect that to give better clarity!

I
Ivan
8/22/2018 4:52:45 AM
In the deck code shown here you have array outside the function and no return on deck, comparing that the one that you have in the deck tutorial. Also When i put the function in the console i have no results.
Walt
10/31/2018 10:40:18 PM
Both are slightly different implementations!
B
Bob
10/22/2018 6:41:46 PM
Hey! I appreciate the code you shared. It is really helpful. Do you happen to have the css or html document so I know or can see how the cards were created?
Walt
10/22/2018 8:51:20 PM
Hey there Bob, thanks for the kind words. If you check at the bottom of the post, I have the source zipped up and ready to download for both versions of the code!
J
11/1/2018 8:10:13 AM
Walter, thank you for this. I was able to extend your examples and images for each card using their unicode values. Seemingly all 52+ cards are available. https://en.wikipedia.org/wiki/Playing_cards_in_Unicode I've implemented it for a simple addition game here: http://thejoshdean.com/citc-2375/lab6/
Walt
10/23/2019 10:15:44 AM
Many thanks for the words Josh! And excellent! Did not know all 52 cards were available! ha!
H
HARSH
2/15/2019 9:26:02 PM
How to sort deck of playing card in series in javascript
R
Rolf
7/9/2021 12:34:50 AM
You can add a new variable (e.g. strength) to the card object, then sort on this variable: In getDeck() for(var x = 0; x < cards.length; x++) { let strenght = x*4+i; let card = {Value: cards[x], Suit: suits[i], Strenght: strenght}; deck.push(card); } In renderDeck() deck.sort(function (a, b) {return a.Strenght - b.Strenght;});
A
Artem
12/26/2019 6:27:44 AM
const SUITS = ['?', '?', '?', '?']; const RANKS = ['6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']; const DECK = SUITS.map((suit) => RANKS.map((rank) => ({ rank, suit }))).flat(1);
Walt
12/31/2019 12:30:51 PM
That's some clean and concise code 👍 Many thanks for the addition!
C
Cyril
9/19/2021 9:48:11 AM
Thanks for simple code. How can you display in the HTML DOM Element?
S
Sam
2/11/2020 3:25:04 AM
How can i get a deck one by one?
Walter
2/11/2020 3:55:42 AM
Thank you for the question and for checking out the post. You can set a variable to the getDeck() function, as the function returns a brand new array. var deck1 = getDeck(); var deck2 = getDeck() would give you 2 different decks.
S
Steve
3/26/2020 7:38:35 AM
Hey. Why bother "shuffling" the deck when you can just get the decks current length. From there, generate a random number between 0 and length - 1 and do an Array.prototype.splice() on the deck? Cheers Steve
M
Martin Ransome
5/1/2020 3:01:55 AM
Hi Walter, Excellent tutorial man. I've been looking for something to create a card game and I think I have found it, Keep up the excellent work man. Good Job.
M
5/2/2020 3:43:55 PM
Code a dungeon themed card game! https://morganpage.teachable.com/p/practise-modern-javascript-by-coding-a-card-game/?product_id=1834511&coupon_code=TWENTYFIVEOFF
C
5/29/2020 2:16:24 AM
Playing a Card Game is always a Fun and enjoyable. Thanks for sharing this detail.
Walter
5/29/2020 5:08:42 PM
Many thanks for the words. Glad you enjoyed it!
J
Josh
6/9/2020 2:29:21 PM
Any way we can use jokers too?
S
Saymon
8/3/2020 3:45:38 PM
Hello, nice tutorial many thank You for creating clear and practical instructions. Can You give a tip how to add API (https://deckofcardsapi.com/) instead of creating own deck? Sorry If my question is little weird, but i'm new to the javascript. Thanks for your response
b
brahmaji
2/6/2021 12:17:04 PM
you are clever in rendering image, thanks for the idea
T
3/8/2021 5:09:56 AM
Such an amazing article.Thank you so much to share coding tips with us. It's really helpful to me in coding. Keep us updating.

Developer Poll 🐱‍💻

Q:

Add a comment

Send me your weekly newsletter filled with awesome ideas
Post