These notes contain an introductory tutorial on the JavaScript language. If you are first learning JavaScript it is probably better to actually type in the code, rather than copying it. The syntax of JavaScript makes use of both parentheses "(" and ")" and curly brackets "{" and "}" for grouping. You have to be careful because the corresponding left characters and correspond rights have a very similar appearance in HTML-Kit. If possible, make the editor window's font size larger to differentiate their appearances.
JavaScript is a programming language which can access and manipulate every feature of an HTML document, indeed, it can access every feature of the entire browser (such as popup windows, the status bar, the history, etc. These browser elements are represented by so called objects within JavaScript. The objects are represented in a hierarchy called the Document Object Model (DOM). JavaScript also provides all the computational abilities of any standard programming language with structures for decision making, looping and creating user-defined functions.
JavaScript is maintained by the European Computer Manufacturer's Association consortium, and so its actual name is ECMA script, but everyone still refers to it as JavaScript. The Internet Explorer browser actually runs a variant called JScript, which is very close, but not identical to ECMA script (i.e. JavaScript). In general it's best to avoid the very latest features of these script languages because your audience's browser may not support them.
Using JavaScript in an HTML document is referred to as Dynamic HTML (DHTML) because it can give an HTML document a more dynamic behavior in various ways:
Comments are any text written in conjunction with code (of any kind) which have no effect on the outcome of the code, and are only present to document the code written. When you write in JavaScript or in any programming language, for that matter it is common to add comments to the code because this helps others understand why you wrote what you wrote. Additionally, it helps you understand what you wrote when you review the code later, after some significant time period.
Both HTML and CSS support comments, although it is perhaps less common to comment these since you mostly "see" the code you wrote, in contrast to JavaScript programming, where much of the code goes "unseen."windowThe subobjects of window are
In addition to subobjects, the JavaScript objects have action functions, or member functions, which are activated using the same "." syntax. The ones we'll start with (as does everyone else) are the write and writeln actions of the document object. Here is a simple JavaScript program created within the body of the document.
<script type="text/javascript">
<!--
document.writeln('Hello')
document.writeln('World')
// -->
</script>
Create this in HTML-Kit as follows:
<script type="text/javascript"> <!-- // --> </script>
document.writeln('Hello')
document.writeln('World')
<!-- // -->They are needed for browsers which cannot recognize the script tag, i.e., those which do not do JavaScript. In that case they act like comments for the code inside. In the last line, the "//" starts a comment line for JavaScript; this is necessary to prevent JavaScript from trying to read the HTML comment terminator "-->" as JavaScript code.
document.writeln('Hello')
is called a statement.
It consists of the action function call
writeln('Hello')
applied to the document object.
The effect is to write this HTML string and then a new line character.
In general an entire JavaScript program consists of a sequence of
statements.
The writeln function is called
with a string 'Hello' as its parameter.
Strings in JavaScript can be enclosed either by single quotes
(' .. ') or double quotes (" .. ").
document.writeln('Hello')
can be optionally followed by a semicolon (;). When this
is used two statements can be put on the same line like this:
document.writeln('Hello'); document.writeln('World');
Nevertheless, it's generally a better programming practice to
keep one statement per line.
window.document.writeln('Hello');
object.property object.method()The type array is used to represent lists of elements. The null value is common to all types and is often used to represent failure of an operation.
4 + 5 = 9 "a" + "b" = "ab" "4" + "5" = "45" 4 + "5" = "45"This ambiguity can be confusing at first. The last of these combines a numeric with a string and indicates that the string type "wins out." In contrast the multiplication operator, "*", is not ambiguous and will always do (or try to do) multiplication by forcing string values to numbers. Thus:
4 * 5 = 20 4 * "5" = 20 "4" * "5" = 20Try entering and running this JavaScript program (in the HTML body)
<script type="text/javascript"> <!-- document.writeln( 4 + 5 ); document.writeln( "<br />" ); document.writeln( "a" + "b" ); document.writeln( "<br />" ); document.writeln( "4" + "5" ); document.writeln( "<br />" ); document.writeln( 4 + "5" ); document.writeln( "<br />" ); document.writeln( "the sum is " + 4 + 5 ); document.writeln( "<br />" ); document.writeln( "the sum is " + (4 + 5) ); document.writeln( "<br />" ); document.writeln( 4 + 5 + " is the sum" ); document.writeln( "<br />" ); document.writeln( "the product is " + "4" * 5 ); // --> </script>The output is
9 ab 45 45 the sum is 45 the sum is 9 9 is the sum the product is 20
<script type="text/javascript"> <!-- document.writeln( 'Before' ); alert( 'Testing' ); document.writeln( 'After' ); // --> </script>View the result in the Preview window. To complete the rendering you need to press the OK button in the popup. The other way to write this call is:
window.alert( 'Testing' );
variable = value;or
var variable = value;The word var is a JavaScript reserved word which has the effect of declaring the variable, starting from this point on in the code. JavaScript permits variables to be used without declaring them but it is better to avoid this usage and always declare them. Here is a very simple example:
<script type="text/javascript"> <!-- var x = "Hello, " var y // still works with this line commented out y = "John" document.writeln( x + y + "<br />" ) x = 5 y = 6 document.writeln( x + y ) // --> </script>
This program illustrates that variables can be assigned values of any types. The ability to do so is referred to as polymorphism; it is characteristic of so-called script programming languages.
The above program doesn't illustrate any real need for variables, since that output could easily be created without any variables whatsoever. The real need of variables is illustrated when the output depends upon a value set by user input.<script type="text/javascript"> <!-- var name = prompt( "Enter your name!", "YOUR NAME" ) document.writeln( "Hello " + name + ", how are you" ) // --> </script>View the result in the Preview window. The result is that a dialog box will pop up with a text field in which the user can type a line of text. You need to enter something in the popup window and press the OK button.
Try running it again and press the Cancel button to see what happens. Cancelling should somehow signal that we want to abort the writeln statement. We'll deal with this problem when we introduce decision-based programming.
Like the alert function, prompt is actually an action function of the window object, and so another way to write it iswindow.prompt( "Enter your name!", "YOUR NAME" )This function uses 2 string parameters. The first parameter "Enter your name!" is what is displayed in the prompt window. The second parameter "YOUR NAME" is the initial value of the text field.
If you pressed the Cancel button, the str variable is null. In Javascript, the null value is similar (but not identical to) a variable being undefined, which would occur if we never even tried to set its value, such as in the script:
<script type="text/javascript"> <!-- var name document.writeln( "Hello " + name + ", how are you" ) // --> </script>JavaScript can regard these two situations as being the same and we will see how to handle them later.
<script type="text/javascript"> <!-- var str = prompt( "Enter a number", "" ) // prompt var num = parseFloat(str) // string to numeric //var num = str // what happens when you use this line ? var sum = num + num var product = num * num document.writeln( num + "+" + num + " = " + sum ) // output document.writeln( "<br/>" ) document.writeln( num + "*" + num + " = " + product ) // output // --> </script>View the result in the Preview window. Enter a number in the popup window and press the OK button. Then try running it again enter some non-numeric text to see what happens. Also try running it again and press the Cancel button to see what happens. The parseFloat is one of the global functions (see global function table), i.e. not an activation function, which converts a presumably numeric string to its numeric value. What this means is that it changes type. This function is valuable for several reasons:
The cases where something goes wrong are, in some sense, the most interesting. If we press Cancel then the str variable is set to null and so parseFloat will fail. If we simply type return or enter some junk like xxx instead of a number, str will not be null, but parseFloat will fail.
What parseFloat does when it fails is generate a numeric value called NaN (meaning Not a Number). A NaN value can be combined arithmetically with other values but the combination will always result in NaN and so in either case we print out this:NaN+NaN = NaN NaN*NaN = NaN
ClassName.function()similar to methods like
document.writeln()The difference is that they don't act on any object. The "." notation is merely a way to categorize the function as being part of a group of similar functions. In this way more than one class can use the same member function name without any ambiguity problem. In the following example we will use the square-root function:
Math.sqrtbeing a member of the Math class (see Math properties)
<script type="text/javascript"> <!-- var str = prompt( "Enter a number", "" ) // get a string var num = parseFloat(str) // string -> numeric var result = Math.sqrt(num) // compute square root document.writeln( "square root of " + num + " = " + result ) // output // --> </script>Here we are using the square root function, Math.sqrt. Try running it with input 9, getting the answer 3. One problem is to give a decent answer to the square root of a number which is not a perfect square. For example, try the input 3, getting the output:
square root of 3 = 1.7320508075688772We really want to simplify the answer. The common way to do this is to round it to a certain number of decimal places. The Math.round function is used to round decimal numbers to the closest integer and so we have to modify its usage to get it to round, say, to 2 decimal places. The desired statement is this:
result = Math.round( result * 100 ) / 100This is done prior to printing the answer, and so the entire program is this:
<script type="text/javascript"> <!-- var str = prompt( "Enter a number", "" ) // get a string var num = parseFloat(str) // string -> numeric var result = Math.sqrt(num) // compute square root result = Math.round( result * 100 ) / 100 // round to 2 decimal places document.writeln( "square root of " + num + " = " + result ) // output // --> </script>With this additional statement in place, the output gives the simplified answer:
square root of 3 = 1.73We can use this technique to round to any number of decimal places:
round to 1 place: multiply and divide by 10
round to 2 places: multiply and divide by 100
round to 3 places: multiply and divide by 1000
...