Exercise 002: Step by Step

Let’s review this function step by step

First of all we capture the value included in the InputBox by using its id tag

 let x = document.getElementById("passid");
    pass = x.value;

numberOfSpecialChar and numberOfNumbers are two variables that we will use respectively to measure how many special chars are in the string and how many numbers have been included.

Let’s also set another variable which is type array and includes all the list of special characters .

 myarr = ['!','@','#','$','%','&','*'];

At this point we can start a loop : the objective is to loop through each character of the password the user has provided

 for (i=0;i<pass.length;i++) {

        if ( (myCharCode>=48) &amp;&amp; (myCharCode<=59) ) {

        for (y=0; y<7;y++) {

            if (mychar==myarr[y]) {


In the line 2 of the above block we use the function charCodeAt to get the ASCII code of each characters included in the password.

In the lines 5-7 we check if the ASCII code is included in the range of numbers code of the ASCII table. The the ASCII code is between 48 and 59 we increase the variable numberOfnumbers.

In the bloc lines 11 to 14 we loop through the myarr variable and check if the char code of the password is equal to one of the char included in the array. If that is the case we increase the variable numberOfSpecialChar

At this point we can verify if all three conditions are met or not. We do that in the following block:

if ( (pass.length>=7) &amp;&amp; (numberOfSpecialChar>=2) &amp;&amp; (numberOfnumbers>=2)) {
        let msg="Password OK"


If the condition are met we output that the password is ok.

If the condition are not met we output why the password is not valid

else {
        msg="Password is rejected because:";

        if (numberOfSpecialChar<2) {
                msg_specialchar=" the number of special chars is less than 2 - ";

        if (numberOfnumbers<2) {
            msg_numberOfnumber="there are less than 2 numbers - ";

        if (pass.length<7) {
            msg_len=" passowrd is not long at least 7 chars - ";

        msg=msg+ msg_specialchar + msg_numberOfnumber + msg_len;



Something interesting in this exercise is the use of the function charCodeAt(). Interestingly in C you can assign a char to a int variable and the variable will store the code of the char.

Something in JAVA where you can cast,int value = (int) c;, but not in JavaScript which has its own function : charCodeAt().

One thought on “Exercise 002: Step by Step”

Leave a Reply

Your email address will not be published. Required fields are marked *