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 ) ;
Enter fullscreen mode
Exit fullscreen mode
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 .…