Start learning free

LESSON 192 OF 285 · PROJECTS: EVERYDAY PROGRAMS

Password Strength V2 in JavaScript: Find a Digit with a Loop and Flag

Practice Read the full explanation

Extend the length check with a second rule: the password must also contain at least one digit.

You start with:

const password = "Secret99";

Build:

Length: 8
Has digit: True
Strong

Rules:

  • Print "Length: " followed by the number of characters.
  • Loop through each character to set a boolean flag hasDigit, which starts as false and becomes true when a digit is seen.
  • Print "Has digit: " followed by the flag. Write it as True or False with a capital letter, exactly as in the example (your language's own boolean prints differently, so choose the text yourself).
  • If the length is at least 8 and hasDigit is true, print Strong; otherwise print Weak.

Try other passwords: with abcdefgh the output is

Length: 8
Has digit: False
Weak

Use a regex test like /[0-9]/.test(c) in the loop. JavaScript prints true/false by default; convert with a ternary (hasDigit ? "True" : "False").

const password = "Secret99";

const length = password.length;
console.log("Length: " + length);
let hasDigit = false;
for (const c of password) {
    if (/[0-9]/.test(c)) {
        hasDigit = true;
    }
}
console.log("Has digit: " + (hasDigit ? "True" : "False"));
if (length >= 8 && hasDigit) {
    console.log("Strong");
} else {
    console.log("Weak");
}

STEP 1 OF 8
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: EVERYDAY PROGRAMS

    Password Strength V2 in JavaScript, explained

    Problem overview

    The checker now has a second rule: a strong password must have at least 8 characters and contain a digit. The program prints three lines: the length, whether a digit was found, and the verdict, Strong or Weak.

    For "Secret99" the output is:

    Length: 8
    Has digit: True
    Strong

    For "abcdefgh", which has 8 characters but no digit, it is:

    Length: 8
    Has digit: False
    Weak

    The digit line must read True or False with a capital letter, which is not what JavaScript prints for a boolean by default.

    Approach: a flag that only ever turns on

    To find out whether any character is a digit, the program looks at the characters one at a time. It keeps a boolean flag, hasDigit, that starts as false: until a digit shows up, we assume there isn't one. When the loop meets a digit, it sets the flag to true, and nothing ever sets it back. After the loop, the flag answers the question for the whole string.

    This "start false, flip to true" pattern is the standard way to ask "does at least one item satisfy this?" The verdict combines the two rules with &&, which is true only when both sides are true.

    Step by step

    1. Store length as password.length, because it is used for both the printed line and the rule.
    2. Print the first line: "Length: " joined with the number.
    3. Create the flag with let hasDigit = false;. It uses let because its value changes.
    4. Write a for...of loop. It gives you one character at a time, in order, in the constant c.
    5. Test each character. Inside the loop, /[0-9]/.test(c) is true when c is one of the digits 0 to 9. When it is, set hasDigit to true.
    6. Print the digit line after the loop. The ternary hasDigit ? "True" : "False" picks the text. It goes outside the braces so that it runs once.
    7. Write the verdict's if. The condition is length >= 8 && hasDigit, and the body prints Strong.
    8. Add the else. It prints Weak for everything else.

    The solution in JavaScript

    const password = "Secret99";
    
    const length = password.length;
    console.log("Length: " + length);
    let hasDigit = false;
    for (const c of password) {
        if (/[0-9]/.test(c)) {
            hasDigit = true;
        }
    }
    console.log("Has digit: " + (hasDigit ? "True" : "False"));
    if (length >= 8 && hasDigit) {
        console.log("Strong");
    } else {
        console.log("Weak");
    }

    Following the flag through the loop

    Here is hasDigit after each character of "Secret99". It is false for the first six characters, S, e, c, r, e and t. At the first 9 it becomes true, and at the second 9 it stays true. The loop doesn't stop early: it visits all eight characters, and only the final value of the flag is used afterwards.

    That final value is what the program prints and tests. With "abcdefgh" the flag never changes, so the line says Has digit: False and the && in the verdict fails on its right side, even though the length rule passes on its left side.

    Details worth knowing

    A for...of loop over a string visits it one character at a time, with no index to manage. That is simpler than a for loop with password[i] when the position doesn't matter.

    The pattern /[0-9]/ is a regular expression literal. The square brackets form a character class, which matches one character from the range 0 to 9, and the method .test(c) returns a boolean. Only the ASCII digits 0 to 9 match: this is the rule the lesson uses for a digit.

    JavaScript prints a boolean in lowercase, and string concatenation does the same: "x" + true is "xtrue". The output here needs True, so the program chooses the text itself with a ternary, condition ? valueIfTrue : valueIfFalse. The parentheses around the ternary matter, because + binds tighter than ?:. Without them, the whole "Has digit: " + hasDigit would be the condition.

    The flag never goes back to false. If the loop did that for a later character that wasn't a digit, only the last character would decide the result.

    A shortcut

    For this one question, the loop isn't strictly needed: /[0-9]/.test(password) searches the whole string and returns true for "Secret99" and false for "abcdefgh" and "". The lesson uses the loop because the later versions check several kinds of character in a single pass.

    Edge cases and common mistakes

    • Declaring the flag with const. Assigning to it in the loop would throw a TypeError.
    • Starting the flag as true. Every password would then claim to have a digit.
    • Putting the Has digit line inside the loop. It would print once per character.
    • Using || in the verdict. Then a password with either 8 characters or a digit would be strong. Both rules must hold, so use &&.
    • Testing digits with isNaN or Number. Number(" ") is 0, so isNaN(" ") is false and a space would look like a digit. The pattern /[0-9]/ matches only the characters 0 to 9. Digits from other scripts, such as "٣", don't match it either.
    • Short passwords with a digit. "abc123" has a digit but only 6 characters, so it is Weak.

    Testing

    Try these passwords in the editor above:

    passwordOutput
    "Secret99"Length: 8, Has digit: True, Strong
    "abcdefgh"Length: 8, Has digit: False, Weak
    "abc123"Length: 6, Has digit: True, Weak
    "a1"Length: 2, Has digit: True, Weak
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free