how to shuffle a deck of cards using Js

Viewed 1198

I searched for how to shuffle a deck of cards that I made and I found these lines but I can't understand...

  1. is (this) that is written in the second line a js keyword or it't just a given name
  2. how does m stores deck.length + i
  3. what does m-- means at the end of the sixth line
  4. what is the function of line no.8

    shuffle() {
        const { deck } = this;
        let m = deck.length, i;
    
        while (m) {
          i = Math.floor(Math.random() * m--);
    
          [deck[m], deck[i]] = [deck[i], deck[m]];
        }
    
        return this;
      }
    

I know it's a lot to ask but I would appreciate your help

2 Answers

is (this) that is written in the second line a js keyword or it't just a given name

Yes, this is a keyword in JavaScript. I strongly suggest you google "this javascript" to learn how this works. It will take some time to get your head around.

how does m stores deck.length + i

I assume you are asking about let m = deck.length, i;. Notice there is a ,, not a +. m only stores deck.length. i is a separate variable that is declared on this line. I suggest you use the Chrome or Firefox developer tools to step through the code to inspect the value of m. If you are unfamiliar with these tools, you definitely need to learn about them and how to use them effectively, especially to debug your code.

what does m-- means at the end of the sixth line

-- is the post-increment operator. It decreases the value of m by 1 and stores that new value in m. The result after the subtraction is used in the rest of the expression. You can experiment with this operator in your own code or in the JavaScript console.

what is the function of line no.8

[deck[m], deck[i]] = [deck[i], deck[m]]; uses destructuring syntax to swap two values in the array. Again, you can use the debugger in the browser's developer tools to inspect the values of the variables to see what happens.

const and this are keywords

const and let are similar to var, except const cannot be assigned after initialization.

m stores only deck.length. i is another variable, declared by the let

m-- means decrementation, i.e. same as m = m-1 and it gives value of m after that calculation.

On line no.8 You can see destructuring assignment.

Related