JavaScript Tutorial Part IIIVariable Basics and Program Flow Control
|
|
|
| 4.7/5.0 (7 votes total) |
|
|
|
William Bontrager
|
Variable
Basics and Program Flow Control
Here is
what this part of the tutorial covers:
Types of
variables Numbers Strings Objects Date String
Program Flow
Control if() else while() do...while() for() Name
Spitter
~~
Types of variables
In Part
I of this article series you were introduced to variables. Part II used some
more variables while explaining functions.
You may
have come to the conclusion that JavaScript has several different types of
variables. Well, you're right.
The
variable type is determined by what type of value it contains.
JavaScript has 3 main types of variables:
(1)
Number -- A variable containing a number. It can be whole or
decimal.
Examples: 4 4.4 44
(2)
String -- A variable containing a string of characters. It may include numbers
and any other characters. Strings are assigned to a variable or otherwise
manipulated in a JavaScript program by enclosing them between either single
(') or double (") quotes.
Examples: '4b' "Hello, world!" "12 + 24"
When it
is enclosed between single or double quotes it is a string variable, even if all
the characters are numerical.
Example:
"4"
Because
"4" is between quotes, it signals the browser that it is a string rather than a
number.
(3)
Object -- An object is a variable which can contain more than one value. It can
contain number(s) and string(s), together, in the same object. An object
variable can also contain functions and even other objects.
Here are
some basics about each of the variable types.
~~
~~ Numbers
Number
variables are used when number comparisons or mathematical calculations are
required.
Here are
some basic calculations that can be done:
Note:
The equal sign used in the context of assigning a value to a variable is
"determine the value or equation on the right and then let the variable on the
left equal that determination". The programming code assigning a value to a
variable is referred to as an assignment statement.
var
n = 2; // variable n now holds the value 2 n = n * 3; // (* is multiply)
variable n now holds the // value 6 n = n / 4; // (/ is divide) variable
n now holds the // value 1.5 n = n - 7; // (- is subtract) variable n now
holds the // value -5.5 n = n + 13.5;// (+ is addition) variable n now
holds the // value 8 n++; // (++ is increment by 1) variable n now //
holds the value 9 n--; // (-- is decrement by 1) variable n now // holds
the value 8 n = n % 3; // (% is modulus -- the remainder of a //
division) variable n now holds the // value 2 n = n * n; // variable n
now holds the value 4
One
could build a calculator using the above mathematical operators. A graphical
calculator with a scrolling tape, operated entirely by clicking with no keyboard
input being accepted, and with memory keys used to assign and display the
results of interim calculations, may be a nice project for later in this series
when a few more of the basics of program decision and flow control have been
introduced.
Program
flow is often determined by the content of a variable. This
if(n ==
10) { document.write('It is 10.'); }
will
print "It is 10." on your page if the variable n equals 10.
Program
flow can also be decided by comparing two or more variables and determining
whether they are equal or in what way they are unequal.
Here are
some number variable comparisons that can be done. Each comparison yields
either "true" or "false":
(n
== b) // true if both n and b contain the same number. Otherwise,
false. (Note: "==" is a test for equality while "=" is an assignment
statement symbol.) (n < b) // true if n is less than b. Otherwise,
false. (n <= b) // true if n is less than or equal to b. Otherwise,
false. (n > b) // true if n is more than b. Otherwise, false. (n
>= b) // true if n is more than or equal to b. Otherwise, false. (n !=
b) // true if n is not equal to b. Otherwise, false.
In
the above examples, the variable b could be an actual number. For
example,
if(n
< 10) { document.write('Is less than 10.'); }
will
print "Is less than 10." on your page if the variable n is less than
10.
~~
~~ Strings
String
variables are used when a sequence of characters (any characters not to be
treated as numbers) are required for display or program control.
String
variables have several symbols in common with number variables.
"="
means the same as it does in numbers, "assign the value on the right to the
variable on the left".
"=="
means "is equal to" except the comparison is character by character rather
than the numerical value. Examples:
var s =
'hi'; // assigns "hi" to variable s s == 'hi'; // is true s == 'hi ya'; //
is false (is not exactly the same) s == 'HI'; // is false ("==" is case
sensitive) s == 'bye'; // is false
The
program code:
var s =
'hi'; if(s == 'hi') { document.write('The same!'); }
will
print "The same!" on your page if the variable s contains 'hi'.
Another
symbol that string and number variables have in common is the "+" symbol. For
number variables, it means addition. However, for string variables it means
concatenation:
var a =
"Hello,"; var b = "world!"; var s = a + b;
stores
the string "Hello,world!" in the variable s.
If you
know ahead of time what the variables a and b will contain, you can accomplish
the same thing with:
var s =
"Hello," + "world!";
If you
want a space in between, you could use either one of the following two
lines:
var s =
a + " " + b; var s = "Hello," + " " + "world!";
With the
above value in s, the code:
s = s +
' -- real loud :)'; document.write("My program says: " + s);
will
print "My program says: Hello, world! -- real loud :)" on your
page.
~~
~~ Objects
An
object can contain many variables and entire functions, and even other objects,
within itself. In order to use the stuff in the object, the object must be
assigned to a variable.
(Although you can make your own objects, this article deals only with
objects that are built into the JavaScript language.)
To
assign an object to a variable, the name of the object must have a pair of
parenthesis at the end (which can have values in them, like functions) and you
must use the word: new
~~
~~ Date
Here is
an example of assigning the Date object to a variable.
var d =
new Date();
The
variable d is now an object variable and has access to all the variables and
functions within the object. To accomplish an access, type the object variable's
name, then a period, then the name of the function or variable inside the
object.
The
following example will access several functions and store the results. Wherever
you put the following code, it will print the current date and time on your
page:
<script language="JavaScript"> <!-- prints date and time on
page var d = new Date(); var hour = d.getHours(); var minute =
d.getMinutes(); var second = d.getSeconds(); var time = 'time is ' + hour
+ ':' + minute + ':' + second; var month = d.getMonth(); month = month +
1; var day = d.getDate(); var year = d.getYear(); if(year < 2000) {
year = year + 1900; } var date = 'date is ' + month + '/' + day + '/' +
year; document.write('The ' + date + ' and the ' + time); //
--> </script>
Notice
the line: month = month + 1;
It is
there because JavaScript's numerical representation of the calendar months are
the digits 0 through 11, rather than the human representation of digits 1
through 12. The line adds 1 to the value returned by d.getMonth() Also, notice the line
beginning with: if(year
It is
there because some browsers will display the correct 4-digit year and some
browsers will display the year minus 1900. The line checks to see if year is
less than 2000 and, if so, adds 1900 to it.
Let's do an example with another object.
~~
~~ String
Sometimes, knowing the length of string variables can be essential to
your program. To determine the length, you must create an object variable using
the built-in: String var s = new String('William');
The
variable s is now an object variable which contains the string "William" along
with several other values and functions. One of the values stored in s is the
length of the string it contains. Two of the functions it contains are
toUpperCase() and toLowerCase().
This
code uses the mentioned value and functions (note that it will print the
<pre> and </pre> HTML tags):
<script language="JavaScript"> <!-- prints data about
"William" using the object String var s = new String('William'); var uc =
s.toUpperCase(); var lc = s.toLowerCase(); var sdisp = '<pre>\nSome
stuff about ' + s + '...\n' + ' Length: ' + s.length + '\n' + 'Upper
Cased: ' + uc + '\n' + 'Lower Cased: ' + lc +
'\n</pre>'; document.write(sdisp); //
--> </script>
Note
that a line break is represented in string variables with the two-character
sequence: \n
The
above code will write the following on your page as preformatted
text:
Some
stuff about William... Length: 7 Upper Cased: WILLIAM Lower Cased:
william
"Netscape JavaScript Reference" and "Netscape - Client-Side
JavaScript Guide" contain lists of built-in objects and functions. The
references are linked from http://search.netscape.com
/Computers/Programming/Languages/JavaScript/References
~~
Program Flow Control
Much of
what you do with JavaScript will require actions dependant on the contents of
variables.
~~
~~ if()
This
articles series has used the if() flow control statement several times. It
is of the format:
if()
{ // code to execute }
Between
the parenthesis is the evaluation. Between the curly braces is the code to
execute if the evaluation is true. Example:
if(n ==
2) { n++; }
One-line
code to execute following the if() statement does not need to be in curly
braces. And, whether or not it is in curly braces, it can be all on one line.
These two examples work just as well as the above:
if(n ==
2) { n++; } if(n == 2) n++;
However,
a multi-line code block must be within curly braces:
if(n ==
2) { n++; n = n * n; }
All of
the flow control statements in this section follow the same rule: If the code to
run is a single line, it may be within curly braces but it is not necessary.
However, if the code is multi-line, the curly braces are required.
~~
~~ else
The if()
flow control statement can have an accompanying: else
if(n ==
2) n++; else n--;
A
multi-line "else" code block would look something like:
if(n ==
2) n++; else { n = n + 21; n = n * n; }
If you
use an else statement, it must immediately follow an if()
statement.
For
example, this will not run correctly:
if(n ==
2) n++; document.write('something'); else n = n - 1;
The
corrected code is:
if(n ==
2) n++; else n = n - 1; document.write('something');
~~ ~~
while()
The
while() flow control statement executes it's code so long as whatever is between
it's parenthesis evaluates as true:
var n =
1; while(n <= 10) { document.write('<br>' +
n); n++; }
writes
the current value of n on your page so long as the value of n is less than or
equal to 10. In other words, it will write a list of numbers 1 through 10 on
your page.
However,
this
var n =
22; while(n <= 10) { document.write('<br>' +
n); n++; }
will
write nothing on your page because the statement between the parenthesis is
never true.
~~
~~ do ... while()
The do
... while() statement, however, will always execute it's code once because it
checks the value in the parenthesis after the code is executed. Thus,
var n =
22; do { document.write('<br>' + n); n++; } while(n <=
10)
will
print the number 22 on your page. And
var n =
1; do { document.write('<br>' + n); n++; } while(n <=
10)
will
print the numbers 1 through 10.
~~
~~ for()
The
for() flow control statement is used to make a series of consistent changes and
test a value repeatedly. There are three items within the for()'s parenthesis,
separated with semi-colons.
The
first item is the variable initialized to a specific value.
The
second item is the check.
The
third item changes the variable.
This
prints the numbers 1 through 10:
for (var
n = 1; n <= 10; n++) document.write('<br>' + n);
~~
Name Spitter
Here is
a function that may amuse some people for a few moments. But then, maybe not.
It's a simple thing with the purpose of demonstrating some of what has been
covered in these first three parts of the JavaScript Tutorial.
The Name
spitter is two JavaScript functions and a form that accepts a first name and a
last name. When the button is clicked, the spitter does some calculations then
opens up a popup window with the name printed twice as many times as the number
of characters it contains, with ever increasing space between the
names.
There
are two functions, which should go between the <head> and </head>
tags. The form should be below the <body> tag. Here is the complete
page:
<!-- BEGIN 61 lines of code
--> <html> <head>
<script language="JavaScript"> <!--
function PopUp(ss) { var p =
'height=300,width=500,scrollbars=yes,resizable=yes'; pu =
window.open('','',p); pu.document.writeln('<html><body>'); pu.document.writeln(ss); pu.document.writeln('</body></html>'); }
// end of PopUp()
function spitter() { // The document.SpitForm._____.value variables
contain // the contents of the fields named ______ in the // form named
SpitForm. var name = document.SpitForm.first.value + ' '
+ document.SpitForm.last.value; var n = String(name); var i = n.length
- 1; var s = n.toUpperCase(); s = s + ' has an '; if(i % 2) s = s +
'odd'; else s = s + 'even'; s = s + ' number of characters (' + i; s =
s + ') not counting the space between names.<br><br>'; i =
n.length * 2; var bar = ''; var br = ''; for(var ii = 0; ii < i;
ii++) { bar = ' ' + bar; br = '<br>' + br; s = s + br + bar +
name; } // end of for() s = s + '<hr>See, <b>very</b>
short term amusement :-)<hr>'; PopUp(s); } // end of
spitter()
// --> </script>
</head> <body>
<form name="SpitForm"> <table><tr> <td
align=right>First Name:</td> <td><input type="text"
name="first" size=28></td> </tr><tr> <td
align=right>Last Name:</td> <td><input type="text"
name="last" size=28></td> </tr><tr> <td colspan=2
align=right> <input type="submit" value="Show Me"
onClick="spitter()"> </td> </tr></table> </form>
</body> </html> <!-- END 61 lines of code
-->
Now,
go forth and populate the internet with elegant and benign JavaScript code
:)
Happy Happy!
|