A Brief Introduction to JavaScript & Programming

By Philip Likens

Introduction

This introduction to JavaScript was written by Philip Likens for use in the Programming Logic class at the Art Institute of Dallas - it is therefore written for students with no programming background. Along your reading you will notice a few things. First of all, you will notice I have put code in a different font. That is so you can tell what is code, and what is not. Commentary is in a blue color but is usually still in the code font as you are allowed to put comments in code. You will also notice little notes throughout the page set apart inside of a box. These are things you should pay attention to, but may not be directly applicable to what we're talking about, but are related in some way. Lastly, if you have questions, suggestions or revisions send them to me at plikens@aii.edu.

The Fundamental Elements of JavaScript & Programming

This section is primarily concerned with introducing you to the basic elements of JavaScript. Most of the concepts introduced here are similar or the same in other programming languages. As such, this section will be mostly for initial reading, understanding and reference with less of a focus on "doing". We will focus on doing once we get past these basics. This should be similar to driving a car. You didn't drive (or shouldn't have anyway) a car on the road for the first time without learning what a traffic light is, the difference between a stop sign and a yield sign, etc. However, just because you want to get into the actual coding, does not mean you should skip this section. Please read through these basic concepts before proceeding. This page was written in such a way as to take you from no knowledge of JavaScript, to creating scripts that work.

What is Scripting or Programming?

Scripting and Programming are similar terms and essentially describe the same process - scripting or programming is the process of writing a script or program. This begs the question, what is a script and how is a script different than a program?

A script and a program are technically different, but very similar. A script is a series of commands or communications written in a specific language to do a specific task. For instance, I could say to you in English "Go pick up the ball." The phrase I just spoke to you is a command in a language you understand, that tells you to do a certain thing.

The difference between a program and a script is not in their core definition, but in the way they go about their task. A script is typically code written to execute, or run, inside a program (like a web browser) whereas a program, theoretically, is written to run independently of other programs. We will be scripting in JavaScript. However, as I said before, scripting and programming are nearly the same process and the basic fundamentals of scripting are the same as the basic fundamentals of programming. That is why the class you are taking is referred to as Programming Logic - the logic is the same in scripting and programming, we just happen to be learning scripting languages here because they are more applicable to our field.

What is JavaScript?

JavaScript is a scripting language that is designed to add interactivity to HTML pages. On the web there are two places a script will typically be executed - in the browser (on your computer) or on the server. Scripts executed on the server are run before a user downloads a web page, thus the user will never see the script in action, only the results. JavaScript, however, is executed client-side, meaning that it runs in the browser while the user is looking at the page.

For more information on how JavaScript got its name, where it originated and the like, check out the JavaScript Wikipedia page.

Java and JavaScript are two different languages - so when you're referring to JavaScript, you say it's name in its entirety, rather than abbreviating it.

How do I view JavaScript?

JavaScript is generally meant to be coupled with HTML, so you will embed your script in an HTML file and open the HTML file in the browser. It is possible to save JavaScript into a .js file, but you would not open that file independently of an HTML file.

For our purposes we will always write our code inside an HTML file unless otherwise noted. To view your code in action, simply open that file in a browser. The browser I recommend is Firefox, specifically because it has a free add-on called Firebug that you can download. Firebug is a great help when you're trying to figure out what is wrong with your JavaScript code - something that we'll detail later on.

Three Layers of the Web

You can think of the web as having three layers. One layer is the content/structure - this is generally XHTML. The XHTML layer provides a structure for your content. XHTML gives you a way to define a heading as a heading, a paragraph as a paragraph, but does not provide much styling or behavior by default.

The next layer is the styling - this is your CSS. CSS gives you a way to make your page look any way you want it to. You can change font colors, sizes, add padding and margin, and even go as far as hiding content that is already there.

The final layer of the web is the behavior layer. Behavior on the web is typically defined with JavaScript. JavaScript allows us to give interactivity to our page. For instance, when I fill out a form and submit it, we can use JavaScript to check the contents of the form and make sure all the fields have been filled out correctly. If they haven't, we can ask the user to complete the form. This is a way of defining the behavior of the page.

It is generally accepted that keeping the three layers separated as much as possible is a good idea. In other words, keeping your structure and content free of styling or behavior is generally the way to go. In the end, this is what we will attempt to do, however, while we are learning the basics we will not focus so much on that separation.

OOP (Object Oriented Programming)

Object Oriented Programming is a method of programming, built around objects. Some popular object-oriented languages include C++, Java, Actionscript (Flash), and Javascript (for a more complete list, see this wikipedia article). Objects offer a method of organizing data into a single unit. The concepts we will talk about in this writing focus around OOP.

The basic terms of OOP are objects, methods and properties. Objects are simply things in programming. Sort of like a car is a thing or a tree is a thing in real life. Methods are basically what the object does or what can be done to an object. So a car could go, or stop. A tree might be able to grow or fall down. Properties are simply bits of information about the object. So the car might be blue, it might be an SUV. A tree might be a banana tree, it might have 5 pieces of fruit.

Script Tags

JavaScript works well with HTML. Any time you put JavaScript in your document (save a couple rare occasions), you will house your JavaScript between two HTML tags called script tags.

<script type="text/javascript">
Some JavaScript would go here...
</script>

<script type="text/javascript" src="someExternalFile.js"></script>

Script tags are written very similarly to the <style type="text/css"></style> style tags of css, but with "script" and "javascript" rather than "style" and "css" . You can put script tags in between the <head> tags of your document, or between the <body> tags of your document. Script tags should not be placed between the closing </head> tag and the opening <body> tag in what I like to call "no man's land." Doing so will cause you problems.

Every once in a while you'll see someone write script tags as: <script language="javascript"> </script>. The language attribute is deprecated, meaning it's no longer a valid way to write script tags. You should write them as we discussed above.

Any time you see JavaScript from here on out in this tutorial, it is assumed to be inside <script> tags unless otherwise noted. So if you're trying to copy and paste the examples, be sure you have script tags in either the head or the body of your HTML document, and you're putting your JavaScript between those script tags. JavaScript will generally not work otherwise. Here's an example document for you to use as a guide:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My First JavaScript!</title>
</head>
<body>

<script type="text/javascript">
// all your code should go in here
</script>

</body>
</html>

Later on I will make an argument for not including script tags in the body of the document in order to separate content and behavior as we have separated content and style with css. But for now, while you are learning the basics, it's ok to go ahead and put your JavaScript in the body of your HTML document.

The second example above is the way you embed an external JavaScript file into your HTML. Again, just like css, JavaScript may be housed in an external file. If it is, you have to embed (or link to) that external file before we can use that code in our HTML file. Without that link, the browser would not know where to look for your JavaScript. Notice, it's the src attribute that links to an external file. Also notice that we cannot have a self-closing script tag. Even though there is nothing between the script tags in our second example, we must have both tags present.

Statements and semi-colons

Any Scripting or Programming language is, at it's essence, a sequence of statements that tell the computer what to do. JavaScript is no exception. JavaScript is merely a sequence of statements telling the browser what to do - typically modifying the behavior of the HTML file the user currently has open.

JavaScript, like all languages, has it's own syntax. That is, JavaScript has it's own way of communicating with the browser. You must follow the rules (syntax) of JavaScript if you wish to write code that actually works. In it's most simple form, you can write a single line of JavaScript as whatever code followed by a semi colon. An example might look like this:

alert("hello world");

Alert is a command or a statement in JavaScript, and it's followed with a semi-colon. The semi-colon simply tells the browser "this is the end of my statement," much like a period does in the English language. JavaScript will only execute one statement at a time, and each statement should be followed by a semi-colon. It is good practice to only write one statement per line.

JavaScript statements are executed from the top down, unless we give the browser a command contrary to this. But the general rule is that JavaScript starts at the very top, with the first command, and works it's way down, executing commands along the way, until it has reached the end of the script.

Commenting

JavaScript allows us to put comments in the middle of our code to remind ourselves, or to tell other people, what a certain a piece of code is doing. You'll notice that I put comments in some of the examples below. In this tutorial my comments will always show up in blue.

A comment in JavaScript may be written one of two ways. Both options are valid, though you may choose which suits you best. The first is simply by prefacing the comment with two slashes. This is useful if you have a single line, or a part of a line that you want to set aside as a comment. It is important to note though, anything else on that line after the two slashes will be viewed as a comment by JavaScript - thus, any JavaScript you want to execute must come before your comments on any give line. For instance:

// This is a comment
Some JavaScript code; // This is another comment

Both are valid comments - you may start a comment on it's own line and devote that whole line to your comment, or you may devote the rest of a certain line of code to a comment.

The other way of commenting is a multi-line comment. It acts like a paragraph tag would in HTML in the fact that anything between the opening and closing /* */ will be considered to be part of the comment (like anything inside the paragraph tags would be considered part of the paragraph). It is shown below:

/* This is a comment
This is still a comment
And again, still a comment */

If you do not want a line of code to run when you run your program, but are not yet ready to delete that particular line, you may comment your code out by putting a // in front of that line.

Errors

Compilation Errors

Compilation errors, or Load errors are the most common types of errors. These errors are caught by the browser as it tries to run (execute) your code. Compilation errors prevent scripts from running altogether. Generally these errors are caused by mistyping some part of your code. These errors could be caused by not typing the correct type of quotation mark or misspelling a key word, among other reasons.

Runtime

Runtime errors are errors that occur as your code is executed. This could include dynamically writing some text outside the body tags, or expecting a certain number but receiving another.

Logical

Logical errors are a little more tricky. Logical errors, as the name implies, are errors in your logic. The syntax of your code may be fine, but what you are telling the code to do may not. For instance, if you told me to get into my car but didn't tell me to open the door first - that would be a logic error. In JavaScript a common logic error would be using an = (assignment operator) where you meant to use an == (evaluation operator).

Debugging

The process of identifying errors in your code is called debugging. An error in code is usually referred to as a bug. So to "debug" your script is to rid your code of error. There are a few different tools that can assist you in debugging your scripts, but we will only go into a couple of the options here.

Firebug

Firebug is an add-on to FireFox that is available for free download. Firebug will alert you to errors in your JavaScript, giving you the line number and, as best as it can tell, what's wrong with your code. Firebug also allows you to insert breakpoints and watch variables so you can step line by line through your program to figure out what's going wrong.

Vocal Trace

Vocal tracing is simply walking through your code by reading each piece of code aloud (quietly). If you read your code silently, your brain tends to fill in the gaps making the code seem syntactically correct. However, many times by reading the code aloud you'll notice errors as you speak them. This is a really good way to find logic errors.

Take a Break

Taking a break is often a good way to find errors, though it might seem counter-intuitive. If you've gone through Firebug and Vocal Trace and not found the problem with your code, it might be that you've been looking at your code too long. Many times just taking a break, going outside, grabbing a drink or a snack, then coming back to the code is a good idea. Often the break will allow your brain to "reset" and you will see your error quite easily when you come back to it.

Phone a Friend

If you have tried everything else, try asking someone else to look at your code. Many times another person will be able to spot an error in your code very quickly. This should be your last resort however, because you should learn to debug your own code.

Variables

Variables are one of the fundamental elements of virtually all programming languages. A variable is simply a container for storing information. Think of a variables as boxes with a label. You can put something in a box. If later you want to see what's in the box, all you have to do is find the box with the particular label and look inside. A variable has three attributes at all times - a name, a value and a data type. We'll look at name and value now, then data types a little later on.

A variable can be named virtually anything, however there are a few rules you must follow.

The syntax for writing a variable is as follows:

var variableName;

You use the "var" keyword in front of a variable to declare the variable for the first time in your script. It's like saying "this box" or "this container" will have a certain label. In the example above, we declare we're creating a variable with a name (or label) of "variableName". Remember, follow each statement with a semicolon.

Above we stated that a variable is a container. So far we have only declared that we have a container with a certain name, but we have yet to put any information in our container. The example above declares the variable without a starting variable, the examples below declare each variable with a starting value - you may declare your variable with or without a starting value, it is up to you. If you declare a variable without a starting value, it will be "undefined" until you give it some sort of value.

var x = 5;
var friendName = "Tyler";
var response = true;

You'll notice we used an equal sign to give our variable a value. This is called "assigning". We are "assigning" our variables to be equal, or to contain, certain values. An equal sign is known as an "assignment operator" because it tells JavaScript that we are attempting to assign a variable to a certain value.

Because a variable simply contains information, we can replace or update the current information at any time. The way you do so is the same way we assigned our initial value, except we leave off the var keyword. Once you have declared a variable using the var keyword, you should not declare it again the rest of the document. It's sort of like announcing that the queen has arrived. It is only necessary to make the announcement once, you do not need to make the announcement every time you see or talk to her.

x = 3.14;
friendName = "Marla";
response = false;

So, initially we declared x as a variable and assigned it the value of 5. Then we went on to update the value, setting it to 3.14.

As we said before, not only can we put information in our variable, but we can also see what's inside a variable. To read the contents of a variable, we simply type the variable name without an assignment operator after it. For instance:

x; // would show 3.14
friendName; // would show Marla
response; // would show false

These would all show their contents to us. They wouldn't show their contents to the user, but this is the syntax we would use to see what's inside our variables. Later on we will discuss how we actually show the user what's inside our variables.

Primitive and Composite Variables

There are two types of variables: Primitive and Composite. Primitive variables hold information such as Numbers, Strings, Boolean values, Null and Undefined. Primitive variables are the basic building blocks of a program. They are limited to storing only one piece of information at a time, though as we've seen that information may be switched out whenever we would like. Composite variables are capable of holding multiple values at one time, among other things. We'll go into all the features of composite data types when we get into Arrays, Functions and Objects.

Data Types

JavaScript works with a number of data types. We've shown examples of the Number, String and Boolean data types above, though we haven't yet called them by that name. A data type just refers to the type of data a variable holds. When we set x = 5 above, we could say "x is of the data type Number." Similarly, when we set friendName = "marla", friendName is now of the String data type. You can switch a variable's data type dynamically by switching what's stored in the variable.

Most programming languages will not allow you to switch a variable's data type on the fly. This is the difference between a "loosely" and "strongly" typed language. A strong-typed language is one in which you must declare a single data type for the entire life of a variable. So if x were declared to be a number, it would be a number now and forever. JavaScript is a loosely typed language - you can switch the data type dynamically by reassigning the value of a variable to be an alternate type of data.

var x = 5; // x is currently of the data type Number
x = "blue"; // now x is of the data type String

In order to check the Data Type of a variable, you can use the typeof operator. For example:

var singer = "Marla";
typeof(singer); // would give us data type of "String"

Number (Primitive)

The Number data type contains a variety of different values. Specifically, numbers can be whole numbers (integers), floating point (decimal), negative or positive values. Observe:

var usefulNum = 3.14;
var age = 25;
var temperature = -500458039;

Boolean (Primitive)

The Boolean data type has two valid options: true or false. Notice these values are not in quotations. If we put true in quotations it would change the data type to String. The same is true for false. The proper way to declare a Boolean variable is displayed below:

var blueSky = true;
var greySky = false;

String (Primitive)

A string is simply a row of characters enclosed in a single pair of matching quotation marks. Strings may be enclosed by either single quotes or double quotes, however the type of quotation you use must be the same at the beginning and the end. Examples of strings are as follows:

var joke = "Why did the chicken cross the road?";
var character = 'a';
var ducks = "512";
var answer = "false";
var HTMLCode = "<br />";
var quotation = "It's his fault";

Notice that the variable ducks is of the String data type. That is because "512" is in quotations. The same is true for our variable answer - "false" is a String, not a Boolean, because it is in quotations. As you can see, Strings can be anything as long as they are in quotations - even bits of HTML.

Any time you have a word of phrase outside of quotations JavaScript will assume it is either a variable or a keyword - thus strings should always be in quotations.

Once we open a string with a quotation mark, JavaScript will begin looking for a quotation mark of the same type. When it finds a match, it ends the string. With that in mind, here is an example of a string that doesn't work.

htmlCode = "<a href="index.html">home</a>";

In the example above, "<a href=" would be understood as a string, index.html would be outside a string, then ">home</a>" would be seen as a string again because JavaScript will always attempt to pair a beginning quotation mark with the next quotation mark of the same kind. However, if you instead used the following code, JavaScript would understand it correctly because the beginning single or double quote is not repeated to till the end - the quotes in the middle are not of the same type and therefore do not end the string prematurely.

htmlCode = '<a href="index.html">home</a>';
htmlCode = "<a href='index.html'>home</a>";

Escape Sequences

Another way to solve the problem above is to use escape sequences. Escape sequences provide a way to put double quotes within double quotes or single quotes within single quotes without JavaScript misinterpreting what we meant. A few examples of escape sequences are as follows:

htmlCode = '<a href=\'index.html\'>home</a>';
// escape sequence \'
htmlCode = "<a href=\"index.html\">home</a>";
// escape sequence \"

The backslash before the character indicates to JavaScript that it should use the quotation mark as a character rather than part of it's JavaScript code, thus leaving the whole string intact. Other escape sequences include \t for tab and \n for new line - which are especially handy for dialog boxes or preformatted text. We will get to those later.

Null (Primitive)

Null is the data type that is used to mean "no value" or "nothing". Both a value of 0 or a string value of "" are not considered null - they still have some value. Only by using null will a variable be truly equal to nothing.

var paper = 0; // not null
var street = ""; // not null
var soap; // not null - see undefined
soap = null; // null

Undefined (Primitive)

Undefined is the value that a variable has when it has been declared without a starting value. It essentially means that we don't yet have a value for that variable, but we will in the future.

var company; // undefined

Array (Composite)

An array is a collection of values, usually with some similarity. You declare an array the same way you declare any other variable, but the variance comes when you assign it a value. Any time you declare a new array you should assign it the value new Array(). This tells JavaScript that this variable will hold multiple pieces of data, rather than just one. If you know how many pieces of data you will want your array to contain, you may put that number between the parenthesis.

var classMates = new Array();
var teamMates = new Array(53);

JavaScript will then allow us to put multiple values into our array. An array is nothing more than a collection of values, however those values are organized in a certain order, which we will assign. You may think of arrays as a parking lot. Each car occupies a certain spot and those spots are aligned in a certain order. In order to refer to a specific car, you could say "the car in the second spot." Anyone who can count would know which car you were referring to. Similarly, if you want to put a certain car in a specific spot, you can.

However, arrays are a little funky compared to what you're used to. Arrays start at an index of 0. "Index" is just another name for the position of an item inside our array (which spot our car is in). So the "first" spot is really index 0. So when you go to populate your array with values, you being with 0.

The way your reference an array, whether you're going to read the value of a specific index, or insert/replace the value of an index, is by typing the array name then an opening [ square bracket, followed by the index, then a closing square bracket ]. JavaScript then knows that the value between the two brackets is referring to a specific index.

For instance, in the first example below we are setting (or assigning) the index 0 of the classMates array to be equal to the String "Tyler". On the second example we are reading the value of our array at the index of 0, which will give us the value "Tyler". The only difference between the two is on the first we are assigning a value with the equal sign whereas on the second we are merely reading the value.

classMates[0] = "Tyler";
classMates[0]; // would give us the value "Tyler"

If you already know the information that an array will contain, you may include it when you declare your variable, thus saving you the trouble of adding information later.

var roomMates = new Array("Geoff","Kent","Tim","Matt");
var thirdFloor = new Array(302,305,316,320,322);

In our roomMates array, Geoff is automatically assigned index 0, Kent index 1, Tim index 2 and Matt index 3. Notice when we declare our array with initial information as we have done above, each piece of information is separated by commas. In the same way, thirdFloor is being loaded with five pieces of content. Observe the difference between the two arrays: roomMates contains all string data (data in quotation marks) whereas thirdFloor contains all numeric data (thus needing no quotation marks). You can also have arrays that contain Boolean values. Additionally, you can mix the contents of an Array to store both Numbers and Strings, or Strings and Boolean values. Arrays are flexible enough to contain any primitive data types you would like. You may also put variable data into an array:

var firstName = "Robert";
var club = new Array(firstName); // club[0] is now equal to Robert

Notice firstName is of the string data type, but it is an array. Whenever you want to see the contents of a variable, you merely put the variable wherever you want that particular value, without quotations around it. So club[0] would be "Robert" because "Robert" is the value we were storing inside firstName.

Thus far we have talked about what are known as "numeric" arrays. Meaning, you access the arrays by a numeric index ( ex. club[0] ). There is another type of arrays known as Associative Arrays. An associative array provides a way of storing information with a string index, rather than a numeric index. Essentially an associative array would function as the following:

var postalCodes = new Array();
postalCodes["Lewisville"] = 75067;
postalCodes["Flower Mound"] = 75028;
postalCodes["Lewisville"]; // would show 75067

One other note about declaring or populating an array: You may declare an array without using the new Array() syntax by simply using opening and closing square brackets.

var myArray = [];

Functions (Composite)

Functions are bits of reusable code. Functions provide a way of doing a certain process, based on certain inputs, multiple times. You can think of a function sort of like you would like of an ATM - you put in certain pieces of information (your card, your pin, possibly a deposit) and the ATM executes a certain process. The ATM, depending on what you put in and what it was programmed to do, might return a receipt, return some cash, or simply process the information and update your bank accounts. The next person can then come and put different information into the ATM, and the same processes will be run.

There are certain built-in functions that we have yet to explore, but you will use, and also you have the ability to write your own. User defined functions can be very simple or very complex, depending on your needs. Here is the structure of a function.

You'll notice that we don't put semi-colons on every line of a function. Semi-colons are only needed for the statements contained within the function. The same is true for conditional statements and loops, among other things.


You'll also notice that we indent the code inside a function. In JavaScript you typically indent, or tab over, any time you have code within squiggly brackets. The more your code is nested within brackets, the more we tab over. This is the same concept as tabbing in HTML, you tab the li tags of a ul over once to show that they are children of the ul tag.

function name ( parameter1, parameter2... )
{
statement;
statement;
...
}

The syntax for a function is the keyword "function" followed by a space and the name of the function. Functions can be named in the same manor as a variable - be sure to stay away from spaces and keywords. Next you open parentheses. Inside the parentheses you can put parameters. A parameter is simply a way of passing information into a function (like a pin number into an ATM). You can set up as many parameters that you want. When you call a function, you simply put in the information you want to pass, and the function will catch the information you put in. Following the parentheses is an opening squiggly bracket followed by your statements (the code you want your function to contain) and then a closing squiggly bracket.

A function is essentially "code for later" meaning that any code within a function will not execute without a function call. Meaning, when you go to use an ATM it's just sitting there, it isn't working on it's own. It isn't until you interact with the ATM that it begins to execute the code locked inside. In the same way, we have to "call" a function, or tell it to run, before it will execute. The way you call a function is shown below:

name( parameter1, parameter2... );

You do not have to use parameters with functions. A simple function and call might look something like this:

function sayHi ()
{
alert("hello world");
}

sayHi();

We'll get into exactly what the statements inside the function do later, all you need to know for now is that whenever we call our function with the line sayHi();, every statement between the squiggly brackets { } will execute.

In addition to being able to execute statements, you can also create your own variables inside a function:

function catchPhrase ()
{
var phrase = "His name is..."; // phrase is equal to "His name is..."
}

catchPhrase();
// outside the function phrase is equal to nothing

When you create variables inside functions you run into a problem known as scope. Scope simply describes where a function is visible or available in a program. Meaning, if I ask JavaScript what the variable phrase is equal to outside my function, it will not know.In fact, if I ask JavaScript what phrase is equal to outside my function, it will not even know a variable named phrase exists. Again, if we go back to the ATM analogy - I do not know what's going on inside a function and a function does not know anything of the outside world. We have to use parameters to pass in information about the outside world, and we have to use "return" to pass information back out to the world.

This is not strictly true - a function can see the outside world, but it is best practice to pass in any information your function should require, rather than pulling information straight from a variable outside a function. The reason is that it's much easier for a fellow programmer to understand what is going on in a function if they can look at the call, and look at the setup of the function and see all the variables being passed in. It gets much more confusing if you are just randomly pulling in variables as you need them without passing them through the call in the proper way. For that reason, I use the language that it cannot be done to try to emphasize the fact that it should not be done. You should always pass in information through parameters and out through return.

If we want to add a parameter to our function, it might look something like this.

function sayName (name)
{
alert("hello " + name ); // name will be equal to "bob"
}

sayName("bob");

You'll notice, in our function declaration we put name in the parentheses. Name is a variable we automatically create when we place it in our function. We can then put the string "bob" inside our call below and "bob" will be passed into our variable name in our function - so when our function executes, the variable name will contain "bob". You can create and pass in as many parameters as you would like, separated by commas.

Earlier I mentioned that a function cannot see to the outside world, nor can we see the variables inside a function. Fortunately JavaScript provides us a way to return information, much like an ATM returns a receipt. This is done with the keyword return followed by the data we want to return - whether it be a number, a string, or a variable.

function doMath (fNum, sNum) // fNum = 5, sNum = 7
{
return fNum+sNum; // it will do the math & return the result
}

var sum = doMath(5,7); // sum will be equal to 12

When you do a return, JavaScript effectively replaces the call with whatever you return. So where JavaScript originally read the line as var sum = doMath(5,7);, once our function is executed and our return takes place, JavaScript will now see our line as reading var sum = 12;. Whatever we returned, in this case the number 12, will replace our function call. In this way, we can set a variable outside our function to "catch" whatever value our function returns. A function can return a Number, String, Boolean or Array. When you return an array, you must access the variable catching the return value as you would an array. For instance:

function getList ()
{
var list = new Array("Bob","Joe");
return list;
}

var myList = getList();

You could then access the values you returned as myList[0] or myList[1] containing "Bob" and "Joe", respectively.

Objects (Composite)

Objects are essentially a collection of all other Data Types. You can think of an object like a car. A car is composed of all kinds of different things - doors, handles, speakers, wheels, paint, leather, metal, etc - but all together, it is a car. In the same way, an object gives us a way to collect all the other data types into something bigger. Additionally, and this is their real value, they give us a way to logically group a collection of functions and variables together into one collective unit. We can then access and change those functions and variables as part of one unit. When a function is part of an object is it referred to as a method. When a variable is part of an object it is referred to as a property. You can think of methods as what the object can do (a car can go, stop, etc), and properties as descriptors, or things about an object (a car has a color, a speed, etc).

We will spend more time with objects later on.

Operators and Expressions

Arithmetic Operators

There are five basic types of Arithmetic Operators: addition ( + ), subtractions ( - ), multiplication ( * ), division ( / ), and modulus ( % ). All of these work the way you might expect them to and are exhibited in the examples below. The modulus operator may not be something you are familiar with, but essentially the modulus operator will get the remainder of one number divided into another. For instance, 5 divided by 3 is 1 with a remainder of 2. The modulus operator allows you access to that remainder of 2. Take a look at the examples:

var num1 = 5 + 10; // 5 + 10 equals 15
var num1 = 10 - 8; // 10 - 8 equals 2
var num1 = 3 * 4; // 3 * 4 equals 12
var num1 = 3 / 2; // 3 / 2 equals 1.5
var num1 = 7 % 3;
// 7 % 3 equals 1 (7 / 3 = 2, remainder of 1)

Order of Operations

Order of operations in JavaScript go in the same basic order as the mnemonic (Please Excuse My Dear Aunt Sally) you learned as a child: Parentheses, Exponents, Multiplication, Division, Addition, Subtraction - with the exception of exponents which are handled with the Math object (which we'll talk about later) and Modulus which wasn't addressed (modulus is on the same level as division). You may have noticed, we've talked about all of these except parentheses. Parentheses are available to us in JavaScript and will allow us to execute certain code before anything else. Behind parentheses, multiplication division and modulus are handled next in a left to right manor. Finally addition and subtraction (and concatenation which we'll address next) will be executed, again in a left to right manor. Observe the following examples:

var num2 = 6 * 4 / 3 + 2 - 1; // 6*4=24, 24/3=8, 8+2=10, 10-1=9
var num3 = 6 * 4 / (3 + (2 - 1)); // 2-1=1, 1+3=4, 6*4=24, 24/4=6

Notice the difference between the two examples. On num2 we do the multiplication first, division second, addition third and subtraction last. For num3 we begin with the expression in parentheses, innermost first. So we do 2 - 1 which is 1, then we add 1 to 3, at which point we're done with our parentheses. Our equation now looks something like this: 6 * 4 / 4. Since multiplication and division are done of the same level, the execution order is left to right. 6 * 4 equals 24, 24 / 4 equals 6.

Concatenation

Concatenation is the name for adding or combining two strings together. Concatenation is done with the same operator as addition ( + ) and is handled automatically by JavaScript when strings are involved. In addition to adding two strings together, if you try to add a number to a string they will concatenate automatically as well.

var someText = "blue" + "dog"; // "bluedog"
someText = "green" + 21; // "green21"
someText = "red" + 15 / 3; // 15/3 = 5, "red" + 5 = "red5"

Assignment Operators

The first type of assignment operator available to us in JavaScript is a simple equal sign. Consider the following examples - in each example we are setting the variables on the lefthand side to be equal whatever is on the right. If there is some sort of math or concatenation that needs to be done on the right hand side, it is done before the value is assigned.

var yourNum = 5; // assigns yourNum to hold the value of 5
yourNum = 5 + 10; // adds 5 + 10 then assigns the value of 15 to yourNum
yourNum = "your " + "number; // concatenates the two strings then assigns the value "your number" to yourNum

If you were to ask JavaScript for the value of yourNum after each consecutive line, the first time it would tell you 5, the next 15 and the last "your number".

Shortcut Assignment Operators

There are times when you need to take the value of a certain variable and manipulate it in some way, then save the new value back into the original variable. The idea is like having a number of marbles in a box (2), opening the lid, adding 5 more, then closing the box. If then you ask how many marbles are in the box, the answer will be 7. Following is a number of examples that exhibit the normal way of doing this:

var counter = 2;
counter = counter+5; // counter(2) + 5 = 7, counter is now 7
counter = counter-4; // counter(7) - 4 = 3, counter is now 3
counter = counter*6; // counter(3) * 6 = 18, counter is now 18
counter = counter/3; // counter(18) / 3 = 6, counter is now 6
counter = counter%5; // counter(6) % 5, counter is now 1

You should notice, each line takes the value of counter from the line above it and uses that in it's math operations to calculate the new value. There is a more succinct way of doing the same operations. The code that allows us to do these operations more succinctly are known collectively as "shortcut assignment operators." The examples below do exactly what was done above, only using the shortcut assignment operators.

var myNum = 2;
myNum += 5; // myNum(2) + 5 = 7, myNum is now 7
myNum -= 4; // myNum is now 3
myNum *= 6; // myNum is now 18
myNum /= 3; // myNum is now 6
myNum %= 5; // myNum is now 1

Autoincrement/Autodecrement offers an even shorter way to add or subtract 1 from a numeric variable. Autoincrement adds 1 to whatever number is currently stored in your variable. Autodecrement subtracts 1 from whatever number is currently stored in your variable. For instance:

var partyPeople = 0;
partyPeople++; // partyPeople(0) + 1 = 1, partyPeople is now 1
partyPeople++; // partyPeople(1) + 1 = 2, partyPeople is now 2
partyPeople--; // partyPeople(2) - 1 = 1, partyPeople is now 1

Comparison Operators

Comparison Operators give us a way of comparing two values to each other. We can see if the values are equal, not equal, or if one is greater than the other. Notice the syntactic difference between the Comparison Equal Operator ( == ) and the Assignment Operator ( = ) - they do completely different things, so make sure you're writing the one you want.

symbol name meaning
== Equal To Checks to see if two values are equal
!= Not Equal To Checks to see if two values are not ( ! ) equal
=== Identical To Checks to see if two values are identical (in both value and data type)
!== Not Identical To Checks to see if two values are not ( ! ) identical (in both value and data type)
> Greater Than Checks to see if the value on the left is greater than the value on the right
>= Greater Than or Equal To Checks to see if the value on the left is greater than or equal to the value on the right
< Less Than Checks to see if the value on the left is less than the value on the right
<= Less Than or Equal To Checks to see if the value on the left is less than or equal to the value on the right

The statements will evaluate to true if the statement is true, and false if it is not. Meaning, 5 == 6 is a false statement, but 5 == 5 is true.

Here are a few examples for each comparison operator:

5 == 5 // true
5 == 6 // false
5 == "5" // true

5 != 5 // false
5 != 6 // true
5 != "5" // false

5 === 5 // true
5 === "5" // false
"5" === "5" // true

5 !== 5 // false
5 !== "5" // true
"5" !== "5" // false

5 < 5 // false
5 < 6 // true
5 < "5" // false

5 <= 5 // true
5 <= 6 // true
5 <= "5" // true

5 > 5 // false
5 > 6 // false
5 > "5" // false

5 >= 5 // true
5 >= 6 // false
5 >= "5" // true

Comparing Numbers and Strings

Numbers are evaluated as you would expect. 5 is less that 6, so 5<6 is a true statement. Negative numbers are less than positive numbers, 5.01 is greater than 5, etc. However, string evaluations are a different matter. JavaScript uses a character's Ascii code equivalent to evaluate a string. So the statements "dog" == "Dog" and "dog" < "Dog" are false, but "dog" > "Dog" is true. Check out http://www.asciitable.com/ to see the Ascii values. A capital "D" is the decimal value 68 whereas a lowercase "d" has a value of 100. Since "D" has a lower value than "d", "d" is greater than "D". All that to say, you won't normally want to compare two strings to see which is greater, but if you do, that's how it works. Additionally, you should now know why "dog" is not equal to "Dog" - JavaScript is case sensitive.

Comparing Variables

You can also compare variables with Comparison Operators. It works exactly as it does with numbers or strings, except you use the variable name. For instance, if we set up these variables:

var marla = "female";
var bob = "male";
var tyler = "male";

Then when we evaluate the following you would get:

marla == "female"; // true because marla contains the string "female"
bob == marla; // false
bob == tyler; // true
bob === tyler; // true
marla != tyler; // true

Variables can also hold numeric and boolean values - comparisons would work the same way with those data types as well. You are comparing the value or contents of the variable, not the name of the variable itself. In the case of an identical (===) comparison, you are comparing both the value and data type of the information inside the variable.

And, Or, Not, Ternary

If you want to compare two or more sets of values, you must use && (And) or || (Or). For instance: 4<5 && 3>4 would evaluate to false because we're asking if 4<5 is true and if 3>4 is true. Since the second is false, it doesn't matter that the first is true - && specifies that both statements must be true statements. In a similar way, || or checks to see if one or the other is true. For instance: 4<5 || 3>4 would evaluate to true. If 4<5 or if 3>4, since 4 is less than 5, the whole statement evaluates as true.

The ! (not) operator is handy if you want to check if something is false. So if we had a variable containing "false" and we wanted to see if it was indeed false, we could say !var which would ask if the var was not true (ask if it was false).

The Ternary operator is an easy way to do a quick check, then return one of two values according to that check. So we could see if 4<5 and if it is we could return "raymond is older" otherwise we return "tyler is older." This would look like:

var older = (4<5) ? "raymond is older" : "tyler is older";

Equal vs Identical

Equal (==) vs Identical (===) is just the extent to which two values are alike. "5" and 5 are alike, or equal, because they are the same value. However, they are not identical because "5" is of the String data type and 5 is of the Number data type. Be sure to think about which you need to check for.

Null and undefined will evaluate as being equal, but not identical. This is sometimes handy to know when comparing values.

Conversions

Sometimes we need to convert a value from one data type to another. For instance, we might have a string containing "10" that I want to add 5 to. In JavaScript, as we discussed, the + sign handles both mathematical addition and concatenation depending on whether there are strings involved or not. If a string is involved, the + means concatenation So, by default, "10" + 5 will equal the string "105", which is not what we wanted. In order to get what we want, we must convert "10" to a number before we attempt to do any addition. We can do this several ways. One way is to work with the parseInt() function that is built into JavaScript. If we wanted to use parseInt, it would look like this: parseInt("10") + 5. Our equation would now convert "10" to the number 10 then add 5, making the resulting value the number 15. If parseInt is called and the string inside the quotations does not start with a number, it will return NaN, meaning "Not a Number".

A very helpful little function when dealing with number conversions is the function isNaN(). isNaN(var) will check to see if a variable is not a number. If it is not a number, it will return true, if it is a number it will return false.

ParseInt does a pretty good job, but it doesn't do a good job on floating point numbers (numbers with decimal places like 10.21 or 3.14). That's where parseFloat comes in. It works exactly the same way as parseInt, except it keeps any decimal values in tact. Here are some examples:

parseInt("45 boxes"); // evaluates to 45
parseInt("19 forty 8"); // evaluates to 19
parseInt("3.14 is pi"); // evaluates to 3
parseInt("I am 67 years old"); // evaluates to NaN

parseFloat("3.14 is pi"); // evaluates to 3.14
parseFloat("pi is 3.14"); // evaluates to NaN

Eval

Eval will convert a string to JavaScript code and run it. For instance: eval("4*5") would return 20 because 4*5 in normal code evaluates to 20. Eval will return undefined if it cannot execute properly. There are very few cases where it is necessary to use eval, but it is available should the need arise.

Control Structures

Conditionals

An "If" statement is a statement that checks to see whether a statement is true, and executes certain code if it is. The syntax for an if statement is:

if( condition )
{
// do this code if the condition is true
}

if( 5<9 )
{
var youngest = "Brian"; // if 5<9 we'll set youngest equal to "Brian"
}

As we mentioned before, and as you should notice here, you do not use semi-colons on the end of multi-line statements, only inside multiline statements. So any statement inside the squiggly brackets will end in a semi-colon, but if you were to write if(5<9); JavaScript would choke on that code.

In the above example, youngest will be set to equal "Brian" because the condition 5<6 will evaluate to true.

If Else is similar in some respects to the Ternary Operator in that we can do one set of code if our statement evaluates to true, and another if it evaluates to false. It uses the same basic syntax as an if statement, but adds an "else" section on to it.

if( condition )
{
// do this code if the condition is true
}
else
{
// do this code if the condition is not true
}

if( 11<9 )
{
var youngest = "Scott"; // if 11 is less than 9, youngest = "Scott"
}
else
{
var youngest = "Erik"; // if 11 isn't less than 9, youngest = "Erik"
}

This time our condition evaluates to false, meaning that instead of doing the code in the first set of squiggly brackets, we skip down to the else and do the code in the second set. You can read this example as "If 11 is less than 9, set the variable youngest to equal the string Scott, else (or otherwise) set the variable youngest to equal the string Erik. Since 11 is not less than 9, youngest will be set to our string Erik."

If, Else If, Else provides us a way to check more than one condition evaluating to true or false. Here is the syntax and an example:

if( first condition )
{
// do only this code if the first condition is true
}
else if ( second condition )
{
// do only this code if the second condition is true
}
else
{
// do this code only if all conditions are false
}

if( 11<9 )
{
var youngest = "Scott"; // if 11 is less than 9
}
else if ( 9<5 )
{
var youngest = "Erik"; // if 9 is less than 5
}
else
{
var youngest = "Brian"; // since both 11<9 and 9<5 are false
}

We begin with the first conditional. If the first condition is true, we do the first set of code, if not we move down to the second condition. If the second condition is true, we do the second set of code, otherwise we move on. If no condition has evaluated to true, the else code will run. You may have as many else if statements as you want, however a more robust way of typing such a statement might be with a switch statement.

When you're using if statements and other control structures, remember that you can use the || and the && operators to check more than one thing at once. For instance:
if ( 5<4 && 6<5 ) ...

A Switch statement is a way to evaluate one variable for a set of different options. Here's the syntax for a switch statement followed by an example:

switch(var)
{
case 1:
// case 1 code
break;
case 2:
// case 2 code
break;
default:
// default code
}

var color = "green";
switch(color) // we're passing in our color variable
{
case "blue":
// case 1 code
break;
case "red":
// case 2 code
break;
default:
// default code
}

First we pass in color which is equal to "green". Then we check the first case: is color ("green") == "blue"? If it is, we'll do any code between case "blue": and the following break;, but if it's not, we go on and look at the next case. We do the same comparison with color ("green") == "red". "green" isn't equal to "red" so we move on. Our default case is just that, the default if none of our cases match (much like else works).

Be sure to put a break; after any code you want to run in a particular case. Leaving off the break; will allow any other of the following cases to match - such as the default case.

A Try Catch statement will try to execute a line of code and if that execution fails, whether because of spelling errors or whatever, it will catch that error in a variable (normally named error as it is below) and will run a different line of code.

try
{
//try to run some code
}
catch ( error )
{
//if the code above generates an error, do this code
}

Fox Example:

try
{
alrt("hello"); // alrt should be spelled alert
}
catch ( error )
{
alert("World!");
}

In the example above, the second line of code 'alert("World"); would run because alrt("hello"); is not the correct syntax. The error returned by our code through the variable error contains information about the particular error JavaScript encountered. However, getting that information is different in Internet Explorer and Firefox. Because of those problems, I'm not going to get into it now. What you need to know at this point is that you can try a line of code, and if that line generates an error, you can execute a backup plan.

Loops

Sometimes you need to repeat a certain set of actions or code a number of times. Fortunately JavaScript provides us the ability to loop (like looping a song in an audio player) through code as many times as we need to.

Loops are controlled by conditional statements. One way is to use a counter - this is sometimes referred to as an increment parameter.

The other way to control a loop is by simply waiting until a value is set to a certain value, typically false.

Break provides a way for us to stop executing a loop prematurely. If a loop hits a break; it will immediately stop looping and jump to the next line of code below the loop.

Continue provides a way for us to stop the current iteration of a loop, mooing on to the next iteration.

There are a few different structures that facilitate looping in JavaScript. They are While, Do While, For and For In.

The variable i is typically used as a counter in loops. You'll see that's what we use for each of our loops. However, you could just as easily use any other variable name such as counter.

While

var i = 0; // counter
while( i<5 ) // condition
{
// some code
i++; // increment
}

A while loop allows us to loop as long as our condition is true. As soon as our condition is false, our loop quits. If our condition starts out being false, no code inside our loop will be executed. This is how a while loop executes:

  1. Check and see if the condition is true.
  2. If the condition is true, execute the code inside our loop.
  3. Increment our counter (i++).
  4. Go back up to the top of the loop and check the condition is true.
  5. If the condition is true, execute the code inside our loop again.
  6. Etc....
  7. Until our condition is false, in which case we stop looping and continue on with any code below our loop. If our condition is false from the beginning, no code in our loop with execute and the loop will be skipped.

Do While

var i = 0;
do
{
// some code
i++;
} while( i<5 )

A do while loop is just like a while loop with 1 exception - we don't check our condition until the end. This means that even if our condition is false from the start, our code inside the loop will run at least once. This is how a do while loop executes:

  1. Execute the code inside our loop.
  2. Increment our counter (i++).
  3. Check if the condition is true.
  4. If the condition is true, go back to the top and execute the code inside our loop again.
  5. Etc....
  6. Until our condition is false, in which case we stop looping and continue on with any code below our loop.

For

for( var i=0; i<5; i++ )
{
// some code
}

A for loop is much like a while loop, but it is self contained - meaning we don't declare our counting variable outside our loop, nor do we increment our counting variable inside our loop. All counting and conditional checks are handled within the parentheses of our looping structure. This makes for loops that are a little more "tidy." Like a while loop, our condition must be true to execute even once, and will continue to execute as long as our condition stays true.

  1. Declare our increment parameter.
  2. Check the condition.
  3. If the condition is true, execute the code inside our loop.
  4. Increment our counter (i++).
  5. Go back to the top and check to see if the condition is true.
  6. If the condition is true, execute the code inside our loop again.
  7. Etc....
  8. Until our condition is false, in which case we stop looping and continue on with any code below our loop.

For In

var characters = new Array('Chloe', 'Lou', 'Irvin');
for(i in characters)
{
// some code
}

For in is a little different than the other looping structures. For in should only be used to loop through an array. Again we have an increment parameter ( i ), but it's value is determined by the indexes of our array. Meaning, we will start at the first index of our array ( 0 ) and loop all the way through until the last index of our array (in our example, 2 - which is 'Irvin'). So ( i ) will start with the value of 0, move to 1, then finish at 2.

Next Page