javascriptfunctionloops

function for shuffling a deck of cards js

I'm trying to build a Black Jack game and moving forward to a function where it is supposed to shuffle the cards, I was struggling a bit just to make a proper 'shuffle' and ended up looking online. I did find some code that does what I want, but there is no reference to what it does exactly, could someone help?

``````const shuffleDeck = () => {
for (let i = 0; i < deck.length; i++) {
let shuffle = Math.floor(Math.random() * (deck.length));
let temp = deck[i];
// here it assigns the iterated elements to newly created temp.
deck[i] = deck[shuffle];
// here uses the shuffle variable on the iterated deck[i]?
deck[shuffle] = temp;
// assigns the shuffled deck to temp? What does temp do after??
}
};``````

I have already managed to create the 52 cards deck, so I'm just going step by step.

Solution

• That function loops through the array, and on each iteration switches the current element with an element on a random position ( choosen here: `let shuffle = Math.floor(Math.random() * (deck.length));`). The `temp` variable is just used to make the value switch between the 2 values.

Say you have two values stored in variables `A = 1` and `B = 2`, to switch the values between the variables you would need a third variable, since there is no way to change them without losing the value of either, so these are the steps:

``````// save one of the values to a temp variable (we save A)
temp = A
// Put the value of B in A (after this step A = 2 and B = 2
// if you hadn't saved the value of A you would have lost it )
A = B
// then restore the value that was in A to B
B = temp
// you don't care about the value of temp after this... just that A and B are now switched
``````

This is equivalent to this part of your code:

``````let temp = deck[i];
deck[i] = deck[shuffle];
deck[shuffle] = temp;
``````

When you do this for every element in the array it's sort of guaranteed the array should be shuffled

Simpler way for switching variables

It is possible in javascript to switch variables in one instruction without a temp variable like this :

``````[a, b] = [b, a]
// for arrays switch element in position i with position j
[array[i], array[j]] = [array[j], array[i]];
``````

So an easier way to shuffle would be to

`````` //loops throug each card
for (let i = 0; i < deck.length; i++) {
// picks the random number between 0 and length of the deck
let shuffle = Math.floor(Math.random() * (deck.length));

//swap the current with a random position
[ deck[i], deck[shuffle] ] = [ deck[shuffle], deck[i] ];
}
``````