HTML and CSS Reference
In-Depth Information
14.7 Variables
Sometimes we need to be able to collect data from the user and do something with it. A
simple example is prompting the user for a name and writing the name to the document.
We would store the name in a variable . You probably took a math course at some point
and used x and y as variables in equations as placeholders for values. The same princi-
ple applies when using variables in JavaScript (we won't do any tricky math, though, so
relax!). JavaScript variables are also placeholders for data and the value of the variable
can change. Robust programming languages like C++ and Java have all kinds of rules
for variables and their data types. JavaScript is very loose that way. We won't have to
worry about what type of data is contained in a variable.
FAQ
Are there any tips for creating variable names?
It really is something of an art form, but first of all, you want to create a variable name that
describes the data it contains. The underscore, or uppercase character, can be used for read-
ability to imply more than one word. Do not use other special characters, though. Stick to
letters and numbers. Be careful not to use JavaScript reserved words or keywords , such as
var , return , function , and so on. A list of JavaScript keywords can be found at
http://www.webreference.com/javascript/reference/core_ref. The following are some variable
names that could be used for a product code:
productCode
prodCode
product_code
Writing a Variable to a Web Page
Before we use a variable we can declare it with the JavaScript var keyword. This step
isn't necessary but it is good programming practice. We can assign data to a variable
using the assignment operator, the equals sign (=). A variable can contain a number or a
string. A string is encapsulated in quotes, and can contain alphabetic characters, spaces,
numbers, and special characters. For instance, a string can be a last name, e-mail
address, street address, product code, or paragraph of information. Let's do a practice
exercise of assigning data to a variable and writing it to the document.
HANDS-ON PRACTICE 14.4
In this Hands-On Practice you will declare a variable, assign string data to it, and write
it to the document.
Open a text editor and type the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
 
Search WWH ::




Custom Search