![]() |
|
Technology Computing, programming, science, electronics, telecommunications, etc. |
|
Thread Tools | Display Modes |
![]() |
#25 |
I am meaty
Join Date: Dec 2001
Location: Salt Lake City, UT
Posts: 1,119
|
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 } 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.
__________________
Hot Pastrami! |
![]() |
![]() |
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
|
|