JavaScript 101 - Part 1
About the Author
Kevin Yank
Kevin began developing for the Web in 1995 and is a highly respected technical author. He wrote Build your own Database Driven Website using PHP and MySQL, a practical step-by-step guide published by SitePoint, and he's co-author of the SitePoint Tech Times, a bi-weekly newsletter for technically-minded web developers. Kev believes that any good webmaster should have seen at least one episode of MacGyver.
By: Kevin Yank
June 22nd, 2001
This article was originally published by Sausage Software [1], makers of the HotDog Professional Web Editor. Reprinted here by permission.
Since the release of Netscape 2 (so long ago that no one remembers!), browsers have included support for more than static HTML. They also have permitted Web authors to include scripts in their pages. Scripts are basically small programs that can react to events occurring in the browser (e.g. the user clicking a link), or other factors (e.g. the current date and time) by changing the Web page in some way.
In contrast to CGI programs (also known as "CGI Scripts"), and other server-side scripts (PHP, ASP, etc.) that are run by a Web server before a requested page is sent to the user's browser, scripts are downloaded as part of the Web page and are run right inside the user's Web browser. While this raises issues of compatibility between different browsers (i.e. older browser versions don't support some of today's fancier script-based tricks), it allows scripts to react to a richer set of events occurring in the browser without the overhead of having the browser contact the Web server to ask what to do every time an event occurs. Furthermore, scripts don't require any special support from the Web server, so you can use scripts in your Web page even if your Web host doesn't let you install custom CGI scripts on your Web site (most ISP's don't).
And besides, scripts are just a whole lot more fun!
If some of the technical jargon above has you a little scared, don't worry. In this, the first in my three-part JavaScript 101 series of articles, I'll teach you everything you need to know to move from the tags-and-attributes world of HTML into the realm of functions and variables that is JavaScript. All I'll assume is that you have a good understanding of HTML.
Your First Script
Statements
You're probably pretty used to what HTML looks like -- text interspersed with tags like <b> and <a href>... JavaScript, on the other hand, looks quite different. The reason for this is that, while HTML is concerned with text and commands that format and define that text, JavaScript (like just about any programming language) is a series of statements. Each statement tells the browser to do something, and the browser steps through the statements one at a time.
Here's a basic JavaScript statement:
alert("Welcome to my Web Site!");
Before we get into what this does, let's notice a couple of things about JavaScript statements in general. As a general rule, a statement appears on a line by itself, and ends with a semicolon (;). In today's browsers, the semicolon is actually optional in most instances (mainly because it's so easy to forget); however, it's a very good idea to try to remember them because they keep the browser from having to guess where each of your statements ends.
Now let's take our statement above and put it to work...
Adding JavaScript to your HTML
As I said before, JavaScript is downloaded as part of a Web page, and is interpreted by the Web browser. For this to happen, you need to somehow put your JavaScript inside your Web page -- inside your HTML. There's a handful of ways to do this, but let me show you the two most common. Both use the HTML <script> tag. The first way of putting a script inside your HTML document is called inline scripting. You put the script right inside your HTML file, and you let the browsers know that it's JavaScript by enclosing it in a <script> tag:
<script language="JavaScript">
alert("Welcome to my Web Site!");
</script>
Notice the language attribute. There are other scripting languages than JavaScript out there (VBScript, which is only supported by Internet Explorer, for example), and this attribute lets the browser know in advance what language your script is written in. Like the semicolon at the end of the statement, the language attribute is optional, but a good idea. Browsers that don't know the language you specify will just skip over the whole tag, rather than trying to read the script and spitting out a bunch of ugly error messages in the process.
When using inline scripting like this, you should always enclose your scripts in an HTML comment tag, like this:
<script language="JavaScript">
<!--
alert("Welcome to my Web Site!");
//-->
</script>
In HTML, anything between <!-- and --> is ignored by the browser, and is called a comment. Some old browsers that were written before the <script> tag existed will ignore the <script> and </script> tags, but will display everything in between as if it were a part of the text in your Web page -- definitely an ugly result. By putting <!-- at the top of your script and --> at the bottom, those browsers will also ignore the script itself. Script-aware browsers know to ignore the <!-- on the first line of a script, but you have to hide the --> with // at the start of the line. While <!-- --> is an HTML comment, // is a JavaScript comment, and tells the browser to ignore everything to the end of the line, so the --> doesn't get interpreted as part of your JavaScript.
The second way to add JavaScript to your HTML document uses a different form of the <script> tag:
<script language="JavaScript" SRC="myscript.js"></script>
Instead of putting the script inside the HTML file, this time you type it into its own file (which I've called myscript.js for this example). This has several advantages. First, you don't have to worry about hiding your script from older browsers with comment tags. Second, you can re-use a single script in several HTML files by referring to the same JavaScript file from each HTML file (and making a change to the script requires a change in only one file instead of in every file where it is used). Finally, you can include information that will be displayed if the browser doesn't support the scripting language you choose:
<script language="JavaScript" SRC="myscript.js">
Get with the <i>times</i>!</script>
The Completed Example
So what does our simple, one-statement script actually do? It tells the browser to stop reading the HTML page where it encounters the script, display the message "Welcome to my Web Site!" (without the quotes) in a message box, and wait for the user to click "OK" before proceeding to read the rest of the page.
The following example will actually display two message boxes, because it contains two scripts, one included as an inline script, and one appearing in an external .js file. Check out the code and try it for yourself!
Language Basics
Built-In Functions
In the previous example, we used a single JavaScript statement, without really explaining how it worked:
alert("Welcome to my Web Site!");
Somehow, this single line was able to stop the browser in its tracks and force it to display a message box... Is JavaScript really that powerful? Well, yes and no. You've probably figured out that the text appearing in quotes (Welcome to my Web Site) is what gets displayed in the message box, and you can change this to be pretty much any message you want. What about the rest of the statement?
The word alert is actually the name of a JavaScript built-in function. You can think of a built-in function as "something that JavaScript knows how to do without you having to explain it." Displaying a message box that the user has to click "OK" in is a built-in function because JavaScript knows how to do this, and nowhere do you have to tell it where to display the window, what buttons it should contain, not to mention all the other mundane details involved.
So the JavaScript statement above tells the browser to execute the JavaScript built-in function called alert. Such a statement is called a function call, because you are calling a function. If this sounds like a strange way of putting it, don't worry -- programmers like to make things confusing. Just think of a function as an expert that's really good at doing a particular job (in this case, the alert function is an expert at displaying message boxes). As the author of a script, you want to make use of that expert's skill, so you call the expert on the phone to ask it to do something -- a function call.
Parameters
The alert function is so good at its job that the only detail that it needs from you is the message to be displayed. The alert function wouldn't be much use if it only let you display a fixed message that was decided upon by the function, would it? Using such a function would be like hiring a painter for your house that only knew how to paint in one colour (probably fluorescent green, too!). These bits of information that need to be specified when calling a function so that it does what you want it to are called parameters.
To specify the parameters for a function call, you list them, separated by colons, between parentheses following the name of the function:
function(parameter1, parameter2, parameter3);
We'll be seeing more examples of built-in functions throughout this series of articles, so don't worry if the details aren't quite clear to you yet.
Variables
In just about any programming language, there exists the concept of a variable. A variable is a name you assign to an imaginary "box". That box can contain many different things: a piece of text, a number, or even a date and time. The box can only contain one thing at a time, though. And whatever it contains, you can always refer to the contents of the box by the name that you've assigned to it-the variable.
You create a variable using the var command, followed by the name of the new variable. To assign a value to a variable, you just use the = operator. This is best illustrated with an example. I've stuck a comment on each line to explain what's happening (remember, everything after // on a line gets ignored by the browser).
var a; // Creates a variable called a
a = 5; // Assigns the value 5 to the variable a
alert(a); // Displays a message box containing the value of a (5)
a = "Hello!"; // Assigns the value "Hello!" to the variable a
alert(a); // Displays a message box containing "Hello!"
Not convinced? Try the example yourself:
You can also set the initial value of a variable when you create it:
var b = 20; // Creates a variable called b with value of 20
Finally, since you can use a variable pretty much anyplace where a value would normally go, you can assign the value of one variable to another:
var c, d; // Creates two variables: c and d
c = 10; // Assigns the value 10 to the variable c
d = c; // Assigns the value of c (10) to the variable d
c = 20; // Assigns the value 20 to the variable c
alert(c); // Displays a message box containing the value of c (20)
alert(d); // Displays a message box containing the value of d (10)
Once again, here's the complete code for you to try:
Operations
JavaScript, like any good programming language, lets you take simple values (like numbers and strings of text) and perform operations on them (like addition, subtraction, or even comparison). You can then pass these values to functions or store them in variables. Again, let me show you some examples so you know what I mean:
var a, b, c; // Three variables
a = 10; // Assigns value 10 to a
b = 10 + 1; // Assigns value 11 to b
c = b - a; // Assigns value 1 to c
a = b * 3; // Assigns value 33 to a (* is multiplication)
c = a / b; // Assigns value 3 to c (/ is division)
You can perform multiple operations in a single statement, if you want to. Note that numerical operations obey the same rules of precedence as they do on a scientific calculator-multiplication and division first, followed by addition and subtraction. Of course, we can use parentheses to change this if we want:
a = 1 + 2 * 3; // a = 7
b = (1 + 2) * 3; // b = 9
Recall that variables don't have to contain numbers. They can also hold strings of text... and operations can be performed on strings as well:
var name = "Kevin";
alert("Hi " + name + ", how are you today?");
The code above displays the message "Hi Kevin, how are you today?". Notice how the + operator, which is used to add numbers together, can also be used to stick strings of text together. Notice also that we've used the result of the expression "Hi " + name + ", how are you today?" as the parameter to be passed to the alert function.
Control Structures
Wow, these headings just keep getting scarier, don't they? Don't worry, control structures aren't as complicated as they sound.
All the examples we've seen so far have taken the form of a series of statements that were to be executed in order from top to bottom. Control structures let us change that. Let's start with the most basic control structure, an if statement:
if (condition) statement;
This tells the browser to execute the statement only if the condition is true. For example:
if (a == b) alert("a and b are equal");
That double-equals is not a typo. Where a = b assigns the value of b to a (as shown above), a == b tests if a and b are equal. So the above line displays a message box saying "a and b are equal" if the condition a == b is true. Makes sense, right? Here are a few more examples of conditions for you:
if (a > b) alert("a is greater than b");
if (a < b) alert("a is less than b");
if (a >= b) alert("a is greater than or equal to b.");
if (a <= b) alert("a is less than or equal to b.");
if (a != b) alert("a does not equal b");
Instead of a single statement, you can specify a whole series of statements that should be executed if the condition is true. You do this by putting the statements between braces:
if (name == "Kevin") {
alert("Hi, Kevin!");
// ... more statements here ...
}
Just to complicate things further, there's also an if-else control structure:
if (condition) {
// statements to be executed if condition is true
}
else {
// statements to be executed if condition is false
}
In this case, one group of statements or the other will be executed. The condition determines which.
The two control structures we have seen are the most basic, and most commonly used. We'll save explaining the rest until we actually need them.
Writing Your Own Functions
One of the big time-savers in JavaScript is the ability to write your own functions. We've already seen that JavaScript provides a set of built-in functions (we've already played with the alert function quite a bit), which can be passed parameters to do various useful things for us without us having to worry about how those things are done.
By writing your own functions, you can extend this convenience to sections of code that you write yourself. Complicated procedures that you want to do more than once can be written as functions, which you can then call as many times as you need. Let's look at an example:
function welcome(name) {
var greeting = "Welcome to my Web site, " + name + "!");
alert(greeting);
}
welcome("Kevin");
welcome("Amy");
The code above starts by defining a function named welcome. When called, this function expects a single parameter to be passed to it, the value of which will be temporarily assigned to the variable called name. The function then creates a variable named greeting, and uses the name variable (containing the value passed as a parameter) to create the greeting message. Finally, the message is displayed in a message box using the alert built-in function that we know and love.
With the function defined, we call it twice: once passing "Kevin" as the parameter and a second time with "Amy" as the parameter. The final result of this script is two message boxes displayed one after another—the first greeting Kevin, and the second greeting Amy. Astute readers may point out that this whole thing could have done with two simple calls to the alert function. The point is that we could have had a really big and twisty bit of JavaScript in our function, in which case having the code bottled up in a function would have made a lot of sense and saved a lot of typing when we wanted to use it more than once.
A Practical Example
At the beginning of this article, I said that JavaScript was a lot of fun. After wading through the last few pages of introductory material, you may be starting to question that assertion. To try to make up for the dry first impression that the mundane details of JavaScript invariably give, let's finish off with an example that you can actually use.
A common way of sprucing up a table of dull figures is to give the rows of your table alternating background colors. The effect looks like this:
| My Table | |
|---|---|
| Item 1 | Value |
| Item 2 | Value |
| Item 3 | Value |
| Item 4 | Value |
The problem is that if you go back and add or remove a row sometime down the line, you have to shift all the colors below the new or removed entry to keep the colors of the rows lining up. By using JavaScript to handle the row colors, you can avoid this problem entirely!
Before we begin, there's one more built-in function that you need to know. We've already seen alert, which takes a single parameter and displays it in a message box. document.write performs a similar function, but instead of displaying the parameter you pass it in a message box, it slots it into the current HTML document for you. Take the following a simple example:
<html>
<head>
<title> document.write example </title>
</head>
<body>
<script language="JavaScript">
<!--
document.write("<p>This JavaScript stuff is pretty <i>neat</i>.</p>");
//-->
</script>
</body>
</html>
All this results in is an HTML document that says "This JavaScript stuff is pretty neat." Not too impressive at first glance... but wait and see what we can do by using this function with all the other tools we've seen so far!
First, let's pick the two HTML color codes for our table rows and assign them to variables:
var color1 = "#6691BC";
var color2 = "#769DC5";
We'll also need a variable to keep track of what row number we're on. We'll set it to 1 because when we start off we'll be on the first row.
var rownumber = 1;
Now we'll write a function. The job of this function will be to write the <tr> tags of our table for us, slotting the right color in each time (are you starting to see where this is going...?):
function tablerow() {
var currentcolour;
if (rownumber % 2 == 0) {
currentcolor = color1;
} else {
currentcolor = color2;
}
document.write("<TR BGCOLOR=\"" + currrentcolor + "\">");
rownumber = rownumber + 1;
}
There are a couple of new tricks in the code above, but mostly it's stuff we've seen already. Regardless, let's step through it line by line to see what's going on.
The first line just says that we're creating a function for ourselves called tablerow. Since there's nothing between the parentheses, our function won't take any parameters, but the parentheses are required nevertheless.
On the second line, we create a variable called currentcolor. It's important to realise that variables created inside of functions only exist for as long as that function is executing. So each time this function is called, a variable called currentcolor will be created, and then will disappear when the function finishes doing its thing. Contrast this with the variables color1 and color2 that we created above. Since these variables weren't created inside any functions, they'll exist for as long as the document is loaded in the browser, and can be accessed by any piece of JavaScript code (including our function, as we're about to see).
The third line is the start of an if-else control structure. You'll remember that this structure allows us to execute one set of statements or another depending on whether some condition is true or not. The condition in this case is (rownumber % 2 == 0). The only thing that should be scary about this is the percent sign. This is actually just another mathematical operator like + or -, but is not as common. Known as the modulus operator, it calculates the remainder obtained when dividing one number by another. In this case, our condition is checking if the remainder of dividing rownumber by 2 equals 0. In simpler terms, we're checking if rownumber is even!
Thus, the fourth line only gets executed if rownumber is even. If it is, we set the value of currentcolor to the value of color1, "#6691BC". If it isn't, the sixth line gets executed instead, and currentcolor is assigned the value of color2, "#769DC5".
With the if-else behind us, the eighth line gets executed regardless of the outcome of the condition. This is where our document.write function comes into play. What we want to be written into our document is the following:
<tr bgcolor="_______">
where the underscore needs to alternate between our two color values. So far, our function has picked one of the two color values depending on whether we're on an even or odd row of the table. All that's left is to write the line with the correct color in it. For convenience, I'm repeating the line here:
document.write("<tr bgcolor=\"" + currrentcolor + "\">");
Thinking back to how alert works, this looks just about right. The value of currentcolor is plugged into the HTML code and is written to the document by document.write. The only point of confusion is the two occurrences of \" that I've highlighted above. Since the double quotes are used by JavaScript to mark the beginning and end of a string of text, using them in the text itself would confuse JavaScript. It would think that the string of text was ending, when in fact you just wanted to put double quotes in the string. To overcome this, JavaScript lets you put a backslash (\) before any character that would usually have a special meaning, to indicate that the special meaning should be disregarded and that the character should appear in the string of text as-is. With this in mind, this line of code does exactly what we need!
As its last order of business, our function adds one to the rownumber variable, by setting its new value to its old value plus one. This ensures that the next time the function is called, the other color will be used for the row background.
Now whenever we want to start a new row in our HTML document and have JavaScript decide on the background color, we replace the <tr> tag with a call to our function:
Before:
<tr bgcolor="#??????">
After:
<script language="JavaScript">
<!--
tablerow();
//-->
</script>
Pretty neat, huh? Here's the complete example for you to refer to:
Summary
In this article, we took a whirlwind tour of the basic elements that make up the JavaScript language: statements, variables, operations, control structures, and functions (both built-in and not). While not every detail of each of these was presented, we covered just enough to make you dangerous!
To solidify our grasp of these basic concepts, we developed a way of making an alternating table row colour effect without having to keep track of which colour belongs on which row. All of the concepts covered earlier in the article were applied here.
Next Time
In Part 2 [10], we'll look at some more useful examples and further refine our knowledge of JavaScript, by learning about things like event handlers, arrays, and objects.
[1] http://www.sausagetools.com
[2] /examples/js101/seefirst.html
[3] /examples/js101/codefirst.html
[4] /examples/js101/seevars.html
[5] /examples/js101/codevars.html
[6] /examples/js101/seevars2.html
[7] /examples/js101/codevars2.html
[8] /examples/js101/seetablecolour.html
[9] /examples/js101/codetablecolour.html
[10] /article.php/454