JavaScript Tutorial – Lesson 4

Welcome to Lesson 4! There are two main parts to JavaScript: the syntax of the language and its library of objects. In Lesson 2, which was an introduction to the syntax, we looked into variables, statements, and if-then clauses, which are parts of all programming languages. Now it’s time to learn the rest of the JavaScript syntax.

There are only three major aspects of JavaScript syntax that we have yet to cover: loops, arrays, and functions.

Introduction to Loops

Sometimes you want to do the same thing more than once. Let’s say, for example, that you wanted to get a password from somebody and you wanted to keep asking until they gave you the right password. If you just wanted to give them two tries, you could do something like this:

Unfortunately, this sort of thing won’t work if you just want to keep asking until they get it right. And it’s pretty ugly already – imagine if you wanted to ask four times instead of just two. You’d have four levels of if-then clauses, which is never a good thing.

The best way to do similar things more than once is to use a loop. In this case, you can use a loop to keep asking for passwords until the person gives up. Here’s an example of a while loop in action. The password is: pass the wrench.

Looping Password

That’s the woyd!

Let’s go through this example line by line. View Source if you want to see the whole script.

After the typical JavaScript preamble, we start with a couple of variable declarations:

var password="pass the wrench";
var answer;

Here we define the password as a string, and we declare a variable called answer. You’ll see why we had to declare answer in a second. The next few lines are the important ones:

So the above lines say, “While the answer isn’t equal to the password, execute the prompt command.” The loop will keep executing the statements inside the curly brackets until the test is false. In this case, the test will only be false when the words the user enters are the same as the password (that is, “pass the wrench”).

We had to declare answer because performing a test like (answer != password) on an undeclared variable will give an error in some browsers. Because answer is given a value by the prompt method inside the while loop, it will have no value the first time we hit the loop. Defining it early gives it an initial value of "".

Although looping indefinitely is often useful, loops are more commonly used to execute a set of statements a specific number of times. Here’s another example of a while loop that shows how to do this.

More about While Loops

You should have seen as many x’s as you asked for. Let’s go over this:

First, we ask for the number of x’s:

var width = prompt("How many x's would you like?
(1-10 is good)","5");

Next, we declare a few variables:

var a_line="";
var loop = 0;

And now for the important part:

while (loop < width)
{
a_line = a_line + "x";
loop=loop+1;
}

This says, “while the variable loop is less than the requested width of the row of x’s, add another x to the line and then add one to the value of loop.” This loop will keep adding an x to the line and adding one to the value of loop until loop is no longer less than the requested width. Here’s a timeline of what happens when a person chooses two x’s at the prompt:

Time 1

a_line = “” (because we initialized it to be “”)

loop=0 (because we initialized it to be 0)

width=2 (because that’s what the user asked for)

0 is less than 2 so

a_line = a_line + “x”, so now a_line = “x”

loop=loop+1, so now loop = 1

Back into the loop: Time 2

loop=1

width=2

a_line = “x”

1 is less than 2 so

a_line = a_line + “x”, so now a_line = “xx”

loop=loop+1, so now loop = 2

Back into the loop: Time 3

loop=2

width=2

a_line = “xx”

2 is NOT less than 2 so

fall out of the loop and do what follows

And what follows is:

alert(a_line);

Throw up an alert box announcing a_line.

This sort of loop is so common that programmers have developed a few shortcuts. Using the shortcuts, the while loop could have been written like this:

The first line, a_line += "x" , says “add x to myself.” This shortcut works with numbers, too. If you have a_number = 5 , and you write, a_number+=3 , it’s just like writing a_number=a_number+3. Programmers are lazy; they’re always coming up with shortcuts like this.

The next line, loop++ , means “add one to myself.” So, loop++ is the same as loop=loop+1 , which could also be written loop+=1. Each of these is equally good. Which one you use depends on how lazy you are.

Just like there’s more than one way to add 1 to a number, there’s more than one way to write a loop. while loops aren’t the only kind of loops out there. Another popular one is the for loop.

So, the above for loop sets loop = 0 and says that you should keep adding 1 to loop as long as loop < width. It’s just like the previous while loop with a few less lines. Both say “add an x to a_line</font> <code>width times.”

One more thing about loops before we do an exercise using them: Loops can be nested. Here’s an example of nested loops. Turn off your pop-up blocker to see this example in action.

After asking for height and width, opening a new window, and writing a header to it, we go into a for loop. The first for loop sets a_line = "". Try doing the example without this line and see what happens. After initializing a_line , the script goes into another for loop to build a line of x’s as wide as required and prints it out to the new window. This happens height times.

OK, here’s your assignment: Take a look at this loop exercise and try doing it on your own before viewing source to see how it works. Turn off your pop-up blocker to see this example in action.

Loop Exercise

This script asks for a few words and then prints them out in reverse order. Try writing the script yourself. When you’re done, View Source on this to see how I did it. After you’ve figured it all out, it’s time to learn about.

Arrays

We’ve seen that variables can hold numbers, strings, and references to objects. There’s one more kind of information that JavaScript understands:arrays.

Arrays are lists. You might have a list of URLs that you want to visit, a list of names that you want to remember, or a list of colors in which you’d like text displayed. All these lists can be stored in arrays.

Here’s how to create an array of colors:

var colors = new Array("red","blue","green");

Now that you have an array, what can you do with it? The good thing about arrays is that elements of an array can be accessed by number. The first element is number 0 and can be accessed like this:

var the_element = colors[0];

After you execute this line of JavaScript, the variable the_element will hold the string “red.” As you can see, you access the first element of an array by writing the name of the array and putting the element’s number in square brackets. The second element of an array is number 1.

Once you’ve created an array, you can add to and change its values. If you decided to change the first element of the colors array to purple instead of red, you could write this:

colors[0] = "purple";

Arrays are often used in tandem with loops.

Arrays and Loops

Arrays are great, because you can loop through each element of the array and do something with it. Here’s an example of arrays and loops that presents a URL slide show. Take a look at the slide show and then come back here. Turn off your pop-up blocker to see this example in action.

This example may need to be updated.

The first thing we do to make the slide show work is declare some variables:

Next, we loop through the array, opening each URL and waiting for the user to click on the alert OK button:

for (var loop = 0; loop <url_names.length; loop++)
{
// make the name of a url, for example http://www.hits.org/
a_url = "http://www." + url_names[loop] + "/";
// open a window
var new_window=open(a_url,"new_window","width=300,height=300");
// wait for the click
alert("hit ok for the next site");
}

There are a few interesting things in this loop. First, note that the loop goes from 0 to something called url_names.length. Putting .length after the name of an array tells you how many elements are in the array. Remember, however, that this number is not the same as the index number of the last element in an array. If an array has three elements, its length is 3 but its last element is array[2]. This is because the first element of an array is array[0]. If you’re getting errors like “object not found” and there’s an array in your code, you may well have mixed up the index number of the array element with the overall number of elements in the array.

You might have noticed that putting a .length at the end of an array looks a lot like finding a property of an object. Well, that’s because arrays actually are objects and length is one of the array’s properties.

The other sign that arrays are objects is that you create a new array using the new command. In the above example, url_names = new Array("blah","blah"...) actually says, “make a new array and make url_names a reference to it.” In general, that’s how you create a new instance of an object. We won’t be going much deeper into objects for this set of lessons, so, for now, just keep in mind that if you see the word “new” being used in this way, you’re looking at an object being created.

The first line in the loop just creates a variable that holds a string.

a_url = "http://www." + url_names[loop] + "/";

The first time into the loop, the value of the variable loop is 0. The first element in the url_names array is the string "hits.org". So, during the first time in the loop, the variable a_url will equal the string "http://www.hits.org/".

The next line of the loop opens a window with that URL.

var new_window=open(a_url,"new_window","width=300,height=300");

Because each time we open the window we give it the same name, we won’t get multiple windows. If we had left out the name "new_window" we would have opened a different window each time we went through the loop.

The third line of the loop simply throws up an alert box and waits for the user to hit the OK button.

There are more uses for arrays than just holding strings. In fact, it turns out that arrays run throughout the JavaScript Document Object Model.

Arrays in the Document Object Model

This example is going to use image swapping to show how arrays are woven into the DOM. Try the example, view source, and read on.

The first line gets a number and the second line does the change. In the past, we changed images using something like this:

document.image_name.src = 'some_image.gif';

In order to do this, each image has to be named. If you don’t know the name of an image that you want to swap, but you know its order on the HTML page, you can refer to the image by its DOM number. The first image in an HTML document is document.images[0], the second is document.images[1], and so on. If you want to know how many images are in a document, you can find out by checking the length of the images array:document.images.length. For instance, if you wanted to change all the images on your page to a spacer GIF, you could do this:

OK, there’s one more part of JavaScript syntax you need to know before you can consider yourself a full-fledged programmer: functions. Once we cover functions, we’ll do a few exercises, and then I’ll give you your homework for this lesson.

On to functions.

Functions

Functions are the last bit of basic programming you need to know before you can understand and perform your own serious JavaScripting. All programming languages have functions. Functions, or subroutines, as they’re sometimes called, are bits of JavaScript that you can call over and over without having to rewrite them every time.

Let’s say you were trying to teach yourself to speed read and you wanted to sprinkle a long text with links which, when hit, would tell you the current time.

The details of how this little JavaScript works aren’t really important right now; I’ll go over them soon. The important thing to notice is that it’s fairly long. If you wanted to have 10 of these time links, you’d have to cut and paste this script each time, making your HTML pretty long and ugly. In addition, if you wanted to change the script, you’d have to change it in 10 different places.

Instead of having 10 copies of it on your page, you could write a function to execute the JavaScript. That way you’d have the function in one place, making it easier to edit and easier to read.

Here’s how you’d write a timer function.

Functions with No Parameters

This HTML page contains a function called announceTime(). To call announceTime from a link you’d do this:

OK, let’s go over this function line by line. First, all functions come in this format:

function functionName(parameter list)
{
statements ...
}

Functions’ naming rules are the same as those for variables. The first character has to be a letter or an underscore. The rest of the characters can be numbers or dashes. Also, you must make sure you don’t name a function the same as a variable. If you do, you’ll get really strange, hard to debug, results. I use internal capitalization for my function names to make sure I don’t accidentally name a function and a variable the same thing.

After the function name comes a list of parameters. This function has no parameters, so I’ll hold off describing parameters until the next example.

After the parameters comes the body of the function. This is the set of statements you want to run when the function is called. I’m going to use this timer for the next few examples, so let me describe how it works.

The first line …

var the_date = new Date();

… gets a new date object. Just like you have to get a new array object before you can do anything with it, you need to get a new date object before you can find out what time it is. When you get a new date object, it is automatically preset to the current date and time. In order to get the information out of the object, you have to use the object’s methods:

You might be asking yourself, how am I supposed to know what methods a date object knows? How do I even know there’s such a thing as a date object? Well, these are reasons you need to have access to a JavaScript library. I’ll do my best to explain as many of the built-in JavaScript objects as I can, but there’s no way I can go through all of them.

The rest of the function is pretty clear. It takes the numbers returned by the method calls, turns them into a string, and calls the alert method to put up a dialog box with the string. Note that you can call methods and functions from within functions. We’ll see a lot more of this.

Now, if you’ve played with the time link enough, you might have noticed something isn’t quite right. Every once in a while you get something like this:"The time is now:12:14:4". What’s the deal here?

Well, it turns out that the getSeconds() method returns a number. If it’s 12:14:04, getSeconds() will return the value 4. Then when we do the string concatenation, the_minute + ":" + the_second, we get 14:4 instead of what we want. There’s an easy way out of this, and that’s to make a new function that fixes the minutes and seconds if they need fixing. This new function will demonstrate parameters and return values, two crucial parts of functions, so it deserves a page of its own.

On to parameters and return values.

Parameters and Return Values

Although functions with no parameters are pretty handy for cutting down on the amount of typing you have to do and help make your HTML look better, functions that take parameters are far more useful.

In the last example, we had a problem when the getMinutes and getSeconds methods of the Date object returned numbers less than 10. We wanted them to come out as 04 instead of just 4.

This would work fine. Notice, however, that we’re basically writing the same code twice:If something is less than 10, stick a “0” in front of it. When you start to notice that you’re writing almost the same exact code a bunch of times in your JavaScript, you should start thinking about writing a function to do it. In this case, I wrote a function called fixNumber:

fixNumber takes one parameter, called the_number. A parameter is just a variable that gets set when the function is called. In this case, if we call the function like this:

var fixed_variable = fixNumber(4);

The parameter the_number gets set to 4 in the function. The body of fixNumber should make sense to you by now. It says, “if the variable the_number is less than 10, add a to the front of it.” The only new thing is the return command:return the_number. The return command is used when you say something like this:

var some_variable = someFunction();

The variable some_variable gets set to the value returned by the someFunction() function. In fixNumber, I wrote:return the_number. This exits the function and returns the value of the_number to whatever variable is waiting to be set. So, if I write …

var fixed_variable = fixNumber(4);

… the_number will be initially set to 4 by the function call. Then, because 4 is less than 10, the_number will be changed to “04“. Then the_number is returned, and the variable fixed_variable will be set to “04.”

To include fixNumber in original function, announceTime(), I’ve made the following additions:

Let’s say it’s 12:04:05 when the time link is clicked on. We get the date using new Date(), get the hour using getHours(), which doesn’t need fixing, get the minute as we did before, which in this case will be the number 4, and then call fixNumber on the_minute:

var fixed_minute = fixNumber(the_minute);

When fixNumber() is called, the parameter the_number gets set to the value of the_minute. In this example, since the_minute is 4, the_number will be set to 4. Once the parameter is set, we go into the body of the function. Since 4 is less than 10, the_number is changed to be “04“. Then the_number is returned, using the return command. Once “04” is returned by fixNumber, the variable fixed_minute will equal “04”.

function fixNumber(the_number)fixNumber() is called with the value of the_minute, which is 4, now the_number = 4

if (the_number < 10) {the_number = "0" + the_number;} Since 4 is less than 10, the_number now equals “04”

return the_numberThe function exits and returns “04” ===Function fixTime() has exited, so we’re back in announceTime()===

The function returns with “04” So fixed_minute now equals “04”

This example used a function which only had one parameter. You can actually have as many parameters as you’d like. For example, here’s a function in the Functions with More Than 1 Parameter section that takes two arrays and returns a list of elements that the arrays have in common.

This is a function with three parameters:a string representing the name of the intersection, the first array, and the second array. It’s similarly easy to find the names of Webmonkeys who like cats:cat-loving monkeys.

Like so:

<a href="#" onClick="arrayIntersect('monkeys who love cats',monkeys,kittyphile); return false;">Click to see the cat-loving monkeys</a>

See if you can figure out for yourself what the for loops are doing in this example. The important thing to note here is the first line of the function:

function arrayIntersect(intersect_name, array_1, array_2)

This defines a function called arrayIntersect with three parameters. Just like in the earlier example, each parameter is like a variable that gets set when the function is called. So, when this function is called like this:

arrayIntersect('dancing monkeys',monkeys,discophile);

The following assignments are made:

intersect_name = ‘dancing monkeys’

array_1 = monkeys

array_2 = discophile

The only thing you have to be careful of is that you call your functions with the right number of parameters. If we had accidentally called arrayIntersect like this:

arrayIntersect(monkeys,discophile);

We would have gotten all kinds of errors. Try it and see what happens.

Functions are the basic building blocks of any decent JavaScript, so it’s very important that you understand how they work. Here’s an exercise to test your knowledge of functions. After you’ve done the exercise, we’ll do one more exercise that combines everything we’ve learned in this lesson, and then go on to do some more work on our personal browsers. Here’s a snazzy way to give people a chance to go to another URL without having to drag their mouses all the way to the Location window:Where are you heading?

The neat thing about this script is that people can type either http://some.address.com or just some.address.com. If they do the latter, JavaScript will figure it out and append http:// to the front of what they type. Give it a try. Type www.hits.org and you’ll see that the script appends the http:// on the front.

Your assignment, of course, is to do this. You’ll need one tip though. To check the first few letters of the typed URL, you need to do this:

var the_first_seven = the_url_they_typed.substring(0,7);

After you do this, the_first_seven will hold the first seven characters of the string typed into the prompt.

Try doing this exercise. If you give up, View Source for the solution. Try it first, though! Then go on to the final exercise for this lesson.

Lesson 4 Review

Today we finished with the syntax of JavaScript. We’ve covered, in broad strokes, most of what is covered in an introductory computer science course. If you understood it all, you should go grab a celebratory banana. Here’s what you should know by now:

while loops

How to make a while loop loop both indefinitely and a specific number of times

for loops

How for loops work

Arrays

What arrays are and how to initialize and set them

Arrays and loops

How to use loops to go through arrays (using the array.length property)

Arrays in the DOM

How to use arrays to affect images on your pages (the DOM is packed with arrays)

Functions

You should know what a function is and how to write and call one

Parameters and return values

Functions get interesting when you can change their behavior based on parameters and use their results in other parts of your JavaScript

You can now call yourself a junior computer programmer. In

Lesson 5, we’re going to leave the dry-ish world of JavaScript syntax and return to the JavaScript Document Object Model. Here we will learn about how you can use forms to interact with users in powerful and interesting ways.

Here’s The Thing With Ad Blockers

We get it: Ads aren’t what you’re here for. But ads help us keep the lights on. So, add us to your ad blocker’s whitelist or pay $1 per week for an ad-free version of WIRED. Either way, you are supporting our journalism. We’d really appreciate it.