The Tempting but Wrong Way

This is a shuffle method you will run into in plenty of code snippets:

deck.sort(() => Math.random() - 0.5); 

It looks elegant. It's one line. But it is not a reliable shuffle. The sort() function is built to order things, not to randomize them, and a random comparison function breaks the consistency that sorting algorithms expect. Different JavaScript engines sort differently, so the result is not guaranteed to give every ordering an equal chance. For a card game, you want that guarantee.

The Right Way: Fisher-Yates Shuffle

The Fisher-Yates shuffle (also called Knuth shuffle) gives every possible arrangement equal probability. Here's how it works:

function shuffleDeck() { const suits = ['♠', '♥', '♦', '♣']; const ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']; const deck = []; for (let suit of suits) { for (let rank of ranks) { deck.push(rank + suit); } } for (let i = deck.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [deck[i], deck[j]] = [deck[j], deck[i]]; } return deck; } 

How It Works

Start at the last card. Pick a random position from the start up to and including the current position. Swap those two cards. Move to the previous card and repeat.

The loop walks backward through the deck. For each position, we generate a random index from zero to the current position. The swap happens using array destructuring. By the time we reach the front, every card has been placed randomly.

Provided your random number generator is good, Fisher-Yates gives every one of the 52! possible orderings exactly the same chance of appearing. That is the property you want from a deck.

Use this, not sort().