LearnFrenzy
Sign in Take a free test

Closures · Closures Coding Problems · Question 4

Limit login attempts with a closure in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

Write createLogin(password, maxAttempts) that returns a function: correct passwords log in, wrong ones count as failures, and after maxAttempts failures the account is locked even for the right password.

Solution
main.js
function createLogin(password, maxAttempts = 3) {
  let failures = 0;
  return (guess) => {
    if (failures >= maxAttempts) return "Account locked";
    if (guess === password) { failures = 0; return "Welcome!"; }
    failures++;
    const left = maxAttempts - failures;
    return left > 0 ? `Wrong password (${left} left)` : "Account locked";
  };
}

const login = createLogin("lf@2026", 3);
for (const guess of ["abc", "lf@2026", "123", "456", "789", "lf@2026"]) {
  console.log(guess.padEnd(8), login(guess));
}

Output Verified by running it on Node.js

abc      Wrong password (2 left)
lf@2026  Welcome!
123      Wrong password (2 left)
456      Wrong password (1 left)
789      Account locked
lf@2026  Account locked

failures is private, so nothing outside can reset it. A successful login resets the count; three consecutive failures lock the account permanently.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links