Build a Secret Code Checker
Combine loops and conditionals to build a guessing game. The player has limited attempts to guess the correct secret code.
YOUR TASK
Create a program that:
- Stores a secret code in a variable (e.g.
"js42")
- Creates an array of guesses to simulate attempts
- Loops through the guesses (max 3 attempts)
- Logs "Access granted!" if the guess is correct and breaks
- Logs "Wrong code. X tries left." on a miss
- Logs "Access denied." after all attempts fail
Step-by-step:
1. const secret = "js42";
2. const guesses = ["abc", "js42", "xyz"];
3. let success = false;
4. for (let i = 0; i < 3; i++) {'{'}
5. if (guesses[i] === secret) {'{'}
6. console.log("Access granted!");
7. success = true; break;
8. {'}'} else {'{'}
9. console.log("Wrong code. " + (2 - i) + " tries left.");
10. {'}'}
11. {'}'}
12. if (!success) console.log("Access denied.");
Wrong code. 1 tries left.
Access granted!