Start learning free

LESSON 165 OF 410 · PROJECTS: EVERYDAY PROGRAMS

Password Strength V2 - Has Digit in JavaScript

Practice

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

    Password Strength V2 in JavaScript

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free