WT Unit 3 Notes
WT Unit 3 Notes
JavaScript
Although it contains the word Java, JavaScript and Java are vastly different programming
languages with different uses. Java is a full-fledged compiled, objectoriented language, popular
for its ability to run on any platform with a Java Virtual Machine installed. Conversely,
JavaScript is one of the world’s most popular languages, with fewer of the object-oriented
features of Java, and runs directly inside the browser, without the need for the JVM.
JavaScript is dynamically typed (also called weakly typed) in that variables can be easily (or
implicitly) converted from one data type to another.
The disadvantages of client-side scripting are mostly related to how programmers use JavaScript
in their applications. Some of these include:
■ There is no guarantee that the client has JavaScript enabled, meaning any required
functionality must be housed on the server, despite the possibility that it could be offloaded.
■ The idiosyncrasies between various browsers and operating systems make it difficult to test for
all potential client configurations. What works in one browser, may generate an error in another.
■ JavaScript-heavy web applications can be complicated to debug and maintain. JavaScript has
often been used through inline HTML hooks that are embedded into the HTML of a web page.
Although this technique has been used for years, it has the distinct disadvantage of blending
HTML and JavaScript together, which decreases code readability, and increases the difficulty of
web development.
3
6.1.2 JavaScript’s History and Uses
JavaScript was introduced by Netscape in their Navigator browser back in 1996. It originally was
called Live Script, but was renamed partly because one of its original purposes was to provide a
measure of control within the browser over Java applets.
JavaScript is in fact an implementation of a standardized scripting language called ECMAScript.
Internet Explorer (IE) at first did not support JavaScript, but instead had its own browser-based
scripting language (VBScript). While IE now does support JavaScript, Microsoft sometimes
refers to it as JScript, primarily for trademark reasons (Oracle currently owns the trademark for
JavaScript). It wasn’t until the middle of the 2000s with the emergence of so-called AJAX sites
that JavaScript became a much more important part of web development. AJAX is both an
acronym as well as a general term. As an acronym it means Asynchronous JavaScript and XML,
which was accurate for some time; but since XML is no longer always the data format for data
transport in AJAX sites, the acronym meaning is becoming less and less accurate. As a general
term, AJAX refers to a style of website development that makes use of JavaScript to create more
responsive user experiences. The most important way that this responsiveness is created is via
asynchronous data requests via JavaScript and the XML HttpRequest object. This addition to
JavaScript was introduced by Microsoft as an ActiveX control (the IE version of plug-ins) in
1999, but it wasn’t until sophisticated websites by Google (such as Gmail and Maps) and Flickr
demonstrated what was possible using these techniques that the term AJAX became popular.
The most important feature of AJAX sites is the asynchronous data requests. You will eventually
learn how to program these asynchronous data requests in Chapter 15. For now, however, we
should say a few words about how asynchronous requests are different from the normal HTTP
request-response loop. You might want to remind yourself about how the “normal” HTTP
request response loop looks. Figure 6.4 illustrates the processing flow for a page that requires
updates based on user input using the normal synchronous non-AJAX page request-response
loop.
As you can see in Figure 6.4, such interaction requires multiple requests to the server, which not
only slows the user experience, it puts the server under extra load, especially if, as the case in
Figure 6.4, each request is invoking a server-side script.
But as can be seen in Figure 6.5, when these multiple requests are being made across the Internet
to a busy server, then the time costs of the normal HTTP request response loop will be more
visually noticeable to the user. AJAX provides web authors with a way to avoid the visual and
temporal deficiencies of normal HTTP interactions. With AJAX web pages, it is possible to
update sections of a page by making special requests of the server in the background, creating
the illusion of continuity. Figure 6.6 illustrates how the interaction shown in Figure 6.4 would
differ in an AJAX-enhanced web page.
6.2 JavaScript Design Principles
As mentioned earlier, JavaScript does have a bad reputation for being a difficult language to use.
Although frameworks and developer tools can help, there is some truth to this reputation.
It should be said, however, that this reputation is based not so much on the language itself but in
how developers have tended to use it. JavaScript has often been used through inline HTML
hooks—that is, embedded into the HTML of a web page. Although this technique has been used
for years, it has the distinct disadvantage of blending HTML and JavaScript together, which
decreases code readability, and increases the difficulty of web development.
6.2.1 Layers
When designing software to solve a problem, it is often helpful to abstract the solution a little bit
to help build a cognitive model in your mind that you can then implement. Perhaps the most
common way of articulating such a cognitive model is via the term layer. In object-oriented
programming, a software layer is a way of conceptually grouping programming classes that have
similar functionality and dependencies. Common software design layer names include:
■ Presentation layer. Classes focused on the user interface.
■ Business layer. Classes that model real-world entities, such as customers, products, and sales.
■ Data layer. Classes that handle the interaction with the data sources.
Presentation Layer
This type of programming focuses on the display of information. JavaScript can alter the HTML
of a page, which results in a change, visible to the user. These presentation layer applications
include common things like creating, hiding, and showing divs, using tabs to show multiple
views, or having arrows to page through result sets. This layer is most closely related to the user
experience and the most visible to the end user.
Validation Layer
JavaScript can be also used to validate logical aspects of the user’s experience. This could
include, for example, validating a form to make sure the email entered is valid before sending it
along. It is often used in conjunction with the presentation layer to create a coherent user
experience, where a message to the presentation layer highlights bad fields. Both layers exist on
the client machine, although the intention is to prevalidate forms before making transmissions
back to the server.
Asynchronous Layers
Normally, JavaScript operates in a synchronous manner where a request sent to the server
requires a response before the next lines of code can be executed. During the wait between
request and response the browser sits in a loading state and only updates upon receiving the
response. In contrast, an asynchronous layer can route requests to the server in the background.
In this model, as certain events are triggered, the JavaScript sends the HTTP requests to the
server, but while waiting for the response, the rest of the application functions normally, and the
browser isn’t in a loading state. When the response arrives JavaScript will (perhaps) update a
portion of the page. Asynchronous layers are considered advanced versions of the presentation
and validation layers above.
<script type="text/javascript">
/* A JavaScript Comment */
alert ("Hello World!");
</script>
listing 6.2 Embedded JavaScript example
You may recall that in Chapter 3 on CSS you were warned that inline CSS is in general a bad
practice and should be avoided. The same is true with JavaScript. In fact, inline JavaScript is
much worse than inline CSS. Inline JavaScript is a real maintenance nightmare, requiring
maintainers to scan through almost every line of HTML looking for your inline JavaScript.
6.3.2 Embedded JavaScript
Embedded JavaScript refers to the practice of placing JavaScript code within a <script> element
as shown in Listing 6.2. Like its equivalent in CSS, embedded JavaScript is okay for quick
testing and for learning scenarios, but is frowned upon for normal real world pages. Like with
inline JavaScript, embedded scripts can be difficult to maintain.
<head>
<script type="text/JavaScript" src="greeting.js">
</script>
</head>
listing 6.3 External JavaScript example
6.4 Syntax
Since it’s a lightweight scripting language, JavaScript has some features (such as dynamic
typing) that are especially helpful to the novice programmer. However, a novice programmer
faces challenges when he or she tries to use JavaScript in the same way as a full object-oriented
language such as Java, as JavaScript’s object features (such as prototypes and inline functions)
are quite unlike those of more familiar languages.
We will briefly cover the fundamental syntax for the most common programming constructs
including variables, assignment, conditionals, loops, and arrays before moving on to advanced
topics such as events and classes.
JavaScript’s reputation for being quirky not only stems from its strange way of implementing
object-oriented principles, but also from some odd syntactic gotchas that every JavaScript
developer will eventually encounter, some of which include:
■ Everything is type sensitive, including function, class, and variable names.
■ The scope of variables in blocks is not supported. This means variables declared inside a loop
may be accessible outside of the loop, counter to what one would expect.
■ There is a === operator, which tests not only for equality but type equivalence.
■ Null and undefined are two distinctly different states for a variable.
■ Semicolons are not required, but are permitted (and encouraged).
■ There is no integer type, only number, which means floating-point rounding errors are
prevalent even with values intended to be integers.
var x;
var y = 0;
y = 4;
a variable x is defined
y is defined and initialized to 0
y is assigned the value of 4
Figure 6.13 Variable declaration and assignment
6.4.1 Variables
Variables in JavaScript are dynamically typed, meaning a variable can be an integer, and then
later a string, then later an object, if so desired. This simplifies variable declarations, so that we
do not require the familiar type fields like int, char, and String. Instead, to declare a variable x,
we use the var keyword, the name, and a semicolon as shown in Figure 6.13. If we specify no
value, then (being typeless) the default value is undefined. Assignment can happen at
declaration-time by appending the value to the declaration, or at run time with a simple right-to-
left assignment as illustrated in Figure 6.13. This syntax should be familiar to those who have
programmed in languages like C and Java. In addition, the conditional assignment operator,
shown in Figure 6.14, can also be used to assign based on condition, although its use is
sometimes discouraged.
Optional else if statements can follow, with an else ending the branch. Listing 6.4
uses a conditional to set a greeting variable, depending on the hour of the day.
6.4.5 Loops
Like conditionals, loops use the ( ) and { } blocks to define the condition and the
body of the loop.
While Loops
The most basic loop is the while loop, which loops until the condition is not met.
Loops normally initialize a loop control variable before the loop, use it in the condition,
and modify it within the loop. One must be sure that the variables that make
up the condition are updated inside the loop (or elsewhere) to avoid an infinite loop!
var i=0;
while(i < 10){
//do something with i
i++;
}
For Loops
A for loop combines the common components of a loop: initialization, condition,
and post-loop operation into one statement. This statement begins with the for
keyword and has the components placed between ( ) brackets, semicolon (;) separated
as shown in Figure 6.15.
for (var i = 0; i < 10; i++){
//do something with i
}
Figure 6.15 For loop
6.4.6 Functions
Functions are the building block for modular code in JavaScript, and are even used
to build pseudo-classes, which you will learn about later. They are defined by using
the reserved word function and then the function name and (optional) parameters.
Since JavaScript is dynamically typed, functions do not require a return type, nor do
the parameters require type. Therefore a function to raise x to the yth power might
be defined as:
function power(x,y){
var pow=1;
for (var i=0;i<y;i++){
pow = pow*x;
}
return pow;
}
And called as
power(2,10);
With new programmers there is often confusion between defining a function
and calling the function. Remember that when actually using the keyword function,
we are defining what the function does. Later, we can use or call that function by
using its given name without the function keyword.
Later in this chapter you will see the advanced use of functions to build classes.
Alert
The alert() function makes the browser show a pop-up to the user, with whatever
is passed being the message displayed. The following JavaScript code displays a
simple hello world message in a pop-up:
alert ( "Good Morning" );
The className property is normally a better choice, because it allows the styles
to be created outside the code, and thus be better accessible to designers. Using this
model we would change the background color by having two styles defined, and
changing them in JavaScript code.
var commentTag = document.getElementById("specificTag");
commentTag.className = "someClassName";
HTML5 introduces the classList element, which allows you to add, remove,
or toggle a CSS class on an element. You could add a class with
label.classList.addClass("someClassName");
The approach shown in Listing 6.10 is widely supported by all browsers. The
first line in the listing creates a temporary variable for the HTML element that will
trigger the event. The next line attaches the <div> element’s onclick event to the
event handler, which invokes the JavaScript alert() method (and thus annoys the
user with a pop-up hello message). The main advantage of this approach is that this
code can be written anywhere, including an external file that helps uncouple the
HTML from the JavaScript. However, the one limitation with this approach (and
the inline approach) is that only one handler can respond to any given element
event.
The examples in Listing 6.10 and Listing 6.11 simply used the built-in JavaScript
alert() function. What if we wanted to do something more elaborate when an
event is triggered? In such a case, the behavior would have to be encapsulated within
a function, as shown in Listing 6.12.
function displayTheDate() {
var d = new Date();
alert ("You clicked this on "+ d.toString());
}
var element = document.getElementById('example1');
element.onclick = displayTheDate;
// or using the other approach
element.addEventListener('click',displayTheDate);
listing 6.12 Listening to an event with a function
function submitButtonClicked(e) {
if (e.cancelable){
e. preventDefault();
}
}
listing 6.14 A sample event handler function that prevents the default event
These events are most useful within input fields. We could for example validate
an email address, or send an asynchronous request for a dropdown list of suggestions
with each key press.
<input type="text" id="keyExample">
The input box above, for example, could be listened to and each key pressed
echoed back to the user as an alert as shown in Listing 6.15.
listing 6.15 Listener that hears and alerts keypresses
document.getElementById("keyExample").onkeydown = function
myFunction(e){
var keyPressed=e.keyCode; //get the raw key code
var character=String.fromCharCode(keyPressed); //convert to string
alert("Key " + character + " was pressed");
}
Form Events
Forms are the main means by which user input is collected and transmitted to the
server. Table 6.9 lists the different form events.
The events triggered by forms allow us to do some timely processing in response
to user input. The most common JavaScript listener for forms is the onsubmit event.
document.getElementById("loginForm").onsubmit = function(e){
var pass = document.getElementById("pw").value;
if(pass==""){
alert ("enter a password");
e.preventDefault();
}
}
listing 6.16 Catching the onsubmit event and validating a password to not be blank
Frame Events
Frame events (see Table 6.10) are the events related to the browser frame that contains
your web page. The most important event is the onload event, which tells us
an object is loaded and therefore ready to work with. In fact, every nontrivial event
listener you write requires that the HTML be fully loaded.
However, a problem can occur if the JavaScript tries to reference a particular
<div> in the HTML page that has not yet been loaded. If the code attempts to set
up a listener on this not-yet-loaded <div>, then an error will be triggered. For this
reason it is common practice to use the window.onload event to trigger the execution
of the rest of the page’s scripts.
window.onload= function(){
//all JavaScript initialization here.
}
6.8 Forms
Chapter 4 covered the HTML for data entry forms. In that chapter it was mentioned
that user form input should be validated on both the client side and the
server side.
To illustrate some form-related JavaScript concepts, consider the simple HTML
form depicted in Listing 6.17.
6.8.1 Validating Forms
Form validation is one of the most common applications of JavaScript. Writing code
to prevalidate forms on the client side will reduce the number of incorrect submissions,
thereby reducing server load. Although validation must still happen on the
server side (in case JavaScript was circumvented), JavaScript prevalidation is a best
practice. There are a number of common validation activities including email validation,
number validation, and data validation.
Some additional things to consider are fields like checkboxes, whose value is
always set to “on”. If you want to ensure a checkbox is ticked, use code like that
below.
var inputField=document.getElementByID("license");
if (inputField.type=="checkbox"){
if (inputField.checked)
//Now we know the box is checked, otherwise it isn’t
}
Number Validation
Number validation can take many forms. You might be asking users for their age
for example, and then allow them to type it rather than select it. Unfortunately, no
simple functions exist for number validation like one might expect from a fullfledged
library. Using parseInt(), isNAN(), and isFinite(), you can write your
own number validation function.