Flag

Keywords: 
Situation: 

You want to keep track of whether something happened. For example, whether one of several input errors happened.

Actions: 

Use a variable as a flag. Write code that initializes it, sets it if some condition occurs, then checks it.

Explanation: 

This pattern has many uses. Here are two examples.

Validation

//Set a flag to show data isn't bad.
var badData = false;
if ([some error condition]) {
    badData = true;
    ...
}
else if ([some error condition]) {
    badData = true;
    ...
}
if ([some error condition]) {
    badData = true;
    ...
}
//Any of tests show bad data?
if ( badData ) {
    //Respond to error.
    ...
    return; //Leave the function.
}
//Data is OK.
//Process data.
...

Notice the return statement. The code exits if there is an error. If the code gets to the line //Process data, then it knows that the data is OK. No more validation checks need be run.

You can reverse the flag variable:

//Set a flag to show data is good.
var goodData = true;
if ([some error condition]) {
    goodData = false;
    ...
}
else if ([some error condition]) {
    goodData = false;
    ...
}
if ([some error condition]) {
    goodData = false;
    ...
}
//Any of tests show bad data?
if ( ! goodData ) {
    //Respond to error.
    ...
    return;
}
//Data is OK.
//Process data
...

Remember that ! means "not."

User permissions

This is the second example of the flag pattern in action.

We could have a variable called adminUser, that is "yes" if an admin user is logged in. Any other value (or if adminUser doesn't exist at all), means that an admin user is not logged in.

The login form sets the variable. Pages you want to secure start by reading the variable.

We need a way to store variables across page requests. We use localStorage in this course. Real apps use a combination of server memory, and browser memory. Browser memory means either cookies, or localStorage. Cookies are similar to localStorage, but with less capacity.

In a login form:

if ( some username/password test ) {
    //Set the flag.
    localStorage.setItem('adminUser', 'yes');
    ...
}
else {
    //Erase the flag.
    localStorage.removeItem('adminUser');
    ...
}

During the load event of an admin page:

if (  ! localStorage.getItem("adminUser")  //Does the permission flag exist?
        || localStorage.getItem("adminUser") != "yes" //Does the flag have yes in in?
    ) {
    window.location.href = "permission-denied.html";
}
//Code for the admin page.
...

If the flag does not exist, or the flag is not "yes", jump to a page with a permission denied message.