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

Window Object

The JavaScript window object has quite a few properties and methods, but beware because many of them are not supported in all major browsers. However, the information you can obtain using the window object can be extremely important depending on what you want to do. For example, maybe for some reason you want to know the size of the user’s window. Using the window object is the primary way you would get this information.

The JavaScript window object isn’t used very often, but it is quite powerful. For example, one of the window object’s methods is a print(). So, you could create a button on the page that would trigger an event that called the window.print() rather than the user having to search in the browser for the hidden print option. One cool distinction about the window that you may notice is that you can directly type something like alert() and not window.alert() and JavaScript will completely know what you are talking about. That is because window is the primary object of a browser, which means you don’t need to declare it before the method unlike the other objects.

Common Window Object Properties

innerHeight – gets or sets the inner height of the actual content area

Example
document.write(window.innerHeight);
Result

473

innerWidth – gets or sets the inner width of the actual content area

Example
document.write(window.innerWidth);
Result

662

navigator – we discuss this in the Navigator Object tutorial

outerHeight – gets or sets the outer height of a window (This includes tabs, toolbars, and scrollbars)

Example
document.write(window.outerHeight);
Result

728

outerWidth – gets or sets the outer width of a window (This includes tabs, toolbars, and scrollbars)

Example
document.write(window.outerWidth);
Result

680

Common Window Object Methods

alert() – shows an annoying alert box

print() – prints the window’s contents (Many users don’t know how to print a web page. Make it easy for them.)

Example
function exampleFunction3()
{ 
    window.print();
}
<input name="" type="button" onclick="exampleFunction3()" value="I Print"/>
Result

scrollTo() – scrolls to specified x and y coordinates

Example
function exampleFunction4()
{
     window.scroll(0,30)
}
</script>
<input name="" type="button" onclick="exampleFunction4()" value="I Scroll"/>
Result

Timers

Timers are a method of the window object. They can be very tricky, but often very useful when dealing with a variety of issues. While a good amount of timers are used correctly, JQuery’s animate can often do your job much more efficiently. Please be sure to check out a few of JQuery’s functions before using timers.

Example
var timeoutTimer=setTimeout("alert('10 seconds!')",30000);// This fires once
var intervalTimer=self.setInterval("intervalTimerFunction()",10000); // This fires every 10 seconds
function intervalTimerFunction() // intervalTimer calls this function
{
    alert('intervalTimer timer happened');
}
<input name="" type="button" onclick="clearTimeout(timeoutTimer)" value="Stop timeoutTimer"/>
<input name="" type="button" onclick="clearInterval(intervalTimer)" value="Stop intervalTimer"/>

Try and Catch

JavaScript has a great way to deal with errors. Try and catch are a way to handle errors. Normally, if an error occurs, a couple of things might happen:

  • The browser will error silently causing some JavaScript code around the where the error occurred not to be executed.
  • The browser will create annoying pop up boxes alerting the user that an error occurred.

Neither of the following options are ideal, which is why we like to handle errors on our own. Let me start by not suggesting that your whole code is written in a try/catch statement. While that may not be a terrible idea for beginners, it is extremely impractical. Generally, I will use try/catch statements when dealing with user input. Of course, there are many of great reasons to use try/catch statements.

When you are writing JavaScript, try to think of how your code could possibly mess up and cause an error. If you can think of way that it is possible, use a try/catch statement.

Example
                var animalArray = new Array("Meerkat","Dog","Squirrel");
                var userInputVariable = document.getElementById('exampleTextField').value;
                try
                {
                    document.getElementById('inputTest').innerHTML = animalArray[userInputVariable].length;
                }
                catch(e)
                {
                    document.getElementById('inputTest').innerHTML = "Please type a 0, 1, or 2.";
                }

Let’s say for some random reason we want a user to enter a number between 0 and 2. Whatever number they enter will return the length of that item in the array. If the user enters a 0, which is “Meerkat” in our animal array, our code will output 7 in our div with an id of inputTest. When a 1 is entered, the output is 3. However, if the user inputs a 4, we cannot check the items length because it doesn’t exist. Normally, we would get an error here, and in fact, we do. Since we caught the error with catch, we can tell the browser what to do instead of what it would normally do when it finds the error. In this case, we change our div inputTest to show “Please type a 0, 1, or 2.”

To make our try/catch error handling even smoother, throw can help us break down the error even more.

Example
                var animalArray = new Array("Meerkat","Dog","Squirrel");
                var userInputVariable = document.getElementById('exampleTextField2').value;
                try
                {
                    if(userInputVariable > 2)
                    {
                        throw "Err1";
                    }
                    else if(userInputVariable < 0)
                    {
                        throw "Err2";
                    }
                    else if(isNaN(userInputVariable))
                    {
                        throw "Err3";
                    }
                    else
                    {
                        document.getElementById('inputTest2').innerHTML = animalArray[userInputVariable].length;
                    }
                }
                catch(e)
                {
                    switch(e)
                    {
                        case "Err1":

document.getElementById(‘inputTest2’).innerHTML = “That value is too high.”; break; case “Err2”: document.getElementById(‘inputTest2’).innerHTML = “That value is too low.”; break; case “Err3”: document.getElementById(‘inputTest2’).innerHTML = “That value is not a number.”; break; default: document.getElementById(‘inputTest2’).innerHTML = “Please type a 0, 1, or 2.”; break; } }

Look at all of that code. It might be somewhat lengthy, but test this result out with the result from the earlier example. It actually shows the user what they are doing wrong, rather than the blanket statement of “Please type a 0, 1, or 2.” We are putting conditions into our try statement. If the user input satisfies any of our conditions, except for the else, we will throw a certain type of error. For instance, when the user inputs a 4, it will satisfy the condition of userInputVariable > 2, which will throw an error of “Err1”. When it throws the error, catch will start running. Since our current error is Err1, when will execute the statements in the case “Err1”:. The statement will change inputTest‘s value to “That value is too high.” Always try to use the some sort of fallback plan when using throw. In my example, my fallback plan is my default in the switch statement.

References