4. Introducing JavaScript

What We Will Cover


Elucidations

Reminders

Questions from last class?

Homework Questions?

Homework Discussion Questions

  1. Have any students worked with CSS before?
  2. How does CSS make formatting Web pages a simpler and more robust activity?
  3. When would you use an in-line style versus an embedded or external style?
  4. What challenges do new forms of media present to Web developers?
  5. How can CSS help meet thee challenges?

4.1: Introduction to JavaScript

Learner Outcomes

At the end of the lesson the student will be able to:

  • Discuss the history and theory of JavaScript

4.1.1: About JavaScript

  • JavaScript was developed by Brendan Eich while working at Netscape
  • Netscape released JavaScript in Navigator version 2.0B3 in December of 1995
  • Microsoft added support in IE version 3, released in August 1996, for their version of JavaScript which is called JScript
  • Since multiple browsers were supporting JavaScript, Netscape submitted the specification to a standards organization: European Computer Manufacturers' Association (ECMA)
    • Standardized as ECMA-262 in 1997
    • Officially known as ECMAScript
    • However, most people still call the language JavaScript
  • Since then, both Netscape and Microsoft have continued to add extensions to the standard language
  • In the last few years, however, Mozilla has taken the lead in JavaScript development from Netscape
  • For instance, Firefox has added support for E4X, an extension that adds native XML support to ECMAScript

Brief History of JavaScript

Version Date Browser Version
1.0 1995 Netscape Navigator 2.0
1.1 1996 Netscape Navigator 4.0
1.2 1997 Netscape Navigator 4.0
1.3 1998 Netscape Navigator 4.5
1.5 2001 Netscape Navigator 6.0
1.6 2005 Firefox 1.5
1.7 2006 Firefox 2.0

Brief History of JScript

Version Date Browser Version Approx. JavaScript
1.0 1996 Internet Explorer 4.0 1.0
4.0 1997 Internet Explorer 4.0 1.3
5.0 1999 Internet Explorer 5.0 1.5
5.5 2000 Internet Explorer 5.5 1.5
5.6 2001 Internet Explorer 6.0 1.5

JavaScript is Not Java

  • The last minute name change of LiveScript to JavaScript has resulted in years of confusion
  • There is no real relationship between Java and JavaScript
  • Java is a programming language developed by Sun Microsystems (vs. Netscape)
  • JavaScript was designed as a language for web browsers
  • Java is a general-purpose language like C++
  • JavaScript is a scripting language with easier to use, but more problematic, language features
  • A scripting language is designed to be easy to use for small programming projects
  • However, it becomes much harder to use scripting languages for large programming projects

More Information

4.1.2: What Can JavaScript Do?

  • JavaScript was designed as an easy way to add interactivity to HTML pages
  • Since its inception, JavaScript has become the default browser scripting language
  • Let us look at some of the things you can do with JavaScript
  • We will explore many of these during the course

Some JavaScript Capabilities

  • Validate the data users enter into forms
  • Perform calculations
  • Manipulate the HTML Document Object Model (DOM)
  • Change the browser itself or even create new browser windows
  • Create different content for different users
  • Randomly display different images
  • Play sounds
  • Create animations
  • Make online games
  • Respond to events (like mouseovers) to make your Web pages "come alive"

4.1.3: Case Study: Hiding E-Mail Addresses from Spammers

  • To introduce you to the language, the textbook provides a case study on using JavaScript to hide email addresses from spammers
  • Some terms and definitions:
    • Spam: Junk email
    • Spammer: Person who sends spam
    • Email harvester: Program that scans documents looking for email addresses
  • As the Internet has evolved, spammers, email harvesters and other intrusive programs have looked to take advantage of the Web
  • Because of this, you want to be careful when putting email addresses on a web site
  • Email harvesters work by scanning web pages and looking for text that looks like an email address
    john.smith@nowhere.net
  • When they find a match, they add the email address to a database
  • Spammers use these email databases to send out their spam messages

Listing Email Addresses

  • The problem for the case study is how to list email addresses that are hard for spammers to harvest
  • You can look at the problem by following the link: Monroe Public Library
  • Note how the email addresses are missing from the Staff Directory
  • Our job is to display the email addresses in a secure manner
  • JavaScript can help us protect email addresses from email harvesters
  • To do this, we want to list the email addresses in the web page in a scrambled way
  • Then we want to use JavaScript to unscramble the addresses when people look at the page

Staff Directory Web Page

Staff directory

4.1.4: Server-Side and Client-Side Programming

  • Before we can solve the problem, we need to look at how web programming works
  • Web programming comes in two types:
    • Server-side programming
    • Client-side programming

Server-Side Programming

  • Server-side programming puts the programs on the server that hosts the web site
  • The program can modify the content and structure of Web pages
  • This is shown in the following diagram
  • We will look at how to do this type of programming toward the end of the course
Diagram of server-side programming

Client-Side Programming

  • Client-side programming runs programs on user's computer
  • Programs likely to be more responsive to users
  • However, can never completely replace server-side programming
  • This is shown in the following diagram
Diagram of client-side programming

Combining Client-Side and Server-Side Programming

  • You can combine client-sided and server-sided programming
  • This allows you to take advantages of the strengths of both types of programming
  • This is shown in the following diagram
Diagram of client-side programming

4.1.5: Summary

  • JavaScript was first released in the Netscape Navigator 2 in 1995
  • Microsoft released a version of JavaScript, called JScript, in IE 3 in 1996
  • Since multiple browsers were supporting JavaScript, Netscape submitted the specification to a standards organization: European Computer Manufacturers' Association (ECMA)
  • Because of this, JavaScript is officially known as ECMAScript
  • However, almost everyone still calls it JavaScript
  • All the major browsers support the ECMAScript standard but add extensions
  • If the extension become widely used, then they eventually get added to the standard
  • JavaScript is not Java and has no real relationship to Java
  • JavaScript is a scripting language designed to be easy to use for small web-programming projects
  • Even though JavaScript is easy to use, it has many capabilities
    • We saw a list of some of those capabilities
  • We also looked at how web-programming works
  • Web programming comes in two types:
    • Server-side programming, which puts the programs on the server that hosts the web site
    • Client-side programming, which runs programs on the user's computer
  • You can combine client-sided and server-sided programming
  • This allows you to take advantages of the strengths of both types of programming

Check Yourself

  1. Who invented JavaScript and when was it released?
  2. Which browsers support JavaScript?
  3. Is there a standard JavaScript? Is so, what is the standard?
  4. Why was JavaScript invented?
  5. What task is JavaScript designed for?
  6. What is a client-side program?
  7. What is a server-side program?

Activity 4.1

Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.

Quick Quiz

  1. Which Netscape version was the first to support JavaScript programming?
    1. 1.0
    2. 2.0
    3. 4.0
    4. 4.5

  2. JavaScript is designed to be easy to use.

    True
    False

  3. Microsoft's Internet Explorer supports a slightly different version of JavaScript known as .
  4. Java programming and JavaScript programming are identical.

    True
    False

4.2: Creating Scripts

Learner Outcomes

At the end of the lesson the student will be able to:

  • Create a script element
  • Code basic JavaScript syntax
  • Write text to a Web document using JavaScript

4.2.1: Working with the Script Element

  • JavaScript can be placed either directly in HTML or in a separate file
  • We will first look at adding JavaScript directly to an HTML page

Creating a Script Element

  • To add JavaScript directly to HTML, you can use the script element
  • You can add the script element in either the head or body element of an HTML page
  • The syntax is:
    <script type="text/javascript">
        script commands and comments
    </script>
    
  • Where the script commands and comments are the scripting code
  • As an example, to display the words "Hello world" in a web page, you would add the code:
    <script type="text/javascript">
        document.write("Hello world");
    </script>
    
  • When the page is loaded, the JavaScript runs and displays:

  • Note that you can run other scripting languages, if they are supported by the browser, by specifying a different type

JavaScript Statements

  • Statements are the commands you give a computer in a program
  • One of JavaScript's many statements is: document.write(something);
  • JavaScript has many scripting statements, also known as JavaScript commands
  • The document.write() method is one way to send output to a web document
  • The first part of the statement, document, is known as an object
  • The second part, write(), is known as a method
  • The statement ends with a semicolon (;)
  • An object in the real world is some item that you can select and interact with
  • In programming, we simulate real-world objects using a programming language
  • We select the object using its name, such as document
  • We interact with the object by calling a method, such as write()

4.2.2: Understanding JavaScript Rules and the Use of White Space

  • Besides using semicolons to end statements, there are other JavaScript rules you need to know

JavaScript is Case Sensitive

  • First of all, JavaScript is case sensitive
  • That means that the following are NOT the same:
    document.write("Hi");
    Document.write("Hi");
  • The first line writes "Hi" to a web page
  • The second line means nothing to a browser and will cause an error

JavaScript Ignores Most Extra White Space

  • Like HTML, JavaScript ignores most occurrences of extra white space
  • This means that you can add extra spaces in your code to make it easier to read
  • However, there are some cases where line breaks will cause problems
  • Line breaks cannot be placed in statements anywhere you cannot have spaces
  • Also, you cannot have line breaks in the middle of quoted strings
  • For instance, the following will cause an error:
    document.write("This is an example
    of how a JavaScript error
    occurs due to incorrect line breaks.");
    
  • If you need to break a long line, you can indicate that the statement continues on the next line by using a backslash (\)
    document.write("This is an example \
    of how a JavaScript error \
    occurs due to incorrect line breaks.");
    
  • The following code shows the error
  • To see the error in Firefox, you will need to open the JavaScript Console from the Tools menu
  • To see the error in IE, you first need to install and enable the Script Debugger tool

Example File with a JavaScript Error

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>JavaScript Error Demonstration</title>
    <script type="text/javascript">
      document.write("This is an example
      of how a JavaScript error
      occurs due to incorrect line breaks.");
  </script>
  </head>

  <body>
    <h1>JavaScript Error Demonstration</h1>
    <p>This page has an error in the JavaScript.</p>
  </body>
</html>
See the example

4.2.3: Supporting Non-JavaScript Browsers

  • For browsers that do not support scripts, or have client-side scripts disabled, you can specify alternative content using the noscript element
  • The syntax is:
    <noscript>
        alternative content
    </noscript>
    
  • For example:
1
2
3
4
5
6
7
8
<script type="text/javascript">
    document.write("Hello world");
</script>
<noscript>
    <p>This page requires JavaScript. Please turn on
    JavaScript if your browser supports it and reload
    the page.</p>
</noscript>

4.2.4: Supporting JavaScript in XHTML

  • Using JavaScript in XHTML can cause problems
  • The issue is that XHTML parsers try to parse the symbols in JavaScript
  • Since JavaScript often contains symbols such as angle brackets (< >) and the ampersand (&), a validator may reject the page
  • To avoid this, you can place your JavaScript code in a CDATA section

CDATA Section

  • CDATA marks text as data that should not be processed by XHTML parsers
  • The syntax is:
    <script type="text/javascript">
    <![cdata[
          JavaScript code
    ]]>
    </script>
    
  • Unfortunately, CDATA is not well supported by all browsers
  • A better solution is to place your JavaScript code in a separate file
  • We will look at how to do this later in the lesson

4.2.5: Summary

  • In this section, we looked at how to place JavaScript directly in an HTML (or XHTML) file
  • To add JavaScript, you use the script element
  • The syntax is:
    <script type="text/javascript">
        script commands and comments
    </script>
    
  • JavaScript commands are known as statements
  • Most JavaScript statements end in a semicolon (;)
  • To send output to a browser, you can use the statement: document.write()
  • We noted a few JavaScript rules during this section:
    1. JavaScript is case sensitive
    2. JavaScript ignores most occurrences of extra white space
  • We also covered the exceptions to the white space rule
  • In addition, we covered how to support JavaScript when the browser does not support scripting
    • Either because the browser is really old
    • Or, more likely, because scripting is disabled
  • Finally, we discussed adding JavaScript to XHTML using CDATA

Check Yourself

  1. What element do you use to add JavaScript to HTML code?
  2. What is a statement? A command?
  3. What is an object?
  4. What is a method?
  5. What JavaScript would you use to write the text "Public Library" as an h1 heading?
  6. What JavaScript would you use to write the following tag?
    <h2 id="sub">Public Library</h2>
  7. How do you enter a single JavaScript statement on two lines?

Activity 4.2

In this activity we write text to a web page using JavaScript.

Specifications

  1. Save the following files to a convenient place on your computer like the Desktop:
  2. Complete the instructions in Figure 1-9 on page JVS 10 of your textbook.
  3. If you have difficulty, please ask a classmate or your instructor for help.

4.3: Working with Variables and Data Types

Learner Outcomes

At the end of the lesson the student will be able to:

  • Declare a variable and assign it a value
  • Reference a variable in a JavaScript statement
  • Describe the different data types supported by JavaScript

4.3.1: Introduction to Variables

  • A variable is the name of a location in a computer's memory
  • In this location you can store numbers and text strings
  • However, you can only store one value in each variable
  • Values stored in a variable can change (vary) as the program runs

Variable as a Container

  • You can think of a variable as a container like a CD jewel case
  • Each case can hold only one CD at a time
  • You can label the case with a name like: mystuff
  • You can put CD's in a case and take them out again
  • You can reuse the case many times
CD Jewel Case

4.3.2: Declaring Variables

  • When you declare a variable, you tell the computer to reserve memory space
  • The syntax for declaring a variable:
    var variableName;
  • You can declare more than one variable at a time by separating the names with a comma
  • For example:
    var emLink, userName, emServer;
  • Note that JavaScript does not require you to declare a variable before use
  • However, it is considered good programming practice

Naming a Variable

  • A variable name is a sequence of letters, numbers, or underscore characters
  • However, JavaScript has some limitations on variable names
  • Specifically, the first character must be either a letter or an underscore character ( _ )
    • Cannot be a number
  • Also, the variable name cannot be one of JavaScripts reserved words (keywords)
  • For a list of reserved words, see: Reserved words in JavaScript
  • Note that you cannot have spaces in a variable name
  • A space is NOT a letter, number or underscore character

Check Yourself

Which of the following are valid variable names?

  1. var myHello2;
  2. var 2myHello;
  3. var My_HeLlO;
  4. var my hello;
  5. var a_very_long_variable_name_that_is_hard_to_read;
  6. var hel-lo;

4.3.3: Assigning a Value to a Variable

  • To assign a value to a variable you use an equal (=) sign
  • The syntax is:
    variableName = value;
  • For example:
    var userName = "eparrish";
  • You can combine a variable declaration and assignment into a single statement
    var userName = "eparrish", emServer = "yahoo.com";
    
  • Note the way that an assignment statement works
  • The right-hand side of the equals sign is always assigned to the variable on the left-hand side
  • You cannot reverse the sides

4.3.4: Writing a Variable Value to a Web Document

  • You can use a variable in place of the value it contains
  • For instance, to write a text string to a web page:
    var libName = "Monroe Public Library";
    document.write(libName);
    
  • You might assign a value to a variable like this because you want to use it in several places on your page
  • By using the libName variable, you will not accidentally misspell "Monroe Public Library" somewhere in the page

Combining Text Strings

  • JavaScript lets you combine a variable with a text string using the plus (+) sign
  • For example:
    var libName = "Monroe Public Library";
    document.write("<p>Welcome to the " + libName + "</p>)";
    
  • JavaScript also lets you combine multiple text variables and strings using a plus (+) sign
  • For example:
    var userName = "eparrish";
    var emServer = "nowhere.com";
    var emLink = userName + "@" + emServer;
    document.write(emLink);
    

4.3.5: JavaScript Data Types

  • Data type: the type of information stored in a variable
  • JavaScript variables can store four different types of information:
    • Numeric values: any number, such as 13, 22.5, or -3.14159
    • Text strings: any group of text characters, such as "Hello"
    • Boolean values: either true or false
    • Null values: a value has not yet been assigned to the variable (null)
  • A JavaScript variable's data type always depends on how it is used
  • Programmers refer to JavaScript as a weakly-typed language
  • This is because variables are not strictly tied to specific data types
  • For example, the following sequence is valid in JavaScript:
    month = 5;
    month = "March";
    
  • Some other languages, in contrast, are strongly typed
    • For instance, Java and C++ are strongly typed
  • Strongly-typed languages force a programmer to explicitly identify a variable's data type

Why Does Strong and Weak Typing Matter?

  • Why are some languages strongly typed and others weakly typed?
  • Weakly-typed languages are convenient because they save you the trouble of deciding on and typing a data type
  • However, this convenience can lead to unpredictable results if you are not careful
  • For example, in JavaScript the plus symbol (+) has two purposes
  • When used with two numbers, it adds them together
  • For example:
    var sum = 2 + 3;
    document.write(sum);
    
  • When used with a string, it combines two text strings into one string
  • For example:
    var fullName = "Ed " + "Parrish";
    document.write(fullName);
    
  • What happens if you combine a number and a string together?
  • For instance:
    var x = 5;
    var y = "4";
    var z = x + y;
    document.write(z);
    
  • The rule that JavaScript follows is that combining numbers and text always produces text
  • What happens is not always readily apparent from reading the code
  • In future lessons, we will look at how to manipulate text and numeric properties of variables
  • For now, you just need to know about the different types

4.3.6: Summary

  • In this section, we learned how to create and use variables
  • A variable is a location in the computer's memory where you can store a single value
  • To declare a variable, you use the syntax:
    var variableName;
  • You make up a name for each variable following the naming rules of JavaScript
  • To assign a value to a variable, you use the syntax:
    variableName = value;
  • You can write the value of a variable to a web page using document.write()
  • For example:
    var libName = "Monroe Public Library";
    document.write("<p>Welcome to the " + libName + "</p>);
    
  • As shown in this example, you can combine variables and text strings using a plus (+) sign
  • We also discussed data types and how JavaScript deals with them

Check Yourself

  1. How do you store data in a program?
  2. What are the four data types supported by JavaScript?
  3. What code do you use to declare a variable named weekDay and assign it a value of "Friday"?

Activity 4.3

Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.

Quick Quiz

  1. JavaScript requires you to declare variables before you use them.

    True
    False

  2. By setting the variable named "name" to true, you have declared the variable type to be a type.
  3. Which of the variable declarations below passes a text value to the variable text1?
    1. text1 var = 'Hello World'
    2. text1 = "Hello World"
    3. var text 1 = "Hello World"
    4. text 1 = 'hello world'

4.4: Creating Functions

Learner Outcomes

At the end of the lesson the student will be able to:

  • Create and call a JavaScript function
  • Return values from functions

4.4.1: About Functions

  • Recall the case study from the textbook
Staff directory
  • Using variables, we might use code like the following to display an email address:
    var userName = "cadler";
    var emServer = "mpl.gov";
    var emLink = userName + "@" + emServer;
    document.write("<a href='mailto" + emLink + "'>");
    document.write(emLink);
    document.write("</a>");
    
  • This code displays one email address
  • What would we need to do to display two email address?
  • We would end up with code like this:
    var userName = "cadler";
    var emServer = "mpl.gov";
    var emLink = userName + "@" + emServer;
    document.write("<a href='mailto" + emLink + "'>");
    document.write(emLink);
    document.write("</a>");
    
    // HTML code here
    
    var userName = "mikeli";
    var emServer = "mpl.gov";
    var emLink = userName + "@" + emServer;
    document.write("<a href='mailto" + emLink + "'>");
    document.write(emLink);
    document.write("</a>");
    
  • Do you notice any similarities in the code for displaying the first and second email addresses?
  • It would be nice if there was a way to display the email addresses without creating longs lists of duplicate code
  • You can do this in JavaScript by using a function

4.4.2: Defining a Function

  • A function is a collection of commands that perform an action or return a value
  • Once you define a function, you can execute the commands by using the function's name

Function Syntax

  • The syntax for defining a function is:
    function functionName(parameters) {
        JavaScript commands
    }
    
  • Where the functionName is a name that the programmer choses and parameters are values passed to the function
  • As an example, we can define a function to display an email address like this:
    function showEm(userName, emServer) {
        var emLink = userName + "@" + emServer;
        document.write("<a href='mailto:" + emLink + "'>");
        document.write(emLink);
        document.write("</a>");
    }
    
  • Notice the various parts of the function:
  • The keyword function starts the definition of every function
  • Following this you define the function's name
    • You follow the same rules making up a name for a function as you do for a variable
  • After the name you must have a set of parentheses
  • Inside the parenthesis you define parameters, if any
    • A parameter is like a variable except it is declared inside the function parentheses
    • Also, a parameter is assigned a value when you use the function
    • Some functions need parameters and some do not
    • You decide on the parameters when you define the function
    • In our example, it made sense to define two parameters
  • After the parenthesis, you define the block of code that you want to execute
  • The block starts with an opening curly brace: {
  • The block ends with a closing curly brace: }
  • Between the curly braces, you list all the commands you want the function to execute

4.4.3: Calling a Function

  • When you define a function, JavaScript ignores the commands at first
  • In order to run the commands, you must call the function
  • The syntax of a function call:
    functionName(parameterValues);
    
  • For instance, to call our example function, you code something like:
    showEm("cadler", "mpl.gov");
  • This function call executes the commands inside the function
  • When JavaScript executes the function call, it copies the values in the parentheses to the function parameters
  • Inside the function, the parameters act like variables
  • The only difference is that function parameters are initialized by a function call
  • When you call a function, you need to supply a value for every parameter defined by the function

Flow of Control for a Function Call

  • To understand how your code works, you need to trace its flow
  • JavaScript code starts executing at the top of a page and works its way downward
  • As mentioned before, JavaScript does not execute the statements in a function right away
  • Instead, you have to call the function
  • When you call the function, the flow jumps to the function and starts executing its commands
  • When the flow reaches the end of the function, the flow returns to where the function was called
  • Then JavaScript continues with the next statement after the function call
  • You can see this in the following diagram

Function Call and Return

Diagram of a function call

4.4.4: Functions and Variable Scope

  • As we have seen, the commands of a function run only when called
  • This has an effect on the way variables within a function are treated
  • Essentially: if a variable is created in a function then it can only be used inside the function
  • Where a variable can be used is known as its scope
  • In JavaScript, a variable's scope can be either local or global
  • Local scope: variable declared within a JavaScript function
  • Global scope: variable not declared within a function

Testing the Effects of Scope

  • Let us take a look at the effect of local and global scope
  • In the following, which variables have local scope and which have global scope?
  • What is output by the web page?
  • What is displayed, if anything, if we uncomment the following two lines in the code?
    //document.write("<br />" + text1 + ", " + text2);
    //document.write("<br />" + text4 + ", " + text3);
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Testing JavaScript</title>
  </head>

  <body>
    <h1>Testing JavaScript</h1>
    <script type="text/javascript">
    var text1 = "Hello World";
    var text4 = "Good night world";

    function callValue(){
        var text2 = "Hello All";
        document.write("<br />" + text1 + ", " + text2);
    }

    function showValue(){
        var text3 = "Good night all!";
        document.write("<br />" + text4 + ", " +text3);
    }

    callValue();
    showValue();
    //document.write("<br />" + text1 + ", " + text2);
    //document.write("<br />" + text4 + ", " + text3);
    </script>
  </body>
</html>

4.4.5: Returning a Value from a Function

  • Sometime you want a function to calculate a value and then return the value
  • For a function to return a value it must include a return statement
  • The syntax for defining a function that returns a value is:
    function functionName(parameters) {
        JavaScript commands that perform the calculation
        return theValue;
    }
    
  • Where the return statement is required and theValue is the value the function returns
  • For example, if we wanted to calculate the area of a rectangle, we could write a function like:
    function areaRectangle(length, width) {
        var area = length * width;
        return area;
    }
    
  • When we call the function, we need to save, or make use of, the value it returns
    var rectLength = 4;
    var rectWidth = 5;
    var rectArea = areaRectangle(rectLength, rectWidth);
    document.write("Area is: " + rectArea);
    
  • If we do not save the returned value, it disappears

4.4.6: Summary

  • In this section we introduced the concept of functions
  • You use functions to reduce the amount of duplicate code in a program
  • Functions are a collection of commands whose purpose is to perform an action or return a value
  • Once you define a function, you can execute the commands by using the function's name
  • The syntax for defining a function is:
    function functionName(parameters) {
        JavaScript commands
    }
    
  • When you define a function, JavaScript ignores the commands at first
  • In order to run the commands, you must call the function
  • The syntax of a function call:
    functionName(parameterValues);
    
  • Since the commands of a function run only when called, this has an effect on the way variables within a function are treated
  • Essentially: if a variable is created in a function then it can only be used inside the function
  • Sometime you want a function to calculate a value and then return the value
  • For a function to return a value it must include a return statement
  • The syntax for defining a function that returns a value is:
    function functionName(parameters) {
        JavaScript commands that perform the calculation
        return theValue;
    }
    

Check Yourself

  1. What are the two purposes of a JavaScript function?
  2. What is the syntax for defining a function?
  3. How does a parameter differ from a variable?
  4. What is the syntax for calling a function?
  5. What are the two variable scopes in JavaScript?
  6. What scope does a variable have when it is declared inside a function?
  7. What keyword do you use to return a value from a function?
  8. When a value is returned from a function, what do you do with the value?

Activity 4.4

In this activity we write text to a web page using functions.

Specifications

  1. If you do not have the following files on you computer, then save them to a convent place like the Desktop:
  2. Complete the instructions in Figure 1-15, 1-16 and 1-17 (pages JVS 22-24) of your textbook.
  3. If you have difficulty, please ask a classmate or your instructor for help.

4.5: Working with JavaScript

Learner Outcomes

At the end of the lesson the student will be able to:

  • Access functions from an external JavaScript file
  • Document code with multi-line and single-line comments
  • Make use of basic techniques for debugging JavaScript code

4.5.1: Accessing an External JavaScript File

  • It is a common practice to create libraries of functions located in external files
  • For instance, here is a library file from the textbook: spam.js
  • We do not really have to understand how a function works to use it
  • All we really need to know is what a function does and how to call it
  • To include the file in a web page, you use the script element
  • In the script element, you include an src attribute with a URL pointing to the file
  • For example, for the spam.js file:
    <script type="text/javascript" src="spam.js"></script>
    
  • Script elements that point to external files are placed in a document's head section
  • Note that the extension ".js" is used by external files containing JavaScript commands and functions
  • For a diagram, see Figure 1-19 of the textbook on page 26

4.5.2: Commenting JavaScript Code

  • Comments are ... comments -- notes to people reading the code
  • Comments are an important programming practice
    • It helps other people understand your code (like the instructor)
    • It may help you in the future when you return to edit a program
  • Comments are ignored by JavaScript so you can put them anywhere in your scripts
  • Comments can start with // and last to end of the line
    // This is a comment
  • Comments can span multiple lines: /* ... */
    /* This is a multi-line comment
          which can be split
       over many lines or a portion of one line. */
    

When to Make Comments

  • Comments should be used sparingly in your code
  • Essentially, there are just three situations in which you should use comments
    1. Unusual or Obscure Code
    2. Function Comment Block
    3. File Comment Block
  • We discuss each of these situations below
  • I expect you to follow these comment guidelines in your homework

Unusual or Obscure Code

  • You should include a comment whenever you do something unusual or obscure in your JavaScript code
  • This will help whomever is reading your code to understand it

Function Comment Block

  • To use a function, you need to know what it does and how to call it
  • To explain what a function does, you write a multi-line (block) comment immediately before the function
  • For instance, before the showEm() function, you could write a comment like:
1
2
3
4
5
6
7
8
9
10
11
12
/**
  This function displays a mailto link for an email
  address.
  @param userName The email user name.
  @param emServer The email server name.
*/
function showEm(userName, emServer) {
    var emLink = userName + "@" + emServer;
    document.write("<a href='mailto:" + emLink + "'>");
    document.write(emLink);
    document.write("</a>");
}
  • The function comment block should start with: /**
  • The parameters descriptions are often placed on a separate line
  • However, you can describe the parameters in the rest of the description if preferred

File Comment Block

  • It is a good practice to include a comment block at the top of every file
  • This block should explain the purpose of the file
  • In addition, the comment block should document who wrote the code and when
  • In HTML, you typically use meta tags for this information
  • However, in a JavaScript file you include this information in a multi-line (block) comment
  • For this course, use the following style of block comments for all your JavaScript (*.js) files:
    /**
      CIS-132 Asn 4
      mylibrary.js
      Purpose: a library of functions for my great web
      application.
    
      @author Ed Parrish
      @version 1.0 7/31/06
    */
    
  • The first few lines describe, the course, assignment, and purpose of the file
  • The @author line is the name of the person who wrote the code
    • You can have multiple @author lines if needed
  • The @version line lets you document the version and when the code was last changed

More information

  • JSDoc: JavaScript documentation tool.

4.5.3: Using Comments to Hide JavaScript Code

  • Older browsers that do not support JavaScript can be a problem
  • Such browsers may display JavaScript code as part of the web page
  • To avoid this problem, you can hide JavaScript in HTML comments
  • The syntax for hiding script is:
    <script type="text/javascript">
    <!-- Hide from non-JavaScript browsers
           JavaScript commands
    // Stop hiding from older browsers -->
    </script>
    
  • Hiding JavaScript is not as important as it once was
  • Therefore, its use for homework in this course is optional

4.5.4: Debugging Your JavaScript Programs

  • As you work with JavaScript, you will inevitably write code that does not work
    • Making programming mistakes is a part of the learning process
    • Even experienced programmers make mistakes
  • Debugging is the process of finding and removing errors is your code
  • To help us understand debugging, we can classify JavaScript errors into three categories:
    • Load-time error: occurs when script is first loaded by the JavaScript interpreter
    • Run-time error: occurs after script has been successfully loaded and is being executed
    • Logical errors: free from syntax and structural mistakes, but result in incorrect results
  • The first two types of errors can be reported by the browser
  • However, each browser displays errors differently

Microsoft Internet Explorer Error Reporting

  • To see the error in Internet Explorer, you first need to install the Script Debugger tool
  • Once you do, you will see a window like the following pop-up whenever IE detects an error
Microsoft debugger window

Firefox, Mozilla and NetScape Error Reporting

  • To see errors in Firefox, Mozilla or NetScape browsers, you open the JavaScript Console window
  • The window will list all the errors the browser detects
  • To see more details about an error, you simply click on its link

Common Mistakes

  • Misspelling a variable name
  • Mismatched parentheses or braces
  • Mismatched quotes
  • Missing quotes
  • See textbook page 35 for more information

Logical Errors

  • The following example from the textbook shows a logical error
  • Logical errors are usually the hardest to detect
  • The browser cannot detect them because there are no syntax errors
Logical error example

Debugging Techniques and Tips

  • It may sound obvious, but the best way to debug is to not write bugs into your code:
    • Check before compiling -- do not "write, run and pray"
    • When you write a section of code, check it over for anything you might have missed
    • Work through it by hand if you are not sure it will work
    • By preventing problems, you will spend much less time fixing bugs
  • Write readable code:
    • Use meaningful and descriptive variable and function names
    • Use indentations and format your code consistently
    • When code is formatted correctly, you can spot errors more easily
  • Test your code often:
    • Do not use "big-bang programming"
    • Write a small section of code and verify it works before writing more
  • Write modular code
    • Break up a program's different tasks into smaller, more manageable chunks
  • Use Alert Dialogs to report on program status and variables
    • Dialog box generated by JavaScript that displays a text message with an OK button
    • For example: alert("OK to here");
    • Another example: alert(emLink);
    • See textbook page 35 for more information

4.5.5: Summary

  • In this section, we looked at some details for working with JavaScript
  • First we looked at how to place JavaScript into an external file
  • To include the external file, you use the script element like this:
    <script type="text/javascript" src="spam.js"></script>
    
  • Also, we looked at using comments in programs
  • Comments are an important programming practice and I expect certain types of comments in your code
  • We also looked at using comments to hide JavaScript from browsers that do not support JavaScript
  • This problem occurs mostly in very old browsers so I will not require you to hide JavaScript in this course
  • Finally, we discussed program bugs and debugging
  • It is important to realize that making programming mistakes is a part of the learning process
  • Even experienced programmers make mistakes
  • However, there are certain practices you should follow to minimize errors and to correct errors that do occur
  • These practices are listed below

Tips for Writing Good JavaScript Code

  • Apply layout techniques to make code more readable
  • Use descriptive variable names
  • Be consistent in how you apply uppercase and lowercase letters to your variable names
  • Add comments to your code
  • Create customized functions
  • Break up long and complicated functions into smaller functions
  • Use the debugging tools available in the browser
  • In case of a logical error, use alert boxes

Check Yourself

  1. What code would you write to display the multi-line comment:

    This function displays the current date in the format month, day, year.

  2. What are the three kinds of JavaScript errors?
  3. How can prevent bugs in your code?
  4. What command would you run to display the value of the userName variable in an alert box?
  5. In your code you misspelled a variable name. What type of error will result from this mistake?

Activity 4.5

Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.

Quick Quiz

  1. The correct syntax for accessing an external JavaScript file named new_file.js is:
    1. <script src="new_file.js"></script>
    2. <script type="text/javascript" src="new_file.js"></script>
    3. <script type="text/javascript" file="new_file.js"></script>
    4. <script src="new_file.js" type="JavaScript"></script>

  2. To create a multi-line comment, enclose the comment with:
    1. <!...!>
    2. /!...!/
    3. /*...*/
    4. <*...*>

  3. can be used to hide JavaScript code from browsers that do not support JavaScript.
  4. To debug a logical error, you can monitor the changing values of your variables using an alert dialog box.

    True
    False

Wrap Up

Due Next:
A4: Using JavaScript (10/2/06)
Discussion 3 and Quiz 3 (10/2/06)

Home | WebCT | Announcements | Schedule | Room Policies | Course Info
Help | FAQ's | HowTo's | Links

Last Updated: March 16 2007 @15:59:20