0

I'm busy building a memory game in JavaScript.

While following a tutorial online I had to use this code:

function startGame() {

    var shuffledCards = shuffle(cards);

    for (let i = 0; i < shuffledCards.length; i++) {
        [].forEach.call(shuffledCards, function (item) {
            deck.appendChild(item);
        });
    }
}

and I don't really understand what is happening with this part to be exact. (could someone please explain this part?)

[].forEach.call(shuffledCards, function (item) {
     deck.appendChild(item);
});

I'm wrote the code below, which I understand much better:

 function startGame() {

     var shuffledCards = shuffle(cards);

     for (let i = 0; i < shuffledCards.length; i++) {
         deck.appendChild(shuffledCards[i]);
     }
}

So why would I use the above code as apposed to the code I wrote? And could someone please take me through what is happening in the above code too. My brain gets fried when I'm trying to make sense of it.

Nidhi257
  • 754
  • 1
  • 5
  • 23
Jakwakwa
  • 106
  • 1
  • 7
  • 2
    What does this return shuffle(cards)? – Drag13 Apr 30 '18 at 06:41
  • Why? -> [JavaScript closure inside loops](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Andreas Apr 30 '18 at 06:43
  • 1
    @Andreas there is no context breaking code, I am not quite sure this is the main reason – Drag13 Apr 30 '18 at 06:45
  • 2
    To me, it looks like that tutorial has some errors in it. I see no reason to nest that `forEach` in a `for` loop. Either loop should be sufficient. – Cerbrus Apr 30 '18 at 06:46
  • 1
    I don't know the goal of this function, but it looks that it will copy shuffled cards to the deck array so many times as the shuffledCards.length is. IMO it's a mistake. – Vicctor Apr 30 '18 at 06:46
  • Here’s the [tutorial](https://scotch.io/tutorials/how-to-build-a-memory-matching-game-in-javascript#toc-1-shuffing-cards) and a [comment](https://www.spot.im/s/00YjnNI9sdC5) asking about that same part. – Sebastian Simon Apr 30 '18 at 06:52

0 Answers0