Breadcrumbs

Too Easy JavaScript - Control Structures [3]

Similar to regular life, there will be times in scripting where you have to manipulate the flow of a program. JavaScript offers two control structures - conditional statements and loops. Control structures enable us to change the typical execution from top to bottom.

If...Else Statements

Conditional statements work on an if...else basis. For example, we can translate an if...else statement into English. It would go similar to: If this comparison is true then execute this code, otherwise execute this code.

Code: JavaScript

if (condition) {
    // code if condition is true
}
else {
    // code if condition is false
}

Above is the basic format of an if...else statement. If the condition within the parentheses is true, then the code within the curved braces will execute. Otherwise the code within the else's curved braces will execute. We can now apply this to a simple script:

Code: JavaScript

var answer = 2 * 4;
if (answer == 8) {
    alert("JavaScript can do math!");
}
else {
    alert("JavaScript didn't seem to pass the FACT.");
}

When you execute the above code you should receive an alert box with the text "JavaScript can do math!". In the conditional statement slot you'll see the use of a comparison operator, we'll go over this later in this lesson.

Note that not all if statements have to be succeeded by an else statement:

Code: JavaScript

var answer = (8/4) * 4;
if (answer == 8) {
    alert("Eight!");
}

Conditional and Comparison Operators

From Part 2 you should recall JavaScript's Arithmetic and Assignment operators. JavaScript has three other types of operators - conditional, comparison, and logical. Conditional operators serve as a shortcut for if...else statements. Comparison operators are used to compare two values, used in statements such as the if...else statement.

Operator Description
== equality
!= inequality
> greater than
< less than
>= greater than or equal to
<= less than or equal to

Make note that the equality operator (==) differs from the assignment operator (=). When using comparison operators they return boolean values, either true or false. Now that we know all of the comparison operators we can put them to use in our if...else statements:

Code: JavaScript

var answer = 2 * 4;
if (answer > 8) {
    document.write("A little too high.");
}
if (answer == 8) {
    document.write("Just right!");
}

As mentioned earlier, conditional operators serve as a coder's shortcut. The syntax of a conditional operator is as follows:

Code: JavaScript

(conditional expression) ? If-true-do : if-false-do;

We can take a slightly longer if...else statement and transform it into a simple, one line command:

Code: JavaScript

var number = 2;

// Longer if...else version
if (number == 2) {
    alert("The number is 2.");
}
else {
    alert("The number isn't 2.");
}

// Short, conditional operator form
(number == 2) ? alert("The number is 2.") : alert("The number isn't 2.");

Often programmers avoid using the conditional operator as it isn't the easiest form of code to read, and seems to have drifted out of style. The choice of using the conditional operator is your own, but make sure to well comment your code to make up for the shortcut.

Applying Logical Operators

Logical operators are used alongside the conditional operators to create more complex logical operations. JavaScript has three logical operators - AND, OR, and NOT.

Operator Description
&& AND
|| OR
! NOT

When logical operators are combined with operands they output a boolean value, true or false:

Code: JavaScript

var a = 8;
var b = 7;

if (a == 8 && b == 7) { // If A equals 8 AND b equals 7
    document.write("Our values are right!");
}
if (a == 8 || b == 6) { // If A equals 8 OR b equals 6
    document.write("One of our values is right!");
}
if (!(a==b)) { // If A doesn't equal b
    document.write("A and B are different");
}

Logical operators are just logic! (Hence the name) They serve as a method of evaluating multiple conditional statements at once, and therefore expand your ability to control program flow.

While Loops

JavaScript's basic loop is the while loop. The syntax of the while loop is very similar to the if...else statements, only they have a different purpose and task to perform. Loops execute code multiple times. The while loop executes a given block of code as long as the condition remains true.

Code: JavaScript

var x = 0;

// Loop to execute 10 times
while (x <= 10) {
    document.write("Loop executed: " + x + "<br />");
    x++;
}

Example of the loop output.

As you can see, while loops are very similar to if...else statements, with the only difference being their initial purpose (loop and conditional).

For Loops

For loops are a nifty, hybrid like loop that are made to execute a code block a specific amount of times. It includes setting an initializer to get rid of the need to increment a variable.

Code: JavaScript

for (initialization; condition; increment) {
    // statements
}

Now that we know the basic format of a for loop, we can take our previous while loop and make it a for loop:

Code: JavaScript

for (x = 0; x<= 10; x++) {
    document.write("Loop executed: " + x + "<br />");
}

For loops are very popular among programmers, as most loops have a set amount of intended executions.

Summary

In Part 3 you've learned if...else statements, conditional and comparison operators, while loops, and for loops. You've taken in tons of new JavaScript to control program flow. In Part 4 we'll look into storing and working with data via arrays and using more complex conditional statements.