JavaScript Project for Beginners: Memory Card Game
The goal is to match pairs of cards with the same symbol on a grid. It is a timeless game that trains your memory and attention, and a fun javascript project for beginners with plenty of javascript exercises for beginners built in. Read the code, play the live demo, then solve the practice exercises.
How the JavaScript Memory Card Game Works
The game uses an array of emoji symbols. Each symbol is doubled and shuffled to make the deck. The player flips two cards per turn. If the symbols match, the pair stays open. If not, both cards flip back. The game ends when every pair is found.
If you are searching for javascript exercises for beginners, javascript tasks for practice or quick js exercises, this game fits all three. The sections below cover the code, the HTML and CSS, a playable demo and javascript practice exercises with solutions.
What the finished project does
- Builds a shuffled deck with the Fisher-Yates algorithm.
- Flips cards on click and checks two cards for a match.
- Locks the board while two cards are being compared.
- Detects the win when all pairs are matched.
flippedCards or unlocked the board, so the game froze after the first pair. Both are fixed. The alert() pop-up is replaced by an on-page message, a move counter is added, and the CSS now has a real flip animation, because the original showed every symbol from the start.Step 1: Create and Shuffle the Deck
Start with an array of symbols, copy it so every symbol appears twice, then shuffle with Fisher-Yates. These variables (cardSymbols, deck, flippedCards, matchedCards) also make a neat set of javascript variables exercises.
// Array of card symbols
const cardSymbols = [
'🐶', '🐱', '🐭', '🐹', '🐰', '🦊', '🐻', '🐼',
'🐯', '🦁', '🐮', '🐷', '🐸', '🐵', '🐔', '🐧'
];
// Create a new shuffled deck of cards
const createDeck = () => {
const deck = [...cardSymbols, ...cardSymbols];
for (let i = deck.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[deck[i], deck[j]] = [deck[j], deck[i]];
}
return deck;
};
// Global variables
let deck = [];
let flippedCards = [];
let matchedCards = [];
let isBoardLocked = false;
let moves = 0;Step 2: The handleCardClick() Function
This function runs on every click. It ignores clicks while the board is locked or on a card that is already open. Otherwise it flips the card and stores its index. When two cards are open, it compares their symbols: a match is saved, a miss flips both cards back after one second. This is a perfect javascript function exercise.
const setMessage = (text) => {
document.getElementById('message').textContent = text;
};
// Function to handle card click
const handleCardClick = (index) => {
if (isBoardLocked || matchedCards.includes(index) || flippedCards.includes(index)) {
return;
}
document.getElementById(`card-${index}`).classList.add('flipped');
flippedCards.push(index);
if (flippedCards.length === 2) {
isBoardLocked = true;
moves++;
const [card1, card2] = flippedCards;
if (deck[card1] === deck[card2]) {
matchedCards.push(card1, card2);
flippedCards = []; // fix: clear the pair
isBoardLocked = false; // fix: unlock the board
setMessage('It is a match!');
if (matchedCards.length === deck.length) {
setMessage('Congratulations! You won in ' + moves + ' moves!');
}
} else {
setMessage('Not a match. Try again.');
setTimeout(() => {
document.getElementById(`card-${card1}`).classList.remove('flipped');
document.getElementById(`card-${card2}`).classList.remove('flipped');
flippedCards = [];
isBoardLocked = false;
}, 1000);
}
}
};Step 3: Build the Board and Style the Cards
createGameBoard() creates one div per card with a front (the hidden side) and a back (the symbol). The CSS rotates the card in 3D when it gets the flipped class.
// Function to create the game board
const createGameBoard = () => {
const gameBoard = document.getElementById('game-board');
deck = createDeck();
deck.forEach((symbol, index) => {
const card = document.createElement('div');
card.className = 'card';
card.id = `card-${index}`;
card.addEventListener('click', () => handleCardClick(index));
const front = document.createElement('div');
front.className = 'front';
front.textContent = '?';
const back = document.createElement('div');
back.className = 'back';
back.textContent = symbol;
card.appendChild(front);
card.appendChild(back);
gameBoard.appendChild(card);
});
};
// Initialize the game board
createGameBoard();.game-board {
display: flex;
flex-wrap: wrap;
max-width: 460px;
margin: 0 auto;
}
.card {
position: relative;
width: 100px;
height: 100px;
margin: 5px;
cursor: pointer;
font-size: 40px;
transform-style: preserve-3d;
transition: transform 0.4s;
}
.card.flipped { transform: rotateY(180deg); }
.front, .back {
position: absolute;
inset: 0;
display: flex;
justify-content: center;
align-items: center;
border-radius: 5px;
backface-visibility: hidden;
}
.front { background-color: #ddd; }
.back { background-color: #fff; transform: rotateY(180deg); }Step 4: Memory Game HTML Code
The HTML is small because the cards are generated by JavaScript. Link the CSS and JS files, and add a p for messages.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Memory Card Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="game-board" class="game-board">
<!-- Cards are generated by script.js -->
</div>
<p id="message">Find all the pairs.</p>
<script src="script.js"></script>
</body>
</html>Put the three files in one folder and open index.html in your browser.
Live Demo: Play the Memory Card Game
This demo uses the same deck, flip and match logic as the code above, plus a move counter and a timer. Pick a size and flip the cards. You can also use Tab and Enter.
Keep Going: Turn the Game into a Portfolio Piece
- Publish the code on GitHub with a README and a screenshot, and host the demo on GitHub Pages.
- Add difficulty levels by changing how many symbols you use.
- Add a best score and save it with
localStorage. - Add sounds for flips, matches and the win.
JavaScript Exercises and Solutions Based on the Memory Game
Try each task yourself first, then open the solution. These javascript practice exercises with solutions build from variables to functions to game state.
1. Variables: count the cards
A javascript variables exercise: how many cards are in the deck if you use 16 symbols?
const deck = [...cardSymbols, ...cardSymbols];
console.log(deck.length); // 322. Function: is it a match?
A javascript function exercise: write isMatch(deck, a, b) that returns true only for two different cards with the same symbol.
function isMatch(deck, a, b) {
return a !== b && deck[a] === deck[b];
}
console.log(isMatch(['🐶', '🐱', '🐶'], 0, 2)); // true
console.log(isMatch(['🐶', '🐱', '🐶'], 0, 0)); // false3. Task: reset the game
Write resetGame() that clears the board and the state, then builds a new shuffled board.
function resetGame() {
document.getElementById('game-board').textContent = '';
flippedCards = [];
matchedCards = [];
isBoardLocked = false;
moves = 0;
createGameBoard();
}4. Challenge: show the move counter
Show the number of moves on the page after every turn.
// add <span id="moves">0</span> to the HTML, then in handleCardClick
// right after moves++;
document.getElementById('moves').textContent = moves;5. Challenge: count the matched pairs
Return how many pairs the player has found so far.
const pairsFound = () => matchedCards.length / 2;
console.log(pairsFound()); // 0 at the startLooking for more javascript exercises and solutions? Browse our JavaScript projects and the free PDF practice sets.
Frequently Asked Questions About the Memory Game in JavaScript
How do you shuffle cards in JavaScript?
Use the Fisher-Yates algorithm: loop from the end of the array to the start, pick a random index from 0 to the current index, and swap the two items. Step 1 has the code. Avoid sort(() => Math.random() - 0.5) because it gives a biased shuffle.
How does a memory card game check for a match?
The game stores the indexes of the flipped cards. When two cards are flipped, it compares their symbols. If they are equal, both indexes go into the matched list. If not, the cards flip back after a short delay.
Why can’t I click any card after the first match?
The board stays locked if you forget to clear flippedCards and set isBoardLocked back to false after a match. The version in Step 2 does both.
How do you flip a card with CSS?
Give the card transform-style: preserve-3d, put the front and back faces on top of each other with backface-visibility: hidden, and rotate the card 180 degrees with rotateY when it has the flipped class.
How long does it take to learn JavaScript?
Most beginners learn the basics (variables, functions, loops, arrays) in a few weeks of regular practice, and become comfortable building projects after a few months.
JavaScript FAQ in Turkish, Spanish, German and Arabic
Türkçe: JavaScript projeleri
JavaScript ile neler yapılabilir?
Web siteleri, mobil uygulamalar, oyunlar, Node.js ile sunucu uygulamaları ve hafıza kartı oyunu gibi küçük projeler.
JavaScript öğrenmek ne kadar sürer?
Temel konular birkaç hafta, rahatça proje geliştirmek birkaç ay düzenli pratik gerektirir.
JavaScript hangi program?
Bir programlama dilidir. Tarayıcıda veya Node.js ile çalışır.
JavaScript neden popüler?
Her tarayıcıda çalışır, öğrenmesi kolaydır ve hem ön yüzde hem arka yüzde kullanılır.
Español: proyectos en JavaScript
¿Qué proyectos se pueden hacer con JavaScript?
Calculadoras, carritos de compra, juegos de memoria, relojes y aplicaciones del clima.
¿Qué es un proyecto en JavaScript?
Un programa o página web que combina variables, funciones y arrays para resolver un problema concreto.
¿Cómo empezar un proyecto de JavaScript?
Crea un archivo .js, escribe una función pequeña como createDeck() y ejecútala en el navegador.
¿Qué programas se han hecho con JavaScript?
Sitios web, juegos de navegador, servidores con Node.js y aplicaciones de escritorio con Electron.
Deutsch: JavaScript lernen
Wird JavaScript noch benötigt?
Ja. JavaScript ist die Standardsprache des Webs und läuft in jedem Browser.
Was kann man alles mit JavaScript machen?
Websites, Web-Apps, Spiele, Server-Anwendungen und kleine Projekte wie ein Memory-Spiel.
Ist JavaScript für Anfänger?
Ja. Man sieht Ergebnisse sofort im Browser.
Wie schwierig ist JavaScript?
Die Grundlagen sind leicht. Fortgeschrittene Themen wie asynchrone Programmierung brauchen mehr Übung.
العربية: مشاريع جافا سكريبت
تبحث عن مشاريع جافا سكريبت للمبتدئين؟ لعبة الذاكرة هذه مثال بسيط على مشروع جافا سكريبت يمكنك تجربته وتعديل شيفرته. ابحث أيضاً عن مشاريع جافا سكريبت جاهزة pdf أو مشروع جافا سكريبت github للحصول على المزيد من الشيفرات.
لست بحاجة إلى جافا سكريبت تحميل أو تحميل جافا سكريبت للاندرويد، فهي تعمل داخل المتصفح مباشرة. أما تفعيل جافا سكريبت على الهاتف فيتم من إعدادات المتصفح. وللتوسع جرّب مشاريع جافا للمبتدئين، مع ملاحظة أن جافا وجافا سكريبت لغتان مختلفتان.
Keep Building with JavaScript
You built a memory card game with arrays, a Fisher-Yates shuffle, DOM events and CSS 3D flips, then practiced with javascript exercises and solutions. Use it as a launchpad for difficulty levels, scores and sounds.
