JavaScript Basics Part 7: Loops

Loops are used to execute the same statement of code a set number of times, which can be hardcoded or based on variable.

Loops are very common within programming, as they solve the problem of having to write more code to do the same thing multiple times. There are two different types of loops: for and while loops, which both perform looping tasks but in different ways, suitable for different problems.

for

The for loop will run for a set number of times then stop.

var I = 0;

for(I = 0; I < 5; i++) {
	Alert("My number"+ I);
}

If you had to write out a sentence five times, you could do it by writing out each statement. The code can become repetitive and will get hard to manage as you add more lines. Imagine it was 20 sentences, or even 100 sentences – just think of all the code you would have to write.

document.write('The next number after 1 <br>');
document.write('The next number after 2 <br>');
document.write('The next number after 3 <br>');
document.write('The next number after 4 <br>');
document.write('The next number after 5 <br>');

You can write the same code as above in a loop, which will be much easier to scale and manage as you need to add more items to the loop.

var numCount = 0;
for (numCount = 0; numCount < 20; numCount++) {
    document.write('The next number is' + numCount + '<br>');
}

In the proceeding example, I have achieved the same result as writing it out by hand, but only using 3 lines instead of 5.

I’m going to break down each step, so that you will understand how to write your own for loops.

  1. First I need to setup a variable “numCount” and assign it a value of 0.
    var numCount = 0;
    
  2. Next I add the word “for” followed by a parenthesis. I again set the variable numCount = 0, telling the script that I want to stop the loop once it reaches 19. And each time the loop runs, add 1 to the variable numCount. The loop will not work unless the numCount gets incremented each time.
    for(numCount = 0; numCount < 20; numCount++) 
    
  3. I will then add opening and closing brackets, with my action inside that I want to loop through. In this case, I want text to show up on the page that says “The next number will be 1″ and add a line break after it.
    {
        document.write('The next number is' + numCount +
    }
    
  4. I can increase the number of the times the loop runs by changing the numCount to be 20, 40 or 100, or 1000. It’s a much cleaner way to setup repetitive code, than to write it out manually.
    var numCount = 0;
    for (numCount = 0; numCount < 40; numCount++) {
        document.write('The next number is' + numCount + '<br>');
    }
    

While

The while loop will run until a condition is met, or as long as the condition is true. While loops are similar to for loops in how you can run something multiple times using one statement, but while loops are better for running a statement until an event occurs.

var i = 6;
while (i <= 6) {
    document.write("This is the" + i + "statement<br/>");
    i++;
}

In the above example, the variable is set to a value of 6, but that does not mean the loop will run 6 times. The condition says that while the value of i is less than or equal to 6, write the specified statement to the HTML document. In this case the while loop while only run once.

In order to fix the proceeding example so that the loop will run and the statement will be printed 6 times, we will change the variable so that its set to 0 and within the while condition we will set how many times we want the condition to loop. It’s the reverse of how a for loop is setup and can sometimes be confusing.

var i = 0;
while (i <= 6) {
    document.write("This is the" + i + "statement<br/>");
    i++;
}

JavaScript Basics Part 6: Conditionals

Logic is a part of our everyday lives – it’s a very familiar concept, therefore one of the easiest to understand. We are faced with questions all the time, with the “If” question being the most common. If I go to sleep early, I will be able to get up early. If I take this job, I will make more money. If I go to school, I will learn JavaScript. Using JavaScript, you can answer all of these questions using conditional statements.

Conditional statements allow you to setup the question or logic within your script, and if it is a true statement, then actions can be taken which are defined by you. Conditional statements create smarter scripts by performing an action based on something that has been setup in the program – it makes your scripts dynamic!

Similar to other languages, JavaScript offers designers and developers the use of the following conditional statements:

  • If
  • else
  • else if
  • switch

If Statement

An “if” conditional statement is setup with 3 parts: the if keyword that sets up the condition, which is located between the parenthesis, and the curly brackets is where the action is placed. The following is an example of how this is setup:

if (condition) {
    //action or event will go here if condition is equal to true
}

The if statement allows you to test a condition by seeing if it evaluates to true, then something will occur. The condition will often test two values (strings, numbers, and boolean values) using a comparison operator.
The following example uses the comparison operator “for is not equal to” (!=), to compare var a and 100. If the statement executes as true, the browser will display an alert message that says “Not Equal”.

var main = 25;
if (main != 100) {
    alert("Not Equal");
}

If you wanted to test the same variables above to see if they are equal to each other, all you need to do is switch in the (==) comparison operator.

var main = 25;
if (main == 100) {
    alert("Numbers are Equal");
}

This conditional statement will work fine in some situations, but there will be situations where you will want something else to happen if it doesn’t evaluate as true.

Else Statement

One of the main problems with using just an “if” statement is that if the condition returns false, the action will be ignored. If you are wondering what I mean, think about this scenario. If I get the job, I will take it. But what if you don’t get the job, this is where the else statement comes into play. As you could then say; If I get the job, I will take it. Otherwise, I will keep looking and interviewing for other jobs. The important thing to remember about the else statement is that it doesn’t have a condition, it is the condition.

The else statement gives you the option of doing something if the “if condition” comes back as false. In the example below, the value of foo has been set to 100. If the value of foo is not equal to 100, then show an alert that says “foo is not equal to 100!”. Otherwise show the alert “foo is equal to 100!”. Otherwise in this case means else, or the condition in the if statement returned false.

var main = 100;

if (main != 100) {
    alert("main is not equal to 100!");
}
else {
    alert("main is equal to 100!");
}

Else/If Statement

If you would like to test multiple conditional statements, you can add in “else if” after the first if statement. The script will first test the first if condition, if that is false, then it will run the second else if condition, if that is still false, it will execute the statement between the last else.

var topMenu = 25;

if (topMenu != 100) {
    alert("a is not equal to 100!");
}
else if (topMenu < 100) {
    alert("a is less than 100!");
}
else {
    alert("top menu rocks!");
}

You can use else/if statements to test multiple conditions, which is very useful in JavaScript. If you have a web form with 5 required fields, you can use an else/if statement to run through each field and check that something has been entered. If the user did not enter any value, you can create an alert that will show and apply the focus back to that form field. The following example code outlines how you would achieve this problem with JavaScript:

<form name="form">
	<input type="text" name="name" id="name"/>
	<input type="text" name="email" id="email"/>
	<input type="text" name="street" id="street"/>
	<input type="text" name="city" id="city"/>
	<input type="text" name="state" id="state"/>
</form>
<script>
if (form.name.value == "") {
    alert("Please add your name");
    form.name.focus();
    return false;
}
else if (form.email.value == "") {
    alert("Please add your email");
    form.email.focus();
    return false;
}
else if (form.street.value == "") {
    alert("Please add your street");
    form.street.focus();
    return false;
}
else if (form.city.value == "") {
    alert("Please add your city");
    form.city.focus();
    return false;
}
else if (form.state.value == "") {
    alert("Please add your state");
    form.state.focus();
    return false;
}
else {
    // If all the fields have been filled out, then continue.
    return true;
}
</script>

Advanced Conditional Statements

If you would like to test if multiple conditions are true within one if statement, you can do so using the logical operators.

In order to make a decision based on a variety of conditions, a logical operator to link those conditions together can be used.

In the following example: If I get the job and the salary is over 50,000, then I will take the job. The following code shows how this can be achieved in javascript.

var job = true;
var salary = 55000;

if (job == true && salary > 50000) {
    alert("Accept the job");
}

You can link as many conditions together as you need to, but it is important to remember that they all need to return true in order for your action within the curly brackets to occur. In the following example there are five conditions listed, although the fifth condition has an OR logical operator that precedes it. So either the first four conditions have to be true or the fifth condition has to be true, in order for the alert to show up. If none are true, then the else statement will come into effect and that alert will show.

var job = true;
var salary = 55000;
var dress = "casual";
var hours = 8;
var lunch = false;

if (job == true && salary > 50000 && hours == 8 && dress == "casual" || lunch == true) {
    alert("Accept the job");
}
else {
    alert("Don’t accept the job, there will be others.");
}

Switch

If you were planning on testing many conditional statements, the if/else/if can get hard to manage and you will end up with a lot of repetitive code, as seen in the example above. An alternative is to use a switch statement.

  1. Declare a variable to test against.
    var job = 5;
    
  2. . Set up the initial test using the switch keyword
    switch(job)
  3. Set up different cases to which I want to compare against the switch statement. In the following code, I am testing to see if the value of job matches any of the cases, and if so to show the alert, then stop the switch by using the keyword break.
    {
      case 5:
        alert("This is the one.");
        break;
      case 4:
        alert("This is the one.");
        break;
      case 3:
        alert("This is the one.");
        break;
      case 2:
        alert("This is the one.");
        break;
      case 1:
        alert("This is the one.");
        break;
    }
    
  4. Similar to the Else statement, I will setup a default case if none of the cases equate to true. In the following example, I am showing the switch statement from start to finish including the default case.
    var job = 5;
    
    switch(job) {
      case 5:
        alert("This is five.");
        break;
      case 4:
        alert("This is four.");
        break;
      case 3:
        alert("This is three.");
        break;
      case 2:
        alert("This is two.");
        break;
      case 1:
        alert("This is one.");
        break;
      default:
        alert("This is the default");
        break;
    }
    

JavaScript Basics Part 5: Arrays

An array is a variable which can store many values inside it. A variable can only store one value. Those values can be accessed at any time using the array’s index. The values stored within the array are called the members.

Creating an array
To create an array, declare a variable to hold values of the array, and declare the new Array object.

var navArray = new Array();

Alternately, you can also use a shorthand version, which will achieve the same outcome, where you wont have to declare the new array object.

var navArray = [];

Similar to variables, you can setup a new array and assign the values in one line by using shorthand. The variables can be a mix of numbers and strings.

var navArray = [“home”, “catalog”, “about-us”];

Accessing values in an array
To access the values that are now stored in the array, you use the array’s index. The index starts at 0, so if you wanted to access the “catalog” string, you would write the following:

var navArray[1];

Add values to an array
You can add values to an array at any point since there are no restrictions . You do so by using the push method.

navArray.push(“careers”);

Remove values from an array
You can remove values from an array by using two different methods. If you would like to remove the last item from an array, you would use the pop method.

navArray.pop();

If you would like to add the value as the first item in the array, you would use the shift method.

navArray.shift();

Length of an array
A useful tool that you can use when working with arrays is the length property, which will show you how many elements are contained within your array.

var navArray = [“apple”, “pear”, “orange”];
var navLength = navArray.length;
alert(navLength);

Arrays always start at an index of 0 and the navLength variable in the proceeding example would return a value of 2 in the alert. In the following example, I am showing the index values of the navArray, so you can see how indexes are laid out.

navArray[0] = “apple”;
navArray[1] = “pear”;
navArray[2] = “orange”;

JavaScript Basics Part 4: Variables

Variables offer a way to store values of strings, numbers, and boolean data types, as well as being able to reuse at any point within your script. Declaring or creating variables is a common practice when writing any sort of script or program. I will setup variables to store different bits of data that I want to access multiple times. They allow you to create cleaner, more readable, and more organized code.

There are two ways to use variables, the first is by just declaring a variable as show below:

var numClicks;

You can also declare a variable and set a value to it. The “var” syntax is used to declare the variable. You can also forego using the “var” text, and just set the variable to a value. Using the word “var” before declaring the variable is another way of keeping your scripts organized.

var numClicks = 12;
numClicks = 12;

In the second example above, I have also used an operator to assign a value to my variable. The assignment operator (=) is one of the more commonly used operators.

Variable rules and best practices
There are some important rules to follow when creating variable names.

Reserved Words
You cannot use any of JavaScript’s reserved words, which are used in the JavaScript language itself and using them would create a conflict.

Variable names
The names can be comprised of letters and numbers, but they have to start with a letter.

var mainBtn1;

Underscores “_” are allowed, but not dashes “-“ as they will be mistaken for minus signs or spaces.

var main_12453_bar;

Variable names are also case-sensitive, so the following four variable names will be interpreted as different variables, even though it’s the same letter, the case is different.

var mainBtn;
var Mainbtn;
var MAINBTN;
var mainbtn;

A common practice among web designers and developers is to use camelCase. To create camelCase, you make the first letter of the first word lowercase, and the first letter of the second word upper case and no spaces are present.

I will often use camel Casing when creating variable names and/or creating function names. It’s a nice way to adhere to a standard that other developers can immediately recognize, and it also helps avoid long names. I find it much easier to copy and paste since its all one word. A downside to camel Casing is when creating really long variable names or functions that can become illegible.

var mySpecialComputerForDoingMoreThanOneThingProgram;

JavaScript Basics Part 3: Strings

A string is anything enclosed within quote marks – it can be made up of letters, numbers, and/or symbols. Strings will work with either single or double quotes.

“hello world”;
‘I have 5 pears’;

When creating strings, there are often times when you will want to join one or more strings together. This is call concatenation, and is used by adding a “+” (plus sign) in between the strings you want to join together.

“hello” + “world”;

JavaScript Basics Part 2: Comments

JavaScript comments are a way to keep your code clean and easy to read. Comments cannot be rendered because the browsers skip them. Most web designers are probably familiar with HTML comments, which are similar to JavaScript comments with the exception of the syntax.

There are two types of comments that you can use in JavaScript: single and multiple line comments. Single line comments are created using two slashes “//” in front of the line of text. Multiple line comment blocks are created by wrapping the text with a slash and an asterisk “/*” and closing the comment block by adding an asterisk and a slash “*/”. In CSS, comments are setup in a similar way with multiple line blocks.

Single line comments:

// This is my first JavaScript Program
document.write(‘This is very cool stuff’);

Multiple line comment block:

/* This is my comment in JavaScript
which spans multiple lines */

Comments are a great way to document what your program is doing, but it’s important not to go overboard when adding comments, as they can add unnecessary bloat to your code. Comments will help other designers and developers understand your code. When distributing your code to the open source community, or to those who may not fully understand the JavaScript alone, comments can be very helpful.

JavaScript Basics Part 1: Statements

The basic components of JavaScript programs are statements, variables, and types of data.

A JavaScript statement is the most basic piece of JavaScript – which will represent a single action or step in the script that you are building. Many statements will represent a script, and they will always run from top to bottom, similar to how you read a book.

In the following example, there are two statements. The first will write the line ‘hello world, this is the edge’ to the document. The second statement will show a JavaScript alert to the user that says ‘say hello to the world’. You will notice at the end of each line is a semi-colon. It is used to tell the JavaScript interpreter that this statement has ended, and to move onto the next one. Without this semi-colon, the program will get stuck at whichever line is missing the semi-colon.

document.write(‘hello world, this is the edge’);
alert(‘say hello to the world’);

It is very common to see statements as part of a function in between two curly brackets.

How to setup Bronto Tracking Pixels with JavaScript

Recently at my job, I had to setup Bronto email tracking pixels on our order confirmation page. The tracking pixels came in the form of an image tag and had to be populated with some values from our shopping cart. The values (invoice number and order amount) are passed from the order confirmation page using hidden fields.

<input name="InvID" type="hidden" id="InvID" value="12345" />
<input name="Tot" type="hidden" id="Tot" value="69.9900" />

I then used JavaScript to extract the values in the hidden inputs and assigned them variables.

var InvoID = document.getElementById("InvID").value;
var SubTotal = document.getElementById("Tot").value;

Then, I used document.write to create an image tag on the fly with the correct values filled out using JavaScript concatenation.

document.write("<img src='http://bronto.com?type=$&description="+InvItemName+"&money="+ItemPrice+">'");

I have recently found that if you have apostrophes in your code, it will break the above tracking script. A way around this would be to use a string replace function like this:

InvItemName.replace(/'/i,"")

*NOTICE: The values in the scripts are dummy values, as I had to hide some confidential account data. The code is just to show as an example, but its pretty easy to setup. You can use similar techniques to setup Google, MSN, Yahoo, and other types of tracking pixels.