Sams Teach Yourself JavaScript in 24 Hours
- Table of Contents
- Copyright
- About the Author
- Acknowledgments
- We Want to Hear from You!
- Reader Services
- Introduction
- Part I: Getting Started
- Hour 1. Understanding JavaScript
- Hour 2. Creating a Simple Script
- Hour 3. How JavaScript Programs Work
- Part II: Learning JavaScript Basics
- Hour 4. Using Functions and Variables
- Hour 5. Using Strings and Arrays
- Hour 6. Testing and Comparing Values
- Hour 7. Repeating Yourself: Using Loops
- Hour 8. Using Math and Date Functions
- Part III: The Document Object Model (DOM)
- Hour 9. Working with the Document Object Model
- Hour 10. Responding to Events
- Hour 11. Using Windows and Frames
- Hour 12. Getting Data with Forms
- Hour 13. Using Graphics and Animation
- Part IV: Moving on to Advanced JavaScript Features
- Hour 14. Creating Cross-Browser Scripts
- Hour 15. Creating Custom Objects
- Hour 16. Working with Sounds and Plug-Ins
- Hour 17. Debugging JavaScript Applications
- Part V: Working with Dynamic HTML (DHTML)
- Hour 18. Working with Style Sheets
- Hour 19. Using Dynamic HTML (DHTML)
- Hour 20. Using Advanced DOM Features
- Part VI: Putting It All Together
- Hour 21. Improving a Web Page with JavaScript
- Hour 22. Creating a JavaScript Game
- Hour 23. Creating DHTML Applications
- Hour 24. JavaScript Tips and Tricks
- Part VII: Appendices
- Appendix A. Other JavaScript Resources
- Appendix B. Tools for JavaScript Developers
- Appendix C. Glossary
- Appendix D. JavaScript Quick Reference
- Appendix E. DOM Quick Reference
Using Variables
Unless you skipped the first three hours of this book, you've already used a few variables. You probably can also figure out how to use a few more without any help. Nevertheless, there are some aspects of variables you haven't learned yet. We will now look at some of the details.
Choosing Variable Names
Variables are named containers that can store data (for example, a number, a text string, or an object). As you learned earlier in this book, each variable has a name. There are specific rules you must follow when choosing a variable name:
- Variable names can include letters of the alphabet, both upper- and lowercase. They can also include the digits 0–9 and the underscore (_) character.
- Variable names cannot include spaces or any other punctuation characters.
- The first character of the variable name must be either a letter or an underscore.
- Variable names are case-sensitive—totalnum, Totalnum, and TotalNum are separate variable names.
- There is no official limit on the length of variable names, but they must fit within one line. (And you must be able to type the same name twice to make use of the variable.)
Using these rules, the following are examples of valid variable names:
total_number_of_fish LastInvoiceNumber temp1 a _var39
Using Local and Global Variables
Some computer languages require you to declare a variable before you use it. JavaScript includes the var keyword, which can be used to declare a variable. You can omit var in many cases; the variable is still declared the first time you assign a value to it.
To understand where to declare a variable, you will need to understand the concept of scope. A variable's scope is the area of the script in which that variable can be used. There are two types of variables:
- Global variables have the entire script (and other scripts in the same HTML document) as their scope. They can be used anywhere, even within functions.
- Local variables have a single function as their scope. They can be used only within the function they are created in.
To create a global variable, you declare it in the main script, outside any functions. You can use the var keyword to declare the variable, as in this example:
var students = 25;
This statement declares a variable called students and assigns it a value of 25. If this statement is used outside functions, it creates a global variable. The var keyword is optional in this case, so this statement is equivalent to the previous one:
students = 25;
Before you get in the habit of omitting the var keyword, be sure you understand exactly when it's required. It's actually a good idea to always use the var keyword—you'll avoid errors and make your script easier to read, and it won't usually cause any trouble.
A local variable belongs to a particular function. Any variable you declare with the var keyword in a function is a local variable. Additionally, the variables in the function's parameter list are always local variables.
To create a local variable within a function, you must use the var keyword. This forces JavaScript to create a local variable, even if there is a global variable with the same name.
To better understand the types of variables and declarations better, look at Listing 4.4. This is a modified version of the Greet function example from earlier in this hour.
Example 4.4. A script using both local and global variables
<html>
<head>
<title>Local and Global Variables</title>
<script LANGUAGE="JavaScript" type="text/javascript">
var name1 = "Fred";
var name2 = "Ethel";
function Greet(who) {
alert("Greetings," + who);
var name2 = "Barney";
}
</script>
</head>
<body>
<h1>Function Example: the Sequel</h1>
<p>Prepare to be greeted twice.</p>
<script LANGUAGE="JavaScript" type="text/javascript">
Greet(name1);
Greet(name2);
</script>
</body>
</html>
The script in Listing 4.4 uses the following variables:
- name1 and name2 are global variables defined in the header.
- who is a local variable created in the Greet function's parameter list.
- The Greet function creates a local variable called name2. Since the var keyword is used, this variable is local to the function and does not affect the global variable name2. (If it did, the name in the second greeting would change. )
Notice that the global variables are declared within the header of the HTML document. You can actually declare variables in any script in the document, but the header is a good place for global variables because it is executed first. If you attempt to use a variable before it is declared or assigned a value, it will contain the null value and may cause a browser error.
You should now understand the difference between local and global variables. If you're still a bit confused, don't worry—if you use the var keyword every time, you'll usually end up with the right type of variable.
Assigning Values to Variables
As you learned in Hour 2, "Creating a Simple Script," you can use the equal sign to assign a value to a variable. For example, this statement assigns the value 40 to the variable lines:
lines = 40;
You can use any expression to the right of the equal sign, including other variables. You have used this syntax earlier to add one to a variable:
lines = lines + 1;
Since incrementing or decrementing variables is quite common, JavaScript includes two types of shorthand for this syntax. The first is the += operator, which allows you to create the following shorter version of the above example:
lines += 1;
Similarly, you can subtract a number from a variable using the -= operator:
lines -= 1;
If you still think that's too much to type, JavaScript also includes the increment and decrement operators, ++ and --. This statement adds one to the value of lines:
lines++;
Similarly, this statement subtracts one from the value of lines:
lines--;
You can alternately use the ++ or -- operators before a variable name, as in ++lines. However, these are not identical. The difference is when the increment or decrement happens:
- If the operator is after the variable name, the increment or decrement happens after the current expression is evaluated.
- If the operator is before the variable name, the increment or decrement happens before the current expression is evaluated.
This difference is only an issue when you use the variable in an expression and increment or decrement it in the same statement. As an example, suppose you have assigned the lines variable the value 40. The following two statements have different effects:
alert(lines++); alert(++lines);
The first statement displays an alert with the value 40, and then increments lines to 41. The second statement first increments lines to 41, then displays an alert with the value 41.
Data Types in JavaScript | Next Section

Account Sign In
View your cart