Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Memory Game in JavaScript

Match shuffled cards in JavaScript with arrays and a Set. Lock input during the mismatch delay; a round counter stops old timers from changing a new game.

IntermediateJavaScript Mini ProjectsExample 14 of 20

Save this as index.html and open it in a browser.

memory-game.js
1<!doctype html>
2<html lang="en">
3<meta charset="utf-8">
4<title>JavaScript practice</title>
5<body>
6<p>Find the two matching pairs.</p><div id="cards"></div><p id="status"></p><button id="restart">New game</button>
7<script>
8let cards, flipped, matched, locked, round = 0;
9const area = document.querySelector('#cards');
10const status = document.querySelector('#status');
11function render() {
12 area.replaceChildren();
13 cards.forEach((value, index) => {
14 const button = document.createElement('button');
15 button.textContent = matched.has(index) || flipped.includes(index) ? value : '?';
16 button.setAttribute('aria-label', 'Card ' + (index + 1) + ': ' + button.textContent);
17 button.disabled = locked || matched.has(index) || flipped.includes(index);
18 button.onclick = () => flip(index); area.append(button);
19 });
20}
21function flip(index) {
22 if (locked || matched.has(index) || flipped.includes(index)) return;
23 flipped.push(index); render();
24 if (flipped.length < 2) return;
25 const [a, b] = flipped;
26 if (cards[a] === cards[b]) {
27 matched.add(a); matched.add(b); flipped = [];
28 status.textContent = matched.size === cards.length ? 'All pairs found!' : 'Pair found. Keep going.';
29 render();
30 } else {
31 locked = true; render(); status.textContent = 'Not a pair. Watch them turn back.';
32 const thisRound = round;
33 setTimeout(() => {
34 if (thisRound !== round) return;
35 flipped = []; locked = false; status.textContent = 'Try another pair.'; render();
36 }, 800);
37 }
38}
39function restart() {
40 round++; cards = ['Sun', 'Sun', 'Moon', 'Moon'];
41 for (let i = cards.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [cards[i], cards[j]] = [cards[j], cards[i]]; }
42 flipped = []; matched = new Set(); locked = false; status.textContent = 'Choose two cards.'; render();
43}
44document.querySelector('#restart').onclick = restart;
45restart();
46</script>
47</body>
48</html>

Sample Output

Pair found. Keep going.

Two different positions had the same value and were added to matched.

All pairs found!

All four card positions belong to matched. The game is complete.

In this one

  • Track hidden, open, and matched cards
  • Shuffle with swaps
  • Lock input during a mismatch delay
  • Ignore stale callbacks after restart

How it works

  1. 1

    Shuffle two Sun cards and two Moon cards.

  2. 2

    Render question marks except for open or matched positions.

  3. 3

    Open two different unmatched cards.

  4. 4

    Keep a matched pair, or lock input and hide a mismatch after a delay.

  5. 5

    When all four positions are matched, show All pairs found; card order is random.

Edge cases

Same card clicked twice

One physical card cannot be its own matching pair.

Reject indexes already in flipped, and disable their buttons.

Restart during delay

An old timeout could change the new board.

Capture the round number and return if the game has since restarted.

What's going on

A memory game asks the player to uncover two cards and remember their positions. Matching pairs remain visible; different cards turn back after a short delay. This four-card version teaches state changes without needing images or a large board.

The cards array holds shuffled values. flipped contains up to two current indexes, and matched is a Set of positions already solved. A Set stores each value at most once. Buttons for solved or already-open cards are disabled so one card cannot be matched with itself.

When a pair differs, locked prevents a third click while the cards are visible. A delayed callback hides them after 800 milliseconds. Restart increments round; the old callback checks that value before touching the new game. This stops an earlier round's timer from clearing a new selection. The shuffle swaps random positions one at a time instead of using an unreliable random sort comparison.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does flipped contain?

Pick an answer to check it.

Question 2

Why compare thisRound with round?

Pick an answer to check it.

Questions people ask

Why use a Set for matched?

A solved position should appear only once. Set makes that intent clear and provides a direct has check.

Why lock the other buttons?

Otherwise a third click could arrive before a mismatched pair is hidden and break the two-card rule.

Is the layout always the same?

No. Each new game shuffles the four cards using random swaps.