Conditionals

A large part of writing code consists of testing for various conditions. Checking for various conditions is done through what is referred to as the "if" statement. Nearly all if statements can be boiled down to the simple idea of "If we compare these two variables and they fullfill a certain requirement then run the following code" in normal English.

Let's use some code similar to what we've already written.


var variable_one = 72;

if( variable_one > 50 ){
	alert("Greater than 50.");
}

In this case you can almost read the code out loud as it is written. "If variable_one is greater than 50 then open an alert window with a message saying it is greater than 50." And indeed if you run the code you'll simply be greeted with an alert box of the given message.

Not what if we want to take the alternate outcome (in this case the variable being *less* than 50) into account and react to that possibility as well? In this particular case you don't have to use a "less than" symbol. A number can only be greater than, less than, or equal to a number. Because of that we can just presume that any possibility that does not fullfull the first condition falls into one of the other two and just

Let's extend this example a bit...



var variable_two = 64;

if( variable_two > 50 ){
	alert("Greater than 50.");
} else {
	alert("Less than 50.");
}

If you were to run this code you would be greeted with a simple window reading "Greater than 50."

So what's happening here? Basically this is another way of saying the following...

"If the variable named 'variable_one' is greater than the number 50 then show an alert message saying that it is greater than 50, or else if it is not then show an alert message that is is not greater than 50.".

Furthermore you can see this code uses an "else" keyword. This is a way of inserting code to run should the original comparison not be fullfilled. In this case the code is still enacting an "alert" function but alerts the user with a different phrase.

Not what if we want to check for alternative possibilities? What if we want to check if a number is not just above or below another number but between two numbers? We could

Let's extend our example even more...


var variable_three = 50;

if( variable_three > 50 ){
	alert("Greater than 50.");
} else if( variable_three == 50 ) {
	alert("Equal to 50.");
} else {
	alert("Less than 50.");
}

In this case running the code would result in an alert box reading "Equal to 50."

You might have noticed in this particular example that when checking for the posibility of variable three being equal to the number 50 the possibility was checked using "==". This is not a typo. Whereas in most normal written math we would read a single equals sign as "equals" we have to remember that in programming the single "=" sign is already used to define assignments. Unlike variables, conditional checks are not assigning anything, and therefore need a different symbol to check for equality.

In fact there are many different possible symbol pairs that might be used within a conditional check. Let's go over those now.

Making Comparisons

There are generally only a few ways one can compare values within code; especially when dealing with numbers. Each comparison is used the same way. They must have values on either side of them to actually compare and can only be used within either an "if" statement or an "else if" statement.

The most basic, and common, comparisons are as follows.

== Equals to
!= Is not equal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than OR equal to

There are two more rarely used comparisons that can not only check for value but also for type. Essentially what this means is that the program will check not only for if the strored values are the same but if the data types themselves are the same.

=== Equal to both value AND type
!== Not equal to both value AND type

Finally there are two more comparisons that are often referred to as "Logical Operators". These can be used to chain together various condition checks so that you require more than one coondition to be true or false before code is run.

&& Both the first condition AND the next condition must be true.
|| Either the first condition OR the next condition must be true.

The "and" operator is simply the ampersand written with "Shift-7" on most keyboards. The "or" operator is "Shift" and the backslash key above the Enter key on most American keyboards.

These operators are extremely important in that they can be used in lieu of stacking "if" statements within one another.

For instance; if I wanted to write a program for a department issuing driver's licenses I may want both a minimum and a maximum age. In that case I would check the age of the applicant against code that might look like this...


if( age > 16 && age < 80 ){
	// You may take the exam
} else {
	// You may take the bus
}

Using the logical operators is fairly simple. Just remember that they always compare two inputs. There always needs to be a reference or value to the left of the operator, and to the right of the operator, and they should be preferably of the same time. In other words you should never compare a string and an integer and expect to ever get something besides a "false" answer.

Making Comparisons

There is an alternate form of conditional checks that allows you to traverse a list of your own making. This is called the "switch" format and is common in most programming languages.

This format has the benefit of letting the author quickly look at several possibilities and choose the best response. It does not allow for comparative calculations (no "less than", etc.) and whether or not it requires less or more typing probably depends on the kind of checks involved. It also does not allow for branching or nested possibilities (if statements within if statements).

As such this author doesn't really care for it - but many programmers do. It looks like this...


switch( "c" ) {
    case "a":
        console.log("w");
        break;
    case "b":
        console.log("x");
        break;
	case "c":
		console.log("y");
		break;
	case "d":
		console.log("z");
		break;
    default:
        console.log("not found");
}

This code looks at the input figure "c", checks through the cases, finds a match "c", executes the code directly after the matched line (writes "y" to the console), and stops checking for any more matches as a "break" command is issued as part of that code.

"Break" is something you'll learn more about in the section on "for" loops.

We could use numbers or references just as easily as we use strings here.

Just as with the final "else" part of an if statement the final "default" case is what happens should none of the prior conditions be met.