Coding A Card Deck In JavaScript

Written by
Published on
Modified on

In this post, I will be going over how to build a deck of cards in JavaScript, that can be used for future projects or future games, such as this JavaScript Blackjack  game. This is a super quick implementation, and can be done in less than 100 lines of code. I will be implementing as many card related functions/features as I can, such as shuffling a deck, grabbing a card from the top or bottom and creating a new deck of cards.

If you are 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.

Project: Deck of cards
Language: JavaScript
Estimated Completion: 30 minutes

Overview

A deck of traditional 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. The deck will consist of an Array of objects with a function to render each card graphically.

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 our 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()
{
	var deck = new Array();

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

	return deck;
}

This function will populate the deck array with 52 card objects, 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 (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;
	}
}

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.

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> with a particular class specifying its suit. It will use the following sprite image.

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

A cleaner way render the cards (at least to me) 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='?';
		else if (deck[i].Suit == 'spades')
		icon = '?';
		else if (deck[i].Suit == 'diamonds')
		icon = '?';
		else
		icon = '?';

		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
?

Putting it together

Now that we have all of the helper and primary functions setup, we can see how it all comes together.

Creating a new deck

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);

Download full source code

Comments & Questions

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?
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
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!
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

Add a comment

Send me your weekly newsletter filled with awesome ideas
Post