This would be a good time to mention variable
scope. When you create a variable in your script with the
var keyword, that is where the variable is defined. If the variable is defined inside a block, it's
scope is limited to that block. What that means is, once you leave the block of code which defined the variable, it goes away, and no code outside of that block can see the variable. However, any sub-blocks of the block which contains the variable definition can access it, no matter how deep the sub-block is.
Any variable defined outside of a block is accessible to
everything, because it is in the assumed block which wraps around everything, and every other block is a sub-block of that one. Such a variable is called a "global" variable, since everything can see it.
Here's a chunk of code to illustrate... the numbers are there as a reference, not part of the code itself:
Code:
00 var jimIQ = 135;
01 var userName = prompt("Please enter your name");
02 var userIQ = prompt("Please enter your IQ");
03
04 if (userName == "Lumberjim") {
05 var jimResponse = "You're too sexy for your shirt";
06 document.write(response);
07 }
08 else {
09 var notJimResponse = "Jim is too sexy for his shirt";
10 document.write(notJimResponse);
11 if (userIQ < jimIQ) {
12 var iqResponse = " ...and you're not as smart as he is.";
13 document.write(iqResponse);
14 }
15 }
jimIQ,
userIQ, and
userName are all global variables, because they are not defined inside a block. The variable
jimResponse was defined in the block which starts on line 04 and ends on line 07, so it's scope is limited to that block. If I tried to access the variable
jimResponse on line 09 or line 12, I'd get a "variable not defined" error. But I *could* access
notJimResponse on line 13, because that block is a sub-block of the one which defines
notJimResponse.
If I tried to accecss
jimResponse ,
notJimResponse or
iqResponse at any point after line 15, I'd get a "variable not defined" error, because their blocks ended, and the variables went away.
Next: Functions. Then Operators. Then conditionals and loops. Unless I think of something else that I ought to cover first. The way scope works, and it's usefulness, will become more obvious when we get to Functions and Loops.