Let's use closures to build a password-protected vault that locks itself after three wrong guesses. The password and the treasure are stored in the closure, so there's absolutely no way to peek at them from outside.
function createVault(password, treasure) {
let failedAttempts = 0;
let isLocked = false;
const MAX_ATTEMPTS = 3;
function open(guess) {
if (isLocked) {
return "🚨 VAULT LOCKED. Too many wrong guesses. Call security!";
}
if (guess === password) {
failedAttempts = 0;
return `🔓 Access granted! Inside you find: ${treasure}`;
}
failedAttempts++;
const remaining = MAX_ATTEMPTS - failedAttempts;
if (remaining === 0) {
isLocked = true;
return "❌ Wrong! The vault is now LOCKED.";
}
return `❌ Wrong password. ${remaining} ${remaining === 1 ? "attempt" : "attempts"} left.`;
}
return { open };
}
const vault = createVault("open-sesame", "a golden burger pot 🏆");
console.log(vault.open("password123"));
console.log(vault.open("open-sesame"));
console.log(vault.open("abracadabra"));
console.log(vault.open("please"));
console.log(vault.open("pretty please"));
console.log(vault.open("open-sesame"));
console.log(vault.password);
It prints
❌ Wrong password. 2 attempts left. 🔓 Access granted! Inside you find: a golden burger pot 🏆 ❌ Wrong password. 2 attempts left. ❌ Wrong password. 1 attempt left. ❌ Wrong! The vault is now LOCKED. 🚨 VAULT LOCKED. Too many wrong guesses. Call security! undefined
Notice that a correct guess resets the counter (that's why the third guess says "2 attempts left" again). And even when we finally type the correct password, the vault stays locked. And vault.password is undefined: the password is hidden inside the closure, where no outsider can ever reach it.
Add a changePassword(oldPassword, newPassword) function to the vault, which only works if the old password is correct. Since password is a parameter, you'll need to make it changeable. (Hint: parameters can be reassigned, just like let variables.) Remember to include changePassword in the returned object!
Grade 9, complete! You now understand how JavaScript thinks about variables at a deep level. Plenty of people who've been coding for a year still find closures confusing. Not you!
In Grade 10, you'll get the power tools: array methods like map, filter and reduce that will make your loops shorter, cleaner and way more fun.