Sams Teach Yourself JavaScript in 24 Hours Free Open Book

Sams Teach Yourself JavaScript in 24 Hours

Previous Page
Next Page

Using Variables

Unless you skipped the first few 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 09 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 sensitivetotalnum, 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.

Using these rules, the following are examples of valid variable names:

total_number_of_fish
LastInvoiceNumber
temp1
a
_var39

By the Way

You can choose to use either friendly, easy-to-read names or completely cryptic ones. Do yourself a favor: use longer, friendly names whenever possible. Although you might remember the difference between a, b, x, and x1 right now, you might not after a good night's sleep.


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 keywordyou'll avoid errors and make your script easier to read, and it won't usually cause any trouble.

By the Way

For the most part, the variables you've used in earlier hours of this book have been global.


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.

You should now understand the difference between local and global variables. If you're still a bit confused, don't worryif 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;

Because incrementing or decrementing variables is quite common, JavaScript includes two types of shorthand for this syntax. The first is the += operator, which enables you to create the following shorter version of the preceding 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.

By the Way

These operators are strictly for your convenience. If it makes more sense to you to stick to lines = lines + 1, do ityour script won't suffer.


Previous Page
Next Page
Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


     Main Menu
Sams Teach Yourself JavaScript in 24 Hours
Table of Contents
Copyright
About the Author
Acknowledgments
Part I: Introducing the Concept of Web scripting and the JavaScript Language
Part II: Learning JavaScript Basics
Hour 5. Using Variables, Strings, and Arrays
Using Variables
Understanding Expressions and Operators
Data Types in JavaScript
Converting Between Data Types
Using String Objects
Working with Substrings
Using Numeric Arrays
Using String Arrays
Sorting a Numeric Array
Summary
Q&A
Quiz Questions
Quiz Answers
Exercises
Hour 6. Using Functions and Objects
Hour 7. Controlling Flow with Conditions and Loops
Hour 8. Using Built-in Functions and Libraries
Part III: Learning More About the DOM
Part IV: Working with Advanced JavaScript Features
Part V: Building Multimedia Applications with JavaScript
Part VI: Creating Complex Scripts
Part VII: Appendixes
Index


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele