Download as pdf or txt
Download as pdf or txt
You are on page 1of 66

CS495 Design of Web-based

Applications

Chapters 6 to 12
JavaScript: Introduction to Scripting
Internet & World Wide Web How to Program, 5/e
Chapter Objective
Chapter Objectives
Introduction
• JavaScript
• Scripting language which is used to enhance the functionality and
appearance of web pages.
• Before you can run code examples with JavaScript on your computer,
you may need to change your browser’s security settings.
• IE9 prevents scripts on the local computer from running by default
• Firefox, Chrome, Opera, Safari (including on the iPhone) and the
Android browser have JavaScript enabled by default.
• All major web browsers contain JavaScript interpreters, which
process the commands written in JavaScript.
Basic Example
Basic Example
• Often, JavaScripts appear in the <head> section of the HTML5 document
• The browser interprets the contents of the <head> section first

• The <script> tag indicates to the browser that the text that follows is part
of a script. Attribute type specifies the scripting language used in the
script—such as text/javascript

• Browser’s document object represents the HTML5 document currently


being displayed in the browser
• Allows a you to specify HTML5 text to be displayed in the HTML5
document
• Browser contains a complete set of objects that allow script programmers
to access and manipulate every element of an HTML5 document.
JavaScript Basics
• Object
• Resides in the computer’s memory and contains information used by the
script
• The term object normally implies that attributes (data) and behaviors
(methods) are associated with the object
• An object’s methods use the attributes’ data to perform useful actions for
the client of the object—the script that calls the methods
• The parentheses following the name of a method contain the arguments
that the method requires to perform its task (or its action)
• Every statement should end with a semicolon (also known as the
statement terminator), although none is required by JavaScript
• JavaScript is case sensitive – not using the proper uppercase and
lowercase letters is a syntax error
JavaScript Basics
• The document object’s writeln method writes a line of HTML5 text in
the HTML5 document.
• Does not guarantee that a corresponding line of text will appear in
the HTML5 document.
• Text displayed is dependent on the contents of the string written,
which is subsequently rendered by the browser.
• Browser will interpret the HTML5 elements as it normally does to
render the final text in the document
JavaScript Basics
• JavaScript code is typically placed in a separate file, then included in
the HTML5 document that uses the script.
• This makes the code more reusable, because it can be included into
any HTML5 document—as is the case with the many JavaScript
libraries used in professional web development today.
• A script can display Welcome to JavaScript Programming! in many
ways.
• Figure 6.2 displays the text in magenta, using the CSS color
property.
• Method write displays a string like writeln, but does not position the
output cursor in the HTML5 document at the beginning of the next
line after writing its argument
JavaScript Basics

concatenation
Dialogs
• Useful to display information in windows that “pop up” on the screen
to grab the user’s attention
• Typically used to display important messages to the user browsing
the web page
• Browser’s window object uses method alert to display an alert dialog
• Method alert requires as its argument the string to be displayed
Dialogs

Escape
sequence
Scripting
• Scripting
• Gives you the ability to generate part or all of a web page’s content at
the time it is shown to the user
• Such web pages are said to be dynamic, as opposed to static, since
their content has the ability to change
• The next script creates a dynamic welcome page that obtains the
user’s name, then displays it on the page.
• The script uses another predefined dialog box from the window
object—a prompt dialog—which allows the user to enter a value that
the script can use.
Scripting
Scripting
Keywords
• Keywords are words with special meaning in JavaScript
• Keyword var is used to declare the names of variables
• All variables have a name, type and value, and should be declared
with a var statement before they are used in a script
• A variable name can be any valid identifier consisting of letters,
digits, underscores ( _ ) and dollar signs ($) that does not begin with
a digit and is not a reserved JavaScript keyword.
• Several variables may be declared in one declaration or in multiple
declarations.
Keywords
Comments
• A single-line comment begins with the characters // and terminates
at the end of the line
• Comments do not cause the browser to perform any action when the
script is interpreted; rather, comments are ignored by the JavaScript
interpreter
• Multiline comments begin with delimiter /* and end with delimiter */
 All text between the delimiters of the comment is ignored by the
interpreter.
Window
• The window object’s prompt method displays a dialog into which the
user can type a value.
 The first argument is a message (called a prompt) that directs the user to
take a specific action.
 The optional second argument is the default string to display in the text
field.

• Script can then use the value that the user inputs.
JavaScript Basics
• null keyword signifies that a variable has no value
• null is not a string literal, but rather a predefined term indicating
the absence of value
• Writing a null value to the document, however, displays the word
“null”
• Function parseInt converts its string argument to an integer
• JavaScript has a version of the + operator for string concatenation
that enables a string and a value of another data type (including
another string) to be concatenated
Adding Integers
Variables
• JavaScript does not require variables to have a type before they can be
used in a script
• A variable in JavaScript can contain a value of any data type, and in many
situations, JavaScript automatically converts between values of different
types for you
• JavaScript is referred to as a loosely typed language
• When a variable is declared in JavaScript, but is not given a value, it has
an undefined value.
• Attempting to use the value of such a variable is normally a logic error.
• When variables are declared, they are not assigned default values, unless
specified otherwise by the programmer.
• To indicate that a variable does not contain a value, you can assign the
value null to it.
Arithmetic
• The basic arithmetic operators (+, -, *, /, and %) are binary operators,
because they each operate on two operands
• JavaScript provides the remainder operator, %, which yields the
remainder after division
• Arithmetic expressions in JavaScript must be written in straight-line
form to facilitate entering programs into the computer
Control Statements
• Sequential execution
 Execute statements in the order they appear in the code
• Transfer of control
 Changing the order in which statements execute
• All scripts can be written in terms of only three control
statements
 Sequence
 Selection (if-else, switch-case)
 Repetition (loops)
Selection Statement – if … else
• if statement allows a script to make a decision based on the truth or
falsity of a condition
• If the condition is met (i.e., the condition is true), the statement in
the body of the if statement is executed
• If the condition is not met (i.e., the condition is false), the statement
in the body of the if statement is not executed
• Conditions in if statements can be formed by using the equality
operators and relational operators
Decision Making
Date Object
• Used acquire the current local time
• Create a new instance of an object by using the new operator
followed by the type of the object, Date, and a pair of parentheses
• Example:
var today = new Date( );
var hours = today.getHours( );
var month = today.getMonth( );
Selection Statement
• Conditional operator (?:)
• Closely related to the if…else statement
• JavaScript’s only ternary operator—it takes three operands
• The operands together with the ?: operator form a conditional
expression
 The first operand is a boolean expression
 The second is the value for the conditional expression if the
boolean expression evaluates to true
 Third is the value for the conditional expression if the boolean
expression evaluates to false
Selection Statement - switch
• switch multiple-selection statement
• Tests a variable or expression separately for each of the values it
may assume
• Different actions are taken for each value
• Consists of a series of case labels and an optional default case
• When control reaches a switch statement the script evaluates the
controlling expression in the parentheses
• Compares this value with the value in each of the case labels
• If the comparison evaluates to true, the statements after the case
label are executed in order until a break statement is reached
Selection Statement - switch
• The break statement is used as the last statement in each case to
exit the switch statement immediately
• The default case allows you to specify a set of statements to execute
if no other case is satisfied
 Usually, the last case in the switch statement

• Each case can have multiple actions (statements)


• Braces are not required around multiple actions in a case of a switch
• The break statement is not required for the last case because
program control automatically continues with the next statement
after the switch
• Having several case labels listed together (e.g., case 1: case 2: with no
statements between the cases) executes the same set of actions for
each case
Repetition Statement - while
• Allows you to specify that an action is to be repeated while some
condition remains true
• The body of a loop may be a single statement or a block
• Eventually, the condition becomes false and repetition terminates
Assignment Operators
Increment and Decrement
Precedence of Operators
Repetition Statement - for
• Specifies each of the items needed for counter-controlled repetition
with a control variable
• Can use a block to put multiple statements into the body
• for statement header contains three expressions
 Initialization
 Condition
 Increment Expression

• The increment expression in the for statement acts like a stand-alone


statement at the end of the body of the for statement
• Place only expressions involving the control variable in the
initialization and increment sections of a for statement
Repetition Statement - for
• The three expressions in the for statement are optional
• The two semicolons in the for statement are required
• The initialization, loop-continuation condition and increment
portions of a for statement can contain arithmetic expressions
• The “increment” of a for statement may be negative, in which case it
is called a decrement and the loop actually counts downward
• If the loop-continuation condition initially is false, the body of the for
statement is not performed
 Execution proceeds with the statement following the for statement
Repetition Statement – do …
while
• Tests the loop-continuation condition after the loop body executes
• The loop body always executes at least once
Break and Continue in loops
• break statement in a while, for, do…while or switch statement
 Causes immediate exit from the statement
 Execution continues with the next statement in sequence
 break statement common uses
 Escape early from a loop
 Skip the remainder of a switch statement

• continue statement in a while, for or do…while


 skips the remaining statements in the body of the statement
and proceeds with the next iteration of the loop
 In while and do…while statements, the loop-continuation test
evaluates immediately after the continue statement executes
 In for statements, the increment expression executes, then the
loop-continuation test evaluates
JavaScript Functions
• You’ll combine new functions that you write with prepackaged
functions and objects available in JavaScript
• The prepackaged functions that belong to JavaScript objects are
called methods.
• JavaScript provides several objects that have a rich collection of
methods for performing common mathematical calculations, string
manipulations, date and time manipulations, and manipulations of
arrays.
• You can define programmer-defined functions that perform specific
tasks and use them at many points in a script.
JavaScript Functions
• The format of a function definition is
function function-name( parameter-list )
{
declarations and statements
}
JavaScript Functions
• You can use a Javascript defined function in your programmer-
defined function.
User Interactions and Event
Handling
• The JavaScript executes in response to the user’s interaction with an
element in a form. This interaction causes an event.

• Scripts are often used to respond to user-initiated events – GUI Event


Handling.

• The user interacts with an element in the web page, the script is notified
of the event and the script processes the event.

• The function that’s called when an event occurs is known as an event


handler.

• When a GUI event occurs in a form, the browser calls the specified event-
handling function.
• Before any event can be processed, each element must know which event-
handling function will be called when a particular event occurs.
Rolling Dice Example
Rolling Dice Example
Scope Rules
• Each identifier in a program has a scope
• The scope of an identifier for a variable or function is the portion of
the program in which the identifier can be referenced
• Global variables or script-level variables are accessible in any part of
a script and are said to have global scope
 Thus every function in the script can potentially use the variables

• Identifiers declared inside a function have function (or local) scope


and can be used only in that function
JavaScrip
t Global
functions
JavaScript Arrays
• “dynamic” entities that can change size after they are created
• Every array in JavaScript knows its own length, which it stores in its
length attribute and can be found with the expression
arrayname.length
• JavaScript arrays are Array objects.
• You use the new operator to create an array and to specify the
number of elements in an array.
• Zero-based counting is usually used to iterate through arrays
• JavaScript reallocates an Array when a value is assigned to an
element that is outside the bounds of the original Array
• Arrays can be created using a comma-separated initializer list
enclosed in square brackets ([ ])
JavaScript Arrays
JavaScript Arrays

To link from HTML: <script src=“InitArray.js”></script>


JavaScript Arrays
• You can loop through the elements of an Array using for loop or for-
in loop.
 For (var element in ArrayName) { … }

• Pass an array as an argument to a function


• Specify the array’s name (a reference to the array) without brackets
• Although entire arrays are passed by reference, individual numeric
and boolean array elements are passed by value exactly as simple
numeric and boolean variables are passed
JavaScript Array Methods
JavaScript Objects
Math Object
• Math object methods enable you to conveniently perform
many common mathematical calculations.
Math Object
Math Object
String Object
• A string is a series of characters treated as a single unit
• A string may include letters, digits and various special characters,
such as +, -, *, /, and $
• JavaScript supports Unicode, which represents a large portion of the
world’s languages
• String literals or string constants are written as a sequence of
characters in double or single quotation marks
String Object
String Object
String Object
Date Object
• Date object provides methods for date and time manipulations
• Based either on the computer’s local time zone or on World Time
Standard’s Coordinated Universal Time (abbreviated UTC)
• Most methods have a local time zone and a UTC version
• The Date constructor with no arguments initializes the Date object
with the local computer’s current date and time
• A new Date object can be initialized by passing the number of
milliseconds since midnight, January 1, 1970, to the Date constructor
• Can also create a new Date object by supplying arguments to the
Date constructor for year, month, date, hours, minutes, seconds and
milliseconds
Date Object
Date Object
Boolean and Number Objects
• The Boolean and Number objects are object wrappers for boolean
true/false values and numbers, respectively
• When a boolean value is required in a JavaScript program,
JavaScript automatically creates a Boolean object to store the value
Boolean and Number Objects
• JavaScript automatically
creates Number objects to
store numeric values in a
script
• Although you can
explicitly create Number
objects, normally they are
created when needed by
the JavaScript interpreter
Document Object
• Provided by the browser and allows JavaScript code to manipulate
the current document in the browser
Questions?

You might also like