0% found this document useful (0 votes)
0 views31 pages

Chapter 4 - JavaScript Introduction To Scripting

Chapter 4 introduces JavaScript as a scripting language for enhancing web pages, covering basic scripting elements, the document object, and methods for displaying text. It discusses creating dynamic web pages using prompt dialogs for user input and highlights memory concepts and data types in JavaScript. The chapter also explains arithmetic operations, decision-making with if statements, and the importance of strict equality operators to avoid implicit type conversions.

Uploaded by

Anitha Sakthivel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views31 pages

Chapter 4 - JavaScript Introduction To Scripting

Chapter 4 introduces JavaScript as a scripting language for enhancing web pages, covering basic scripting elements, the document object, and methods for displaying text. It discusses creating dynamic web pages using prompt dialogs for user input and highlights memory concepts and data types in JavaScript. The chapter also explains arithmetic operations, decision-making with if statements, and the importance of strict equality operators to avoid implicit type conversions.

Uploaded by

Anitha Sakthivel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Chapter 4

JavaScript: Introduction to
Scripting

• Internet & World Wide Web


How to Program, 5/e
4.1 Introduction
• JavaScript
 Scripting language which is used to enhance the functionality and
appearance of web pages.
• We begin with a simple script that displays the text "Welcome to
JavaScript Programming!" in the HTML5 document.
• All major web browsers contain JavaScript interpreters, which process
the commands written in JavaScript.
• The JavaScript code and its result are shown in Fig. 6.1.
4.2 Your First Script: Displaying a Line of Text with
JavaScript in a Web Page (cont.)
The script Element and Commenting Your Scripts

• 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
• 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.
• A string of characters can be contained between double quotation
(") marks (also called a string literal)
4.2 Your First Script: Displaying a Line of Text
with JavaScript in a Web Page (cont.)
Using the document Object

• Browser’s document object represents the HTML5 document


currently being displayed in the browser
 Allows 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
• 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
Statements
• 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
• The document object’s writeln method
 Writes a line of HTML5 text in the HTML5 document
4.3 Modifying Your First Script
Displaying a Line of Colored Text

• 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.
• The + operator (called the “concatenation operator” when used in
this manner) joins two strings together
4.3 Modifying Your First Script (Cont.)
Nesting Quotation Marks
string can be delimited by single (') or double (") quote characters.
Line 11 nests single quotes inside a double-quoted string to quote the style
attribute’s value in the h1 element.

Displaying Text in an Alert Dialog


Dialogs
 Useful to display information in windows called dialogs (or dialog
boxes) 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
• The script in Fig. 6.3 displays Welcome to JavaScript
Programming! As three lines in a predefined dialog
called an alert dialog.
Fig. 6.3 | Alert dialog displaying multiple lines.
4.3 Modifying Your First Script (Cont.)
Escape Sequences
When a backslash is encountered in a string of characters, the next character
is combined with the backslash to form an escape sequence. The escape
sequence \n is the newline character. It causes the cursor in the HTML5
document to move to the beginning of the next line.

Fig. 6.4 | Some common escape sequences.


4.4 Obtaining User Input with prompt Dialogs
• 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.
4.4.1 Dynamic Welcome Page
• 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.
• Figure 6.5 presents the script and sample output.
Fig. 6.5 | Prompt box used on a welcome screen.
4.4.1 Dynamic Welcome Page (cont.)
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.

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.
JavaScript is case sensitive—uppercase and lowercase letters are considered to
be different characters, so name, Name and NAME are different identifiers.
JavaScript Comments
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.
Multiline Comments
4.4.1 Dynamic Welcome Page (cont.)
window Object’s prompt Method
• Line 13 is a comment indicating the purpose of the statement in the next
line.
• Line 14 calls the window object’s prompt method, which displays the
dialog in Fig. 6.6.
• The dialog allows the user to enter a string representing the user’s
name.

Fig. 6.6 | Prompt dialog displayed by the window object’s prompt method.
4.4.1 Dynamic Welcome Page (cont.)
• A variable is assigned a value with an assignment statement,
using the assignment operator, =.
• The = operator is called a binary operator, because it has two
operands.

String Concatenation
Lines 16–17 use document.writeln to display the new welcome
message.
The expression inside the parentheses uses the operator + to “add” a
string (the literal "<h1>Hello, "), the variable name (the string that the user
entered in line 14) and another string (the literal ", welcome to JavaScript
programming!</h1>").
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 combined.
4.4.1 Dynamic Welcome Page (cont.)

• 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
4.4.2 Adding Integers

• Our next script illustrates another use of prompt dialogs to obtain


input from the user.
• Figure 6.7 inputs two integers (whole numbers, such as 7, –11, 0
and 31914) typed by a user at the keyboard, computes the sum of
the values and displays the result.
prompt dialog returns to the script as a string the value typed by the
user.

Function parseInt converts its string argument to an integer.

method writeln belongs to the document object and


method prompt belongs to the window object.
4.5 Memory Concepts
• Variable names such as number1, number2 and sum actually correspond to
locations in the computer’s memory. Every variable has a name, a type
and a value.
• When a value is placed in a memory location, the value replaces the
previous value in that location.
• When a value is read out of a memory location, the process is
nondestructive.
Fig. 6.8 | Memory location showing the name and value of variable number1.

Fig. 6.9 | Memory locations after inputting values for variables number1 and number2.

Fig. 6.10 | Memory locations after calculating the sum of number1 and number2.
4.5 Memory Concepts (Cont.)
Data Types in JavaScript
• Unlike its predecessor languages C, C++ and Java, JavaScript does not
require variables to have a declared 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. For this reason, JavaScript is referred to as a loosely typed
language.
• When a variable is declared in JavaScript, but is not given a value, the
variable has an undefined value. Attempting to use the value of such a
variable is normally a logic error.
• When variables are declared, they’re not assigned values unless you specify
them.
• Assigning the value null to a variable indicates that it does not contain a
value.
4.6 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

Fig. 6.11 | Arithmetic operators.


Operator Precedence

Fig. 6.12 | Precedence of arithmetic operators.


4.7 Decision Making: Equality and Relational Operators

 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
• Equality operators both have the same level of precedence,
which is lower than the precedence of the relational operators.
• The equality operators associate from left to right.
Common Programming Error 6.7
Confusing the equality operator, ==, with the assignment operator, =, is a
logic error. The equality operator should be read as “is equal to,” and the
assignment operator should be read as “gets” or “gets the value of.” Some
people prefer to read the equality operator as “double equals” or “equals
equals.”

Fig. 6.13 | Equality and relational operators.


4.7 Decision Making: Equality and Relational Operators (Cont.)
The script in Fig. 6.14 uses four if statements to display a time-sensitive
greeting on a welcome page.

Fig. 6.14 | Using equality and


relational operators.
4.7 Decision Making: Equality and Relational
Operators (Cont.)
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

Good Programming Practice 6.8


Refer to the operator precedence chart when writing expressions containing
many operators.
Be sure to observe that some operators, such as assignment (=), associate
from right to left rather than from left to right.

Fig. 6.15 | Precedence and associativity of the operators


The Strict Equals (===) and Strict Does Not Equal (!==) Operators
JavaScript can convert between types comparing values.
For example, the comparison "75" == 75 yields the value true because
JavaScript converts the string "75" to the number 75 before
performing the equality (==) comparison.
To prevent implicit conversions in comparisons, which can lead to unexpected
results, JavaScript provides the strict equals (===) and strict does not
equal (!==) operators.
The comparison "75" === 75 yields the value false because one operand is
a string and the other is a number.
Similarly, 75" !== 75 yields true because the operand’s types are not equal,
therefore the values are not equal.
If you do not use these operators when comparing values to null, 0, true, false
or the empty string (""), javascriptlint.com’s JavaScript validator displays
warnings of potential implicit conversions.

You might also like