Advanced JavaScript Tutorial – Lesson 1

Hello, and welcome to the Advanced JavaScript Tutorial, where I finish off what I started in the basic JavaScript Tutorial. In the second installment – This Time We Mean It – I’ll be covering the finer points of JavaScript that I passed over back in Part I. I’ll also introduce you to some of the fancier aspects of JavaScript and the tips and lowdown that will allow you to build real multimedia applications.


As we head into the JavaScript nitty-gritty, I’m going to assume that you’ve covered the following:

  • Assigning values to variables
  • If-then statements
  • For and while loops
  • Writing your own functions
  • Opening and manipulating windows
  • Reading and writing to HTML forms
  • Using arrays
  • Conducting image swaps


Any of these sound unfamiliar? You may want to take a peek at the first five JavaScript lessons before you get into Part II.

Contents

  1. The Five-Day Lesson Plan
  2. An If-Then-Else Shortcut
  3. What Is This Thing Called Var?
  4. The Way of Var
  5. Conclusion

The Five-Day Lesson Plan

Back in Part I, we covered the heart of JavaScript:most of the important syntax and many of the most commonly used objects. It is now time to refine your JavaScript knowledge and become a true JavaScript master. And here’s what you’ll find along the path to enlightenment.

Day 1
Introductions and the tying up of a few loose ends. A pretty light start, with just a few tips and teasers to get you into the mood. Highlights include a new kind of if-then-else statement and the true meaning of var.
Day 2
Fancy string handling, saving information about your visitors after they’ve left your site, and a new type of array.
Day 3
Setting timelines on your pages so that different events occur at different times. Bonus:making your JavaScript work on as many browsers as possible.
Day 4
Preloading images, image maps and JavaScript. Creating your own objects and using loops to easily get at hard-to-find objects.
Day 5
Tools for developing and testing JavaScript, debugging techniques, and tips for making your JavaScript code run quickly.

By the end of these five lessons, you should have a grip on the full range of JavaScript possibilities. With this knowledge firmly in your grasp, a vast array of Internet applications will be yours for the writing.

Let’s get started with a lovely if-then-else shortcut.

An If-Then-Else Shortcut

One of the most commonly used statements in JavaScript is the good old if-then-else. Take the Webmonkey reward schedule for instance:

 if (monkey_behavior == "good")

 {

 	var toy = "videogames";

 } else {

 	var toy = "rocks";



 }

In plain English, this means, “If the monkey’s been good, he gets to play videogames. If not, he gets only rocks.” For reasons of legibility, it is a perfectly good way to do this. For those who don’t like to squander keystrokes, however, there is a shortcut (albeit, a less legible one). It’s called the “conditional operator,” and it goes a little something like this:

 var toy = (monkey_behavior=="good") ? "videogames" :"rocks";



This expression does the same thing as the if-then-else statement above it. See what I mean about legibility? The conditional operator has three parts:a conditional test, a value to return if that test is true, and a value to return if that test is false. So, in the above example, the conditional test is (monkey_behavior=="good"). If that test is true, it returns the value after the question mark. In this case, it’s the string videogames. If the conditional test is false, the value after the colon is returned; in this case, it’s rocks.

This sort of shortcut is most useful inside function calls. For example, you can use it to do something like this:

 var password = "open sesame";

 var answer = prompt("what's the password? ","");

 alert((answer == password) ? "welcome!" :"buzz off");

Click here to see this in action. What you’re seeing is the conditional operator doing its job and returning either welcome or buzz off, depending on the answer you give at the prompt. The value returned by the conditional gets sent to alert, which throws up an alert box with that value.

Without the conditional operator, the code would look like this:

 var password = "open sesame";

 var answer = prompt("what's the password? ","");

 if (answer == password)

 {

 	alert("welcome");

 } else {

 	alert("buzz off");

 }



It’s definitely longer, but some people find it more readable, and understandable, to actually write out the if-then-else statement. The method you choose is simply a matter of personal preference.

OK, last stop on today’s tour of loose ends: the mysterious var.

What Is This Thing Called Var?

Way back in Part I, Day 2, I said that the first time you use a variable, you should declare it with the word “var.” I promised that I’d explain why when I talked about functions. Well, I forgot! So, now is the time.

Just to jiggle your memory, here’s an example of var in use:

 var happiness = "a banana split";

 alert("The monkeys think happiness is " + happiness);

This little blurb declares a variable called happiness, then throws up an alert box that uses that variable.

If you’ve been looking at other people’s JavaScript, you might have noticed that not everyone declares their variables with var, which can cause problems. First, some versions of MSIE will bomb, or at least act strangely, if a variable isn’t declared with var. This is especially true for MSIE on Macs. Second, if you want to write JavaScripts of any significant size, you’re going to have to write your own functions. And once you start writing your own functions, you really need to understand what var is all about.

As described in Part I, Day 4, a function is a block of JavaScript that can be called when necessary. The best functions are self-contained. You know what goes into the function and what comes out of it, and, once you’ve written the function, you don’t have to worry about how it works.

As long as all your functions are self-contained, you never have to worry that writing a new function will accidentally screw up a function you’ve already written. The key to writing self-contained functions is to make sure that your function doesn’t alter variables that aren’t passed directly into them as parameters.

Here’s an example of what can happen if you’re not careful. Let’s say you want to write a program that converts Fahrenheit temperatures into Celsius. Click the Fahrenheit/Celsius converter to see what I mean. If you convert 50 degrees Fahrenheit, you get a message saying, “50 degrees Fahrenheit is 10 degrees Celsius.” You could write a script without vars that would look something like this:

 function fahrenToCelsius(faren)

 {

     temp = (faren - 32) * 5/9;

     return temp;

 }

 function convertTemp()

 {

     temp = prompt("what temperature fahrenheit? ","50");

     celsius = fahrenToCelsius(temp);

     alert(temp + " degrees Fahrenheit is " +

     celsius + " degrees Celsius.");

 }

The workings of these functions should be pretty clear to you. One function named convertTemp() calls another function named fahrenToCelsius() and returns the results. Take a moment to make sure you understand what’s going on. Breathe. Breathe. If it’s just not coming to you, revisit Day 4, which covers functions at great length.

OK, ready?

The confusing thing about this example is that the variable called temp is used in both functions. In the convertTemp() function, it’s used to store the temperature in Fahrenheit (which is supplied by the user). In the fahrenToCelsius() function, it’s used to calculate temperature in Celsius. Not only does this confuse us, it also confuses JavaScript. Here’s what happens when you try running the code without vars.

Notice that if you try to convert 50 degrees Fahrenheit, you get a message that says, “10 degrees Fahrenheit is 10 degrees Celsius.” Why does the program suddenly think you entered 10 degrees instead of 50? Let’s trace the functions to see what happened.

When we call convertTemp() and type “50″ into the prompt, we get

 temp = 50;



In the next step, “temp” is passed to the function called farenToCelsius(). Inside farenToCelsius(), the parameter called faren is then set to 50 and “temp” gets set to (50 – 32) * 5/9, which is 10. Before returning the value, you have:

 faren = 50

 temp = 10

Now farenToCelsius() returns 10 to the variable celsius:

 temp = 10

 celsius = 10

And we’re left with the false statement, “10 degrees Fahrenheit is 10 degrees Celsius.”

It’s possible to solve this issue if you carefully avoid naming your variables the same thing. If you didn’t have a variable called temp in both functions, you wouldn’t have a problem.

Unfortunately, this isn’t the best solution. As you start adding more and more functions to your script, it becomes harder to ensure that you’re not re-using variable names. Also, you will repeatedly use lots of variable names, like loop, index, count, and the_name. Coming up with different versions of these commonly used variable names would be a real pain.

A better solution is to tell JavaScript that the variable called temp inside the fahrenToCelsius() function is different from the temp variable in the convertTemp() function. If every function has its own special temp variable, then you don’t have to worry about certain functions messing with the variables of other functions.

If you haven’t guessed yet, this is exactly what var does. Let’s take a look.

The Way of Var

To keep JavaScript from mixing up same-name variables, put var in front of your variables as you declare them. A variable inside a function that’s declared with var is called a local variable, and it only exists inside that function. In general, you want your variables to be local whenever possible.

Here is the JavaScript with the correct vars in it:

 function fahrenToCelsius(faren)

 {

 	var temp = (faren - 32) * 5 / 9;

 	return temp;

 }



 function convertTemp()

 {

 	var temp = prompt("what temperature Fahrenheit? ","50");

 	var celsius = badFahrenToCelsius(temp);

 	alert(temp + " degrees Fahrenheit is " +

 	celsius + " degrees Celsius.");

 }

And here’s how it works. Let’s say we call convertTemp() and type 50 into the prompt. Because we used var before the prompt, this temp is localized to the convertTemp() function. So …

 (inside convertTemp) temp = 50

As before, we pass temp to the function called fahrenToCelsius(). Inside fahrenToCelsius(), the parameter called faren gets set to 50. Then temp is set with the line:

 var temp = (faren - 32) * 5 / 9;

As before, putting that var in front of temp tells JavaScript, “This variable called temp is different than any other variable called temp. This one exists only inside the fahrenToCelsius function.” Once JavaScript finishes with fahrenToCelsius(), the special temp variable vanishes. So, just before fahrenToCelsius() returns,

 faren = 50

 (inside fahrenToCelsius) temp = 10

 (inside convertTemp) temp = 50

fahrenToCelsius() then returns its version of the temp variable, which is 10. Once we leave fahrenToCelsius(), its version of the temp variable vanishes.

When fahrenToCelsius() returns, it sets the variable called celsius to 10:

 (inside convertTemp) temp = 50



 (inside convertTemp) celsius = 10

And thus the alert message says, “50 degrees Fahrenheit is 10 degrees Celsius.” Which is exactly what we want.

To review, by using var before a variable, you localize that variable to the one function that houses it. And once that function ends, the variable ceases to exist.

And that’s the (loose) end of today’s lesson. Now all that’s left is your homework assignment.

Conclusion

I didn’t want to give you anything too heavy on the very first day. Mostly I just wanted to make sure you understood all the elements covered in Part I. After today, we’ll be diving in pretty deep, and, if you don’t have a firm grasp of the basics, you might slide into an abyss of confusion. Or – even worse – stop reading. So, make double-sure you understood:

  • why var is a good thing;
  • how to use the if-then-else shorthand operator.


Before we get down and dirty tomorrow, put your knowledge to the test with a little exercise I whipped up.

Now, on to the next Lesson