Module 2
Introduction to JavaScript
• The browser interprets the contents of the <head> section first,
so the JavaScript programs we write there execute before the
<body> of the HTML5 document displays.
• Line 9 uses the <script> tag to indicate to the browser that the
text which follows is part of a script. The type attribute
specifies the MIME type of the script as well as the scripting
language used in the script—in this case, a text file written in
javascript. In HTML5, the default MIME type for a <script> is
"text/html", so you can omit the type attribute from your
<script> tags.
• The term object normally implies that attributes (data) and
behaviors (methods) are associated with the object. The
object’s methods use the attributes to perform useful actions for
the client of the object (i.e., the script that calls the
methods). A method may require additional information
(arguments) to perform its actions; this information is
enclosed in parentheses after the name of the method in the
script.
• In lines 11–12, we call the document object’s writeln method
to write a line of HTML5 markup in the HTML5 document.
The parentheses following the method name writeln contain the
one argument that method writeln requires (in this case, the
string of HTML5 that the browser is to display). Method
writeln instructs the browser to write the argument string into
the web page for rendering. If the string contains HTML5
elements, the browser interpretsthese elements and renders
them on the screen.
Statements
• The code elements in lines 11–12, including document.writeln,
its argument in the parentheses (the string) and the semicolon
(;), together are called a statement. Every statement ends
with a semicolon (also known as the statement terminator)—
Displaying a Line of Colored Text
• Line 11 nests single quotes inside a double-quoted
string to quote the style attribute’s value in the h1
element.
Obtaining User Input with prompt Dialogs
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.
Declarations, Keywords and Variables
• Line 11 is a declaration that contains the JavaScript
keyword var. Keywords are words that have special meaning
in JavaScript. The keyword var at the beginning of the
statement indicates that the word name is a variable.
• A variable is a location in the computer’s memory where a
value can be stored for use by a script. All variables have a
name and value, and should be declared with a var statement
before they’re used in a script.
• Declarations end with a semicolon and can be split over
several lines with each variable in the declaration separated by
a comma—known as a comma-separated list of variable
names. Several variables may be declared either in one or in
multiple declarations
Identifiers and Case Sensitivity
• The name of a variable can be any valid identifier. An
identifier is a series of characters consisting of letters,
digits, underscores ( _ ) and dollar signs ($) that does not
begin with a digit and is not a reserved JavaScript
keyword.
• Identifiers may not contain spaces. Some valid identifiers
are Welcome, $value, _value, m_inputField1 and button7.
The name 7button is not a valid identifier, because it
begins with a digit, and the name input field is not valid,
because it contains a space.
• Remember that JavaScript is case sensitive—uppercase
and lowercase letters are considered to be different
characters, so name, Name and NAME are different
identifiers.
JavaScript Comments
• It’s helpful to indicate the purpose of each variable in the
script by placing a JavaScript comment at the end of each
line in the declaration. In line 11, a single-line comment
that begins with the characters // states the purpose of the
variable in the script. This form of comment is called a
single-line comment because it terminates at the end of
the line in which it appears.
• A // comment can begin at any position in a line of
JavaScript code and continues until 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
• You can also write multiline comments. For example,
/* This is a multiline
comment. It can be
split over many lines. */
Window object’s prompt method
• The argument to prompt specifies a message telling the
user what to type in the text field. This message is called
a prompt because it directs the user to take a specific
action.
Assignment Operator
• The statement in line 14 assigns the value returned by the window
object’s prompt method (a string containing the characters typed by
the user—or the default value or null if the Cancel button is clicked)
to variable name by using the assignment operator, =.
• The statement is read as, “name gets the value returned by
window.prompt("Please enter your name").” The =operator is
called a binary operator because it has two operands—name
and the result of the expression window.prompt("Please enter
your name"). This entire statement is called an assignment
because it assigns a value to a variable. The expression to the
right of the assignment operator is always evaluated first.
Arithmetic
Control statement
JavaScript has only eight control statements: sequence, three types of selection
and four types of repetition. A script is formed by combining control
statements as necessary to implement the script’s algorithm.
if Selection Statement
• A selection statement is used to choose among alternative
courses of action in a script. For example, suppose that the
passing grade on an examination is 60 (out of 100). Then the
pseudocode statement.
If student’s grade is greater than or equal to 60
Print “Passed”
• The preceding pseudocode If statement can be written in
JavaScript as
if ( studentGrade >= 60 )
document.writeln( "<p>Passed</p>" );
if…else Selection Statement
The if…else selection statement allow you to specify that a
different action is to be performed when the condition is true than
when the condition is false.
If student’s grade is greater than or equal to 60
Print “Passed”
Else
Print “Failed”
• The preceding pseudocode If…Else statement may be written
in JavaScript as
if ( studentGrade >= 60 )
document.writeln( "<p>Passed</p>" );
else
document.writeln( "<p>Failed</p>" );
Conditional Operator (?:)
• JavaScript provides an operator, called the conditional
operator (?:), that’s closely related to the if…else statement.
The operator ?: is JavaScript’s only ternary operator—it
takes three operands. The operands together with the ?: form
a conditional expression. The first
• operand is a boolean expression, the second is the value for the
conditional expression if the expression evaluates to true and
the third is the value for the conditional expression if the
expression evaluates to false. For example, the following
statement
document.writeln( studentGrade >= 60 ? "Passed" :
"Failed" );
Nested if...else Statements
• For example, the following pseudocode statement indicates
that the script should print A for exam grades greater than or
equal to 90, B for grades in the range 80 to 89, C for grades in
the range 70 to 79, D for grades in the range 60 to 69 and F for
all other grades:
Blocks
• The if selection statement expects only one statement in its
body. To include several statements in an if statement’s body,
enclose the statements in braces ({ and }).
• This also can be done in the else section of an if…else
statement. A set of statements contained within a pair of braces
is called a block
if ( grade >= 60 )
document.writeln( "<p>Passed</p>" );
else
{
document.writeln( "<p>Failed</p>" );
document.writeln( "<p>You must take this course
again.</p>" );
}
while Repetition Statement
• A repetition structure (also known as a loop) allows you to
specify that a script is to repeat an action while some
condition remains true.
• The pseudocode statement While there are more items on my
shopping list Purchase next item and cross it off my list
• As an example of a while statement, consider a script segment
designed to find the first power of 2 larger than 1000. Variable
product begins with the value 2. The statement is as follows:
Assignment Operators
• JavaScript provides several additional assignment operators
(called compound assignment operators) for abbreviating
assignment expressions. For example, the statement
c = c + 3;
can be abbreviated with the addition assignment operator,
+= as
c += 3;
Essentials of Counter-Controlled Repetition
• Counter-controlled repetition requires:
1. The name of a control variable (or loop counter).
2. The initial value of the control variable.
3. The increment (or decrement) by which the control
variable is modified each time through the loop (also
known as each iteration of the loop).
4. The condition that tests for the final value of the
control variable to determine whether looping should
continue.
For Repetition statement
Examples using the for statements
Switch Multiple-Selection Statement
• Previously, we discussed the if single-selection
statement and the if…else doubleselection statement.
Occasionally, an algorithm will contain a series of
decisions in which a variable or expression is tested
separately for each of the values it may assume, and
different actions are taken for each value. JavaScript
provides the switch multiple-selection statement to
handle such decision making.
do…while Repetition Statement
• The do…while repetition statement is similar to the while
statement.
• In the while statement, the loop-continuation test occurs at
the beginning of the loop, before the body of the loop executes.
• The do…while statement tests the loop-continuation condition
after the loop body executes—therefore, the loop body always
executes at least once.
BREAK STATEMENT
CONTINUE STATEMENT
• The continue statement, when executed in a while, for or do…while
statement, 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. Improper placement of continue before
the increment in a while may result in an infinite loop.
• Figure 8.12 uses continue in a for statement to skip line 19 if line 16
determines that the value of count is 5.
• When the continue statement executes, the script skips the
remainder of the for statement’s body (line 19). Program control
continues with the increment of the for statement’s control variable
(line 14), followed by the loop-continuation test to determine
whether the loop should continue executing.
LOGICAL OPERATORS
• JavaScript provides logical operators that can be used to
form more complex conditions by combining simple
conditions. The logical operators are && (logical AND), ||
(logical OR) and ! (logical NOT, also called logical
negation).
&& (Logical AND) Operator
• Suppose that, at some point in a program, we wish to ensure
that two conditions are both true before we choose a certain
path of execution. In this case, we can use the logical &&
operator, as follows:
if ( gender == 1 && age >= 65 )
++seniorFemales;
• The preceding combined condition can be made more readable
by adding redundant parentheses:
( gender == 1 ) && ( age >= 65 )
Functions
• 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 collections of data called arrays. These make
your job easier, because they provide many of the capabilities
you’ll frequently need.
• You can write functions to define tasks that may be used at
many points in a script. These are referred to as programmer-
defined functions.
• A function is invoked (that is, made to perform its
designated task) by a function call.
• The function call specifies the function name and provides
information (as arguments) that the called function needs to
perform its task. A common analogy for this structure is the
hierarchical form of management.
• A boss (the calling function, or caller) asks a worker (the
called function) to perform a task and return (i.e., report
back) the results when the task is done. The boss function
does not know how the worker function performs its
designated tasks. The worker may call other worker
functions—the boss will be unaware of this. We’ll soon see
how this hiding of implementation details promotes good
software engineering.
Recursion vs. Iteration
• Both iteration and recursion are based on a control statement:
Iteration uses a repetition statement (e.g., for, while or
do…while); recursion uses a selection statement (e.g., if,
if…else or switch).
• Both iteration and recursion involve repetition: Iteration
explicitly uses a repetition statement; recursion achieves
repetition through repeated function calls.
• Iteration and recursion each involve a termination test:
Iteration terminates when the loop-continuation condition
fails; recursion terminates when a base case is recognized.
• Iteration both with counter-controlled repetition and with
recursion gradually approaches termination: Iteration
keeps modifying a counter until the counter assumes a
value that makes the loop-continuation condition fail;
recursion keeps producing simpler versions of the original
problem until the base case is reached.
• Both iteration and recursion can occur infinitely: An
infinite loop occurs with iteration if the loop-continuation
test never becomes false; infinite recursion occurs if the
recursion step does not reduce the problem each time via
a sequence that converges on the base case or if the base
case is incorrect.
ARRAYS
• JavaScript arrays are “dynamic” entities in that they can
change size after they’re created.
• An array is a group of memory locations that all have the same
name and normally are of the same type (although this
attribute is not required in JavaScript). To refer to a particular
location or element in the array, we specify the name of the
array and the position number of the particular element in the
array.
• The position number in square brackets is called an index and
must be an integer or an integer expression
Declaring and Allocating Arrays
• Arrays occupy space in memory. Actually, an array in
JavaScript is an Array object. You use the new operator to
create an array and to specify the number of elements in
an array.
• The new operator creates an object as the script executes by
obtaining enough memory to store an object of the type
specified to the right of new. To allocate 12 elements for
integer array c, use a new expression like:
var c = new Array( 12 );
The preceding statement can also be performed in two steps, as
follows:
var c; // declares a variable that will hold the array
c = new Array( 12 ); // allocates the array