Lesson 1:JavaScript Input/Output and Calculations
JavaScript is a third generation language similar to but NOT derived from Java or C++. JavaScript is a portable code, working on the client side of the exchange rather than server. Like HTML, the code runs on the viewer's computer, interpreted by the browser. Working client-side means the code is directly accessable to the web p-age. JavaScript can be used for server-side programming, but usually languages like Visual BASIC, C++, Perl, and Java are used server-side. The standard for information sent from client-side to server-side is Common Gateway Interface.
Normal form processing involves a mix of client- and server-side operations. An example of how this works is:
- A client (viewer) types in a request for a web page into his browser.
- A copy of the web page, written in HTML and JavaScript, is sent to the client's computer.
- The client fills out the form and clicks on the submit button.
- The form data is checked and cleaned up with client-side processing using JavaScript.
- The data is sent tp a CGI program on the server.
- The CGI program interfaces with a database on the server.
- The server performs whatever actions are specified as necessary.
- The results are sent back to the client browser in the form of a new webpage.
JavaScript can be placed in either the head or body portion of a web page. Since a web page
is interpreted (read) top to bottom, any JavaScript in the head section will be executed before
the web page loads and output to the web page will appear at the top of the page. If the
JavaScript is in the Body section, any output will appear according to where the JavaScript
has been placed in the Body.
Code:
<script language = "JavaScript">
<!--
insert statements, ending with semicolon. ALL JavaScript statements end with a semicolon.
//-->
</script>
The partial tags <!-- and //--> are for those browsers
unable to run JavaScript. With these at each end of the actual
statements, if the browser cannot run them, the entire area becomes
a comment line in HTML. Also, since this is essentially an HTML
comment now, the rules about what is and is not allowed as a tag
in the head section can be ignored. Tags that normally would not
be allowed in the head section can be used.
Information entered in response to prompts is stored in variables. Variables are storage "boxes" created by the programmer, and exist only within the program. The web page creator chooses names for the variables when the
JavaScript program is written. A variable name can be composed of
letters, digits (0-9), and the underscore. It must start with a letter.
It cannot be a reserved word; i.e., a
word the system uses for a special purpose (like var or prompt). And
it is case sensitive: Total is not the same as total. These variable
name rules are similar to the rules for other computer languages.
Other computer languages usually have different types of variables
(string, numeric, logic, et cetera). JavaScript does not differentiate between the various types, so a variable is simply a variable. Calculations can be performed on the data contained within variables. If the data is internal (programmed in by the programmer), calculations can be performed without any special added steps. However, information gained via prompts is always in the form of literal strings and is not recognized by the system as numbers even if they are typed as such. They have to be parsed (changed) into numbers before mathematical operations can be performed with the information. Otherwise the system will treat it as a word and not a number.
This operation is performed by the parseFloat() object or the parseInt() object. Objects in JavaScript can be recognized by the () on the end. The () will contain the variable which is to be used in the operation. An object can be thought of as a built-in task handler. Object-oriented programming utilizes these built-in functions to make the programmer's job easier.
Some other useful built-in coding in JavaScript are part of the
Math object.
x = Math.round(x); will round the value in x to the nearest integer
x = Math.random(); will place a random generated value in x
x = math.pow(y,z); will place the value of y to the zth power in x
There are many more Math objects, and other JavaScript objects. You do not have to understand
object-oriented programming to use them. Sometimes just having a good
reference available is enough.
Top-down logic of a program would be:
- Create (declare) the variable that will store the information
- Prompt the viewer to enter the data to be placed in the variable
- The program automatically stores the data in the variable
- Do calculations, if any.
- Output a message using the stored and/or calculated data
NOTE: When entering a JavaScript statement in a text editor, let the text wrap naturally. It does not matter if the text goes to a second line. But do NOT hit the Enter key. Hitting the Enter key on the keyboard will cause a break in the statement and cause the program to not run correctly.
JavaScript statements:
document.write("characters to appear on web page");
Adds characters onto the web page. To have a line break, you must include the <br> HTML tag inside the quoatation marks.
var variable name;
Creates a variable and gives it a name
variable name = prompt("message to let viewer know what to type in","message that appears in textbox of prompt");
Activates a prompt box that asks a question and places the data provided by the viewer into the specified variable
alert("message to appear in alert box")
Causes an alert box to pop-up with a message created by the program. Viewer removes the alert by clicking on "ok" button
variable name= parseFloat(variable to turn from string to number);
Turns the data within the variable from a literal (word) into a decimal number
variable name= constant;
Places a specified value in the variable. For example tax=.07; or qtr="Fall"; Note quotes around literal values so the system does not mistake the word(s) for a variable name.
variable name= 4 + 5;
Adds 4+5 and places sum in the specified variable. Formulas can use any type of mathematical calculation(s). Rather than constants (actual numbers), calculations usually use variables. For example total=int+bal;
variable name= document.last Modified; document.lastModified contains the date the page was last changed, and this allows programmer to obtain that date and later show it automatically on the page
Takes the system data showing the date the page was last modified and places that in the specified variable
Comment lines
Comment lines in JavaScript are defined
by two slashes at the beginning.
//Script created by me
Calculations:
Calculations follow standard arithmetic rules.
The arithmetic symbols are:
addition + ( x = y+z; )
subtraction - ( x = y-z; )
multiplication * ( x = y*z; )
division / ( x = y/z; )
Order of heirarchy (What math operation is done first):
Parantheses (Do what in parentheses before other portions)
Powers (Powers before Mult/Div or Add/Sub)
Multiplication/Division
Addition/Subtraction
If same level of heirarachy, read from left to right.
A problem with JavaScript's non-differentiated variables is concatenation. With numbers, "int+bal" would mean the addition of the values within the two variables "int" and "bal". But if the values stored in "int" and "bal" came via
prompts, even if numbers were typed in the system will consider them "words". So if a viewer entered "4" as int and "55" as "bal", the calculation "total=int+bal;" would result in 455 (the "letter" 4 with the two "letters" 55 attached on
the end). The values in "int" and "bal" must be parsed (parseFloat operation) so they are numbers before the interpretor will correctly add the values as numbers instead of concatenating them as letters.
Example JavaScript programs
<html>
<head>
<script language = JavaScript>
<!--
var fullname;
fullname = prompt("Please enter your full name.", " ");
document.write(fullname);
document.write(" ,have a nice day.");
//-->
</script>
</head>
<body>
Any other contents of the web page, which will appear after the message:
fullname, have a nice day.
</body>
</html>
Errors in programs
An error in a program is a bug. To fix an error is to debug
the program. There are three types of bugs (errors): syntax, logic,
and user. A syntax error is a typo: a reserved word is mispelled or
punctuation is not correct. A logic error occurs when the program is
written with all the code grammatically correct but the program does not
do what the programmer designed it to. User errors occur when the user (viewer)
enters incorrect data in response to a correctly coded program. There are
steps that can make a program more foolproof (although the fools do tend
to be very inventive). A programmer can often spend a much greater amount
of time debugging a program than it took to design and type it. The more
carefully a program is designed, the fewer errors will occur and the
less debugging has to be done.
Lesson 2 of JavaScript
Return to main page