ITSE 1411 Beginning Web
JS Module 1 Discussion Variables Continued
Discussion
- Declaring and Initializing Variables
- A variable must be created, called declaring the variable.
- A variable is used to hold a value. The most basic way for a variable to hold a value is to
assign the value. This is done with the sign (=), which you may recognize as an equal. However,
in JavaScript, this character does not mean equal, it means assignment and is called the
assignment operator. For example:
var number = 6;
var firstName = "Judy"
var salesTax = 0.0825
- The above examples shows an integer variable (a whole number, a string variable -- we used those
in the document.write() methods in the first assignment, and a numeric number with a decimal
point. Notice numbers NEVER have quotes unless they are meant to be used as text (like a phone
number or zip code).
- The first time you assign a value to a variable it is called initialization. Initialization is
not required. You can wait and make assignments later and even reassign values.
- Displaying Variables
- A value can be displayed using the document.write() method. In the Healthy Heart Assignment,
you will use document.write() methods for literal strings only.
- To separate literal strings and variables in the document.write()
method, use the + operator. In the past in mathematics, you used the + operator to mean
addition. But, in JavaScript the + operator has more than one meaning. It also means
concatenation, which links literal strings and variables. Assuming that you have a variable
that has been declared and assigned a value and you wish to display the value with a description.
For example:
document.write("<p>Your sales total is $" + salesTotal + ".</p>");
- Modifying Variables
- You can change the value of a variable. The value does not have to remain as the initialized
value. For example:
var cost = 10;
var tax = .0825;
tax = cost * tax;
cost = cost + tax;
There are many ways to solve a math problem. The example above is only one. The variable
cost is first assigned 10. Tax is assigned .0825. Then, tax is changed to be the cost times
the tax, which would be .825 in this example. Then, if you add the tax to the cost, the
cost is 10.825. (Rounding does not occur automatically.)