View Single Post
Old 03-23-2004, 11:08 AM   #3
hot_pastrami
I am meaty
 
Join Date: Dec 2001
Location: Salt Lake City, UT
Posts: 1,119
The next few posts are going to go through the example above line-by-line. I'll cover each topic more thoroughly later as we get to that part, but this'll be a good quick overview.
Code:
var prompt = "Click OK to change the background to red.\nClick Cancel to make it blue.";
var is a Javascript keyword, which is short for variable. You use this keyword whenever you want to define a new variable, in this case a variable named prompt. A variable is simply a way to attach a name to any given value, so that you can use that value later. Now that the variable prompt is defined, we can use it any time we want the text "Click OK to change the background to red.\nClick Cancel to make it blue." to appear.

You can change a variable's value at any time, just by assigning it a new value with the equals operator, like so:
Code:
prompt = "Do you like the color red?";
...if you add this line, then any time the variable prompt is used, you'll get the new prompt text.

So how are variables useful? They're good for holding any information that may change while the script is running, or any information that may change with a future update of your script. Say you want to create a MadLibs webpage, where you want to ask the user for nouns, verbs, adjectives, etc, and then insert them all into a text for unexpected, potentially humorous (and potentially lame) outcomes. You'd want to store those user-provided words in variables, as well as the text that the words will be inserted into.

I'll use the MadLibs idea for a sample later... I've actually built such a thing before, although I've long since misplaced the code.

You may also wonder what the \n in that variable's value is all about... but if you entered the code into the Tester, you'll have already seen what it does. That's a newline character, which causes the text to break at that point and start on the next line down. It's one of several special characters, which we'll get to later.

The next post will continue to walk through the code of the first example.
__________________
Hot Pastrami!
hot_pastrami is offline   Reply With Quote