Switch Statement

A switch statement is very similar to an if statement. If statements provide the possibility of attaching else ifs and an else, which helps JavaScript handle multiple conditionals. However, an if statement with many extra conditionals seems a bit excessive and is difficult to read. Typically, a programmer, like yourself, would want to break the if statement down into more readable pieces. The switch statement excels at code readability. The example below will introduce us into the syntax and structure of a standard switch statement.

Example <script type=”text/javascript”>
var x = 3;
switch(x)
{
case 1: // This case condition is the same as the if conditional of if(x == 1)
document.write(‘Case 1.’);
break; case 2: // This case condition is the same as the if conditional of if(x == 2)
document.write(‘Case 2.’);
break; case 3: // This case condition is the same as the if conditional of if(x == 3)
document.write(‘Case 3.’);
break; case 4: // This case condition is the same as the if conditional of if(x == 4)
document.write(‘Case 4.’);
break; default: // This case condition is similar to the else statement
document.write(‘Default.’);
break;
}
</script>
Result Case 3.

To define a switch statement, you begin with the keyword switch and place the value in parentheses. Generally, this value will be a variable, but you can also place numbers or strings in the parentheses as well. Once inside the switch statement, new keywords like case, break, and default appear. The keyword case is followed by some value. However, the value following the case is usually a static value like an integer or a string rather than a variable, but that does not mean you couldn’t use a variable instead. In an if statement, we have a condition, and whenever that condition is met, we execute the statement inside of it. The case condition is more like an if statement that has an equal to (==) conditional. Following the colon, we can provide statements that we want to be executed whenever the condition is true. Statements can be provided inside the case until a break is defined and executed. The keyword break states that the condition is over and to exit out of the switch statement (break is also used in JavaScript loops). Finally, the last important term in the example is default. Other than the syntactic difference, default performs the exact same task as an else statement does. If none of the cases are true, the default case will be executed.

The logic in the example is simple. First, our variable x equals the integer 3. We proceed through the switch statement until we find a case that is equal to 3. Once that condition has been met, we execute the document.write(‘Case 4.’); found inside the appropriate case. Ultimately, switch statements are not used very often in contrast to the if statement. But, the switch statement provides order and simplicity when you are modifying the code or adding extra conditionals.

Operators

JavaScript Operators are pretty standard. They are exactly what you would expect from your high school math class. Operators are anything you use when comparing or acting upon with numbers/values.

Arithmetic Operators:

Example
<html>
    <body>
        <script type="text/javascript">
            var y = 7;  //Setting our variable
            var x = y + 2; //Addition, x would equal 9 here
            var x = y - 2;  //Subtraction, x would equal 5
            var x = y * 2;  //Multiplication, x would equal 14
            var x = y / 4;  //Division, x would equal 1.75
            var x = y % 3;  //Modulus (Divison Remainder), x would equal 1
        </script>
    </body>
</html>

Incrementing and Decrementing JavaScript Operators

Incrementing is adding 1, while decrementing is subtracting 1.

Example
<html>
    <body>
        <script type="text/javascript">
            var w = 0;
            var x = 0;
            var y = 0;
            var z = 0;
            document.write("w++ = " + w++); //Writing our results
            document.write("<br/>"); //Writing a line break
            document.write("x-- = " + x--); //Writing our results
            document.write("<br/>"); //Line break
            document.write("++y = " + ++y); //Writing our results
            document.write("<br/>"); //Line break
            document.write("--z = " + --z); //Writing our results
        </script>
    </body>
</html>
Result

w++ = 0
x– = 0
++y = 1
–z = -1

Incrementing and decrementing is a somewhat difficult concept, so take a deep breath and relax. We have a standard document.write method happening. In that method, we have a string that is showing you which variable we are talking about. So, the “w++ = “ is a string and not a variable. Then, we add that string to the w++ variable that is being incremented. (Quick Note: Strings can be combined with integers using the +, however, if you were to try to combine two integers in this manner, it would give you the sum of them.) The important part here is the order of the increment or decrement operator. Notice how incrementing the w, as in w++, gives you the result of 0, but incrementing the y, as in ++y, gives you the result of 1. This is because it is an increment operator has two options. Since the increment operator is after the w, as in w++, it needs incremented after the statement has been performed, while ++y is incremented before the statement is performed, since the ++ is before the y.

Let’s try to clear up that String + integer part really quick:

Example
<html>
    <body>
        <script type="text/javascript">
            var string1 = "You are awesome, ";
            var string2 = "and you know it.";
            var string3 = string1 + string2;
            document.write(string3);
        </script>
    </body>
</html>
Result
You are awesome, and you know it.

So, that is how you combine two strings.

Example
<html>
    <body>
        <script type="text/javascript">
            var x = "7";
            var y = 7;
            var example1 = x + x;
            var example2 = y + y;
            var example3 = x + y;
            var example4 = y + x;
            document.write("Example1 = " + example1);
            document.write("<br/>"); //Line break
            document.write("Example2 = " + example2);
            document.write("<br/>"); //Line break
            document.write("Example3 = " + example3);
            document.write("<br/>"); //Line break
            document.write("Example4 = " + example4);
        </script>
    </body>
</html>
Result
Example1 = 77
Example2 = 14
Example3 = 77
Example4 = 77

First off, the document.write(“Example1 = ” + is just writing out a string “Example1 = ” and combining that with our returning variable. So, example1 returns 77 because the string “7” + “7” is simply the joined of a string into “77”. Next, example2 returns 14 because the integer 7 added to the integer 7 equals 14. Finally, example3 returns 77 because the string 7 is combined with the integer 7, and the only way JavaScript knows how to join and integer and a string is by joining them like two strings. The same is true for example4

Assignment Operators

These are not a necessity for programmers, but they are great shortcuts.

Example
<html>
    <body>
        <script type="text/javascript">
            var x = 4;
            var y = 2;
            x = y;  //x = 2
            x += y;  //x = 6, (this is the same as x = x + y;)
            x -= y;  //x = 2, (this is the same as x = x - y;)
            x *= y;  //x = 8, (this is the same as x = x * y;)
            x /= y;  //x = 2, (this is the same as x = x / y;)
            x %= y;  //x = 0, (this is the same as x = x % y;)
        </script>
    </body>
</html>

References

If Statements

If your new to programming, this will be a great tutorial for the fundamentals of programming logic. An if statement is one of a few ways to do something when a condition is set. It helps control the flow of your coding logic.

In English:

If you are thirsty, take a drink.

 

We are just going to assume that from now that the code in the examples are embedded in the <script> tags that are in the body of an HTML document.

Example
var thirsty = true;
var drank = false;
if(thirsty == true)  //notice the ==
{
    drank = true;
    document.write(drank);
}
Result
true

The == is one of the comparison operators. It is not the same as = that sets a variable or property equal to something. Since, the variable thirsty does equal true the if is executed. If the statement would have said if(thirsty == false), drank would not have been set to true.

Example
var x = 7;
if(x===7)
{ 
    //this would be executed
}
if(x==="7")
{
    //this would not be executed because === is a strict operator that makes sure that the variable is set to the correct value and type of the conditional variable. The conditional variable here is is "7"
}
if(x!=8)
{
    //this would be executed because != means that the variable is not equal to the conditional variable
}
if(x>8)
{
    //Since 7 is not greater 8, this would not be executed
}
if(x<8)
{
    //Since 8 greater 7, this would be executed
}
if(x>=7)
{
    //Since 7 is equal 7, this would be executed
}
if(x<=6)
{
    //Since 7 is not less than or equal to 6 this would not be executed
}

The comparison operators are extremely useful, but they are not just restricted to integers. For example, if(x == “example”) would return false, since 7 is not equal to the string “example”.

Example
var x = 7;
if(x>=6 && x<=8)
{
    //Since 7 is greater than 6 and is less than 8, this statement would be executed
}
if(x==7 || x>=8)
{
    //This if statement says if x is equal to 7 or if x is greater than 8, then execute this statement. While x is not greater than 8, x is equal to 7; therefore, it will execute the statement.
}
if(!(x==6))
{
    //Since x is equal to 7 and we are checking if that statement is false, this statement would be executed.
}

If statements can be just as simple as the examples above, but they can also be more useful when you combine the if statements with else if and else.

Example
var x = 6;
if(x == 8)
{
    x++;
    document.write("if(x = 8) and now x = " + x);//This would not be executed because x is not equal to 8
}
else if (x == 7)
{
    x = 4;
    document.write("else if (x = 7) and now x = " + x);//This would not be executed because x is not equal to 7
}
else
{
    x = 20;
    document.write("else and now x = " + x);//This would be executed because the other conditionals were not met
}
Result
else and now x = 20

You might be asking yourself, “What is the point in an else if statement?” Well consider the following examples

Example
var x = 8;
if(x == 8)
{
    x++;
    document.write("if(x = 8) and now x = " + x);//This statement would be executed because x is equal to 8
}
if (x == 7)
{
    x = 4;
    document.write("else if (x = 7) and now x = " + x);//This statement would not be executed because x is not equal to 7
}
else
{
    x = 20;
    document.write("else and now x = " + x);//This statement would be executed because the other conditionals were not met
}
Result
if(x = 8) and now x = 9
else and now x = 20

Why did the if(x == 8) and the else both execute their statements? It is best to think of ifs as completely separate conditionals, but else if and else build off whichever if they follow. So, if you had an if statement that was following by and another if statement, the first if statement would be separate from the second if statement just like the example above. However, the second if statement in the example above, has an else built onto it. Since the first if statement’s condition is satisfied, it executes its statements. The second if statement’s condition is not satisfied, but its built on else statement’s condition is satisfied. Therefore, x is incremented in the first conditional, and “if(x = 8) and now x = ” + x is displayed on the screen. Also, we have the second if’s else that sets x equal to 20, and “else and now x = ” + x is displayed on the screen.

References

Functions

JavaScript Functions are extremely useful, and they can save you from writing bunch of redundant code.

Example
<html>
    <body>
        <script type ="text/JavaScript">
            function annoyingPopUp()
            {
                alert(" The most annoying thing ever. ");
            }
        </script>
        <form>
            <input type="button" value="Click me!" onclick="annoyingPopUp()" />
        </form>
    </body>
</html>

One way to execute JavaScript functions is to use a button’s onclick attribute. Putting annoyingPopUp() in the onclick=”” will call the JavaScript function annoyingPopUp. Of course, that will cause the most annoying method to be called, which is alert. Alert is actually a method of the window object, but in it is often shortened to just alert(); This is a very rare exception, and most methods are not shortened like this. Whatever is inside the () of the alert() is what will be shown in an alert box.

Every time, you click this button the annoyingPopUp function will keep giving you the alert.

Example
<html>
    <body>
        <script type ="text/javascript">
            function sampleFunction(argument1)
            {
                alert(argument1);
            }
        </script>
        <form>
            <input type="button" value="Click me!" onclick="sampleFunction(' Test Argument ')" />
        </form>
    </body>
</html>

We can see that the onclick is different in this example than the last one. The onclick=”sampleFunction(‘ Test Argument ‘)” now has a argument it is adding into the sampleFunction(). The argument ‘ Test Argument ‘ is passed into the function sampleFunction(), and the argument1 now takes the value of the ‘ Test Argument ‘. As we begin through the function, we are told to alert our new argument, argument1. The message that pops up is “Test Argument”.

Another way to call a function is to call it from another method or function:

Example
<html>
    <body>
        <script type ="text/javascript">
            function addingFunction(argument1, argument2)
            {
                return argument1 + argument2;
            }
            document.write(addingFunction(333,444));
        </script>
    </body>
</html>
Result
777

This is similar to the last example, but the function is being called from another JavaScript method document.write(). addingFunction() is passing in two arguments this time: 333 and 444. Where 333 is being passed into the addingFunction as argument1 and 444 is also being passed in as argument2. Once they are both passed in we return the sum of the two arguments. return simply means that we will return something back to the method or function that called our function addingFunction. In the result, you can see that return sent back 777. The final statement that executed was more like document.write(777);

References

For Loop

JavaScript For loops are a little bit complicated, but you really need to understand them. It is a combination of a statement, a condition, and another statement. Typically, for loops iterate through code multiple times known as a loop. The great thing about for loops is that you can program them to run exactly how many times you want. Let’s just go ahead and jump into an example.

Example
for(var i = 0; i < 5; i++) //statement 1 var i = 0; condition i<5; statement2 i++;
{
    document.write(i);
    //write current value of variable i
    document.write('&lt;br/&gt;');
}
document.write(" End of for loop ");  
Result
0
1
2
3
4
End of for loop

The for loop is somewhat like a modified if statement that restarts itself until the condition is satisfied. Inside of the for loop we have a statement var i = 0; that declares a variable i and sets it equal to 0. Next, we have the conditional i < 5 that is the if part of the statement. We know that the conditional says if i < 5, then run the statements in the { }. Finally, we have an increment operator statement, i++, which is the most commonly used way to advance a for loop.

Since the ++ is after the variable, we will increment i after all of the statements in the { } have been executed. This is exactly why when we print i, document.write(i), for the first time it is 0 rather than 1. So, we run through the statements in the { } and we get the results 0,1,2,3,4. Right after the final execution of statements, i is incremented to 5, which was then compared against the conditional i < 5. It obviously is false at this stage; therefore, we move outside of the for loop and we execute the next line of code that happens to be our document.write(” End of for loop “); statement.

References