background
|
|
bonsai
The Element
A small area for Bonsai related material.
More icon

bonsai
The Element
A small area for Bonsai related material.
More icon
|
|
Up Image
Navigation
Search this Site
Enter your search terms

Site Breadcrumb - You are here
|
Thau's JavaScript Tutorial
Lesson 2

by Thau!

Page 2 — The Body of the First Variable Example

Now that we've defined the variables, let's do something with them. We start JavaScript in the body of a page just like we do in the head:

<script language="JavaScript">
<!-- hide me

And here's how we can use JavaScript to write variables and HTML to a Web page:

// here's how to use JavaScript to write out HTML

document.writeln("<b>The monkey dances ");

document.writeln(secs_per_year);

document.writeln(" seconds per year.</b><p>");

Here are the interesting points about these three lines:
document.writeln() (as in "write line") writes whatever's between the parentheses to a Web page.
There's a surprising amount of detail involved in what document.writeln() really means. For now, just remember that when you're between <script> and </script> tags, you need to use document.writeln("blah!") to write HTML to your Web page.

Characters inside quotes are printed; characters not inside quotes are considered variables.
Notice that in the first and third lines, quotes surround the thing we want printed, while there are no quotes around secs_per_year. Because there are no quotes around secs_per_year, JavaScript thinks it's a variable and swaps in the value of the variable. Luckily, back in the header we defined secs_per_year to be some huge number, so that's what gets printed. If we hadn't defined secs_per_year, JavaScript would probably report an error.

Anything between quotes is called a string and won't get interpreted by JavaScript. This example uses double quotes ("), but it could also use single quotes ('). The two are interchangeable. If the second line were document.writeln("secs_per_year"), the JavaScript would write secs_per_year to the page, instead of 31,536,000.

This distinction between variables and strings is very important, so make sure you understand what I'm saying before you go on.

You can write HTML with the document.writeln() command.
Note the <b> and </b> tags in the first and third lines.

That's the rundown on this example. One question that often comes up is, "What JavaScript goes in the head of a page and what goes in the body?"

Usually it doesn't matter, but it's a good idea to put most of your JavaScript in the head of a page. This is because the head gets read before the body, so any variables that appear in the body (like secs_per_min) will already have been declared in the head by the time they're needed. If for some reason secs_per_min were defined after JavaScript tried to do the document.writeln(secs_per_min) command, you'd get a JavaScript error.

OK, we're almost ready to do an exercise using variables, but first, a short note about strings.

next page»