2

Am practicing js and while I was searching to make a deck of cards I found these lines of codes but there is one line that I can't understand (I left three emty lines around it to reach it easily)

    class Deck {
        constructor() {
          this.deck = [];

          const suits = ['Hearts', 'Spades', 'Clubs', 'Diamonds'];
          const values = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King'];

          for (let suit in suits) {
            for (let value in values) {



              this.deck.push(`${values[value]} of ${suits[suit]}`);



            }
          }
        }
      }

      const deck1 = new Deck();
      console.log(deck1.deck);
Marco Maher
  • 351
  • 1
  • 9
  • Its string interpolation, it basically inserts the value into the string – Manav Jun 10 '20 at 15:37
  • You can look it up here https://stackoverflow.com/questions/35835362/what-does-dollar-sign-and-curly-braces-mean-in-a-string-in-javascript – Manav Jun 10 '20 at 15:37
  • what does the $ do ? should I write it before every string interpolation? and what is added to what ? I mean the suits are added to the value or the values are added to the suits – Marco Maher Jun 10 '20 at 15:39
  • 1
    Its sort of just a convenient option to use. You could also use `.push(values[value] + ' of '+ suits[suit])` and it should work the same way – Manav Jun 10 '20 at 15:40

1 Answers1

0

this.deck.push(${values[value]} of ${suits[suit]});

you are creating a string inside nested for loop. Using Both the loop variables to construct the element

${values[value] --> substitutes the value of the variable

of --> constant

${suits[suit]} --> substitutes the value of the variable from inner for loop

Output:
["Ace of Hearts", "2 of Hearts", "3 of Hearts", "4 of Hearts", "5 of Hearts", "6 of Hearts", "7 of Hearts", "8 of Hearts", "9 of Hearts", "10 of Hearts", "Jack of Hearts", "Queen of Hearts", "King of Hearts", "Ace of Spades", "2 of Spades", "3 of Spades", "4 of Spades", "5 of Spades", "6 of Spades", "7 of Spades", "8 of Spades", "9 of Spades", "10 of Spades", "Jack of Spades", "Queen of Spades", "King of Spades", "Ace of Clubs", "2 of Clubs", "3 of Clubs", "4 of Clubs", "5 of Clubs", "6 of Clubs", "7 of Clubs", "8 of Clubs", "9 of Clubs", "10 of Clubs", "Jack of Clubs", "Queen of Clubs", "King of Clubs", "Ace of Diamonds", "2 of Diamonds", "3 of Diamonds", "4 of Diamonds", "5 of Diamonds", "6 of Diamonds", "7 of Diamonds", "8 of Diamonds", "9 of Diamonds", "10 of Diamonds", "Jack of Diamonds", "Queen of Diamonds", "King of Diamonds"]
upog
  • 4,965
  • 8
  • 42
  • 81