Module 5
Module 5
<html>
<body>
<script language = "javascript" type =
"text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
1|Page
Applications of Javascript Programming
As mentioned earlier, Javascript is one of the most widely used programming languages both
for Front-end and Back-end. It is used in almost every area of software development. These
include:
Client-side validation: use in front-end to verify user input before submitting it to the server.
Manipulating HTML Pages - helps in manipulating HTML page. Thus, modifying any
HTML tag is very easy to make it looks nice based on different devices and requirements.
User Notifications - use to give different types of notifications to website visitors using
dynamic pop-ups.
Back-end Data Loading - provides Ajax library to assist in loading back-end data while doing
some other processing in parallel. These are amazing website visitors.
Presentations - provides the facility for creating presentations using RevealJS and BespokeJS
libraries to build a web-based slide presentation.
Server Applications - building fast and scalable network applications with Node JS on
Chrome's Javascript runtime which is an event-based library helping in developing very
sophisticated server applications including Web Servers.
Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script is included in or
referenced by an HTML document for the code to be interpreted by the browser. This means
that the web page dynamic, which can include programs that interact with the user, control the
browser, and dynamically create HTML content.
The client-side mechanism provides advantages over traditional server-side scripts. For
example, JavaScript can be used to check if the user has entered a valid e-mail address in a
form field or not. The JavaScript code is executed when the user submits the form. This will in
turn be submitted to the Web Server only if all the entries are valid. JavaScript can be used to
trap user-initiated events such as button clicks, link navigation, and other actions that the user
initiates explicitly or implicitly.
Advantages of JavaScript
The merits of using JavaScript are −
i.) Less server interaction − validates user input before sending the page off to the server,
thus, saves server traffic, which means less load on your server.
ii.) Immediate feedback to the visitors – visitors to the web page need not wait for a page
reload to see if there is a problem or not.
iii.) Increased interactivity − creates interfaces that respond when the user hovers over with
a mouse or activates via the keyboard.
iv.) Richer interfaces − include such items as drag-and-drop components and sliders to give
a Rich Interface to web page visitors.
2|Page
Limitations of JavaScript
It lacks the following −
i.) Client-side JavaScript does not allow the reading or writing of files for security reasons.
ii.) No support for networking applications
iii.) No multithreading or multiprocessor capabilities.
JavaScript Development Tools
JavaScript does not require expensive development tools. With a simple text editor such as
Notepad JavaScript can be developed. No need for a compiler since it is an interpreted language
inside the context of a web browser.
Some of the JavaScript editing tools are −
i.) Microsoft FrontPage – developed by Microsoft with HTML editor providing web
developers with several JavaScript tools to assist in the creation of interactive websites.
ii.) Macromedia Dreamweaver MX – is a popular HTML and JavaScript editor in the
professional web development arena. It provides several JavaScript components,
integrates with databases, and conforms to the standards such as XHTML and XML.
iii.) Macromedia HomeSite 5 − a well-liked HTML and JavaScript editor from Macromedia
that can be used to manage personal websites effectively.
JavaScript syntax
JavaScript can be implemented using JavaScript statements that are placed within the
<script>... </script> HTML tags in a web page. The <script> tags containing your JavaScript
can be placed anywhere within the web page, but it is normally recommended to be kept within
the <head> tags. The <script> tag alerts the browser program to start interpreting all the text
between these tags as a script. A simple syntax of JavaScript appears as follows.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes −
Language − This attribute specifies what scripting language is to be used. Typically, its value
is javascript. Although recent versions of HTML (and XHTML, its successor) have phased out
the use of this attribute.
Type − This attribute is now recommended to indicate the scripting language in use and its
value is set to "text/javascript".
Whitespace and Line Breaks
3|Page
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. Use spaces,
tabs, and newlines freely in programs and format and indent programs neatly and consistently
makes the code easy to read and understand.
Semicolons are Optional
Simple statements in JavaScript are generally followed by a semicolon character, just as they
are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your
statements is placed on a separate line. For example, the following code could be written
without semicolons.
Case Sensitivity
JavaScript is a case-sensitive programming language interpreter. This means that the language
keywords, variables, function names, and any other identifiers must always be typed with a
consistent capitalization of letters. So, the identifiers Time and TIME will convey different
meanings in JavaScript.
NOTE − Care should be taken while writing variable and function names in JavaScript.
Comments in JavaScript
There are three ways to give comments in JavaScript
The use of double forward-slash (//): Any text between a double forward-slash (//) and the end
of a line is treated as a comment and is ignored by JavaScript.
Us of single forward slash and asterisk characters: Any text between the characters /* and */ is
treated as a comment for multiple lines comments.
The use of a combination of less than, greater than sign, exclamation, and double dash:
JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this
as a single-line comment, just as it does the // comment. The HTML comment closing
recognized by JavaScript is written as //-->.
Enabling JavaScript
All the modern browsers come with built-in support for JavaScript. The following browsers
support enabling and disabling JavaScript. These are Internet Explorer, Firefox, Chrome, and
Opera.
JavaScript in Internet Explorer
Steps to turn on or turn off JavaScript in Internet Explorer −
Click Internet Options from the menu.
Select the Security tab from the dialog box.
Click the Custom Level button.
Scroll down to the Scripting option.
Select Enable radio button under Active scripting.
Finally, click OK.
4|Page
Similarly, to disable follow the same step except that disable button is chosen in this case.
JavaScript in Firefox
Steps to turn on or turn off JavaScript in Firefox −
Open a new tab
type about config in the address bar.
A warning dialog appears.
Select I’ll be careful, I promise!
A list of configure options in the browser appears.
In the search bar, type javascript.enabled.
Right-clicking on the value of the option to enable or disable javascript
Select toggle.
If javascript.enabled is true; it converts to false upon clicking the toggle. If javascript is
disabled; it gets enabled upon clicking the toggle.
JavaScript in Chrome
Steps to turn on or turn off JavaScript in Chrome.
Click the Chrome menu at the top right-hand corner of your browser.
Select Settings.
Click Show advanced settings at the end of the page.
Under the Privacy section, click the Content settings button.
In the "Javascript" section, select "Do not allow any site to run JavaScript" or "Allow all sites
to run JavaScript (recommended)".
JavaScript in Opera
Steps to turn on or turn off JavaScript in Opera.
Select Tools, Preferences from the menu.
Select the Advanced option from the dialog box.
Select Content from the listed items.
Select Enable JavaScript checkbox.
Click OK.
To disable JavaScript support in Opera, select the DisEnable JavaScript checkbox.
5|Page
There is flexibility to include JavaScript code anywhere in an HTML document. However, the
most preferred ways to include JavaScript in an HTML file are as follows −
Now let us consider how to place JavaScript in an HTML file in different ways.
JavaScript in <head>...</head> section
To have a script run on some event, such as when a user clicks somewhere, then place the script
in the head section.
6|Page
Strings of text e.g. "This is CSC336 " etc.
Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a
single value. In addition to these primitive data types, JavaScript supports a composite data
type known as an object.
Note − JavaScript does not make a distinction between integer values and floating-point values.
All numbers in JavaScript are represented as floating-point values. JavaScript represents
numbers using the 64-bit floating-point format defined by the IEEE 754 standard.
Variables
Like many other programming languages, JavaScript has variables. Variables can be thought
of as named containers. You can place data into these containers and then refer to the data
simply by naming the container. Before using a variable in a JavaScript program, it must be
first declared. Variables are declared with the var keyword as follows.
Storing a value in a variable is called variable initialization. You can do variable initialization
at the time of variable creation or at a later point in time when you need that variable.
For instance, you might create a variable named money and assign the value 1060.50 to it later.
For another variable, you can assign a value at the time of initialization as follows.
Note − Use the var keyword only for declaration or initialization, once for the life of any
variable name in a document. You should not re-declare the same variable twice.
JavaScript is an untyped language. This means that a JavaScript variable can hold a value of
any data type. Unlike many other languages, you don't have to tell JavaScript during variable
declaration what type of value the variable will hold. The value type of a variable can change
during the execution of a program and JavaScript takes care of it automatically.
Variable Scope
The scope of a variable is the region of your program in which it is defined. JavaScript variables
have only two scopes.
Global Variables − A global variable has a global scope which means it can be defined
anywhere in your JavaScript code.
Local Variables − A local variable will be visible only within a function where it is defined.
Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the
same name. If a local variable is declared or a function parameter with the same name as a
global variable, the global variable is effectively hidden.
Variable Names
While naming variables in JavaScript, keep the following rules in mind.
You should not use any of the JavaScript reserved keywords as a variable name. For example,
break or boolean variable names are not valid.
7|Page
JavaScript variable names should not start with a numeral (0-9). They must begin with a letter
or an underscore character. For example, 10try is an invalid variable name but _123test is a
valid one.
JavaScript variable names are case-sensitive. For example, Name and name are two different
variables.
Reserved or Key Words
These are words that cannot be used as JavaScript variables, functions, methods, loop labels,
or any object names.
Operators
Operators are javascript words that act on operands associated with them. JavaScript supports
the following types of operators.
i.) Arithmetic Operators
ii.) Comparison Operators
iii.) Logical (or Relational) Operators
iv.) Assignment Operators
v.) Conditional (or ternary) Operators
Let us have a look at all operators one by one.
Arithmetic Operators
These are operators to perform arithmetic operations. JavaScript supports the following
arithmetic operators −
Assume variable A holds 1 and variable B holds 2, then −
SNo. Operator Description Example
1 + (Addition) Adds two operands A + B will give 3
2 - (Subtraction) Subtracts the second operand A - B will give -1
from the first
3 * (Multiplication) Multiply both operands A * B will give 2
4 / (Division) Divide the numerator by the B / A will give 2
denominator
5 % (Modulus) Outputs the remainder of an B % A will give 0
integer division
6 ++ (Increment) Increases an integer value by A++ will give 2
one
7 -- (Decrement) Decreases an integer value by Ex: A-- will give 0
one
Note: it worth note that the Addition operator (+) works for Numeric as well as Strings
variables. For example, "A" + 1 will give "A1". This called concatenation of string.
Comparison Operators
The comparison operator is used to compare two operands. JavaScript supports the following
comparison operators:
Assume variable A holds 1 and variable B holds 2, then −
8|Page
Sr.No. Operator Description Example
1 = = (Equal) Checks if the value of two operands is equal (A == B) is not true.
or not, if yes, then the condition becomes
true.
2 != (Not Equal) Checks if the value of two operands are (A != B) is true.
equal or not, if the values are not equal, then
the condition becomes true.
3 > (Greater Checks if the value of the left operand is (A > B) is not true.
than) greater than the value of the right operand,
if yes, then the condition becomes true.
4 < (Less than) Checks if the value of the left operand is less (A < B) is true.
than the value of the right operand, if yes,
then the condition becomes true.
5 >= (Greater Checks if the value of the left operand is (A >= B) is not true.
than or Equal greater than or equal to the value of the right
to) operand, if yes, then the condition becomes
true.
6 <= (Less than Checks if the value of the left operand is less (A <= B) is true.
or Equal to) than or equal to the value of the right
operand, if yes, then the condition becomes
true.
Logical Operators
The logical operators perform a logical operation on logical expression. JavaScript supports
the following logical operators:
Assume variable A holds 1 and variable B holds 2, then
SNo. Operator Description Example
1 && (Logical AND) If both the operands are non- (A && B) is true.
zero, then the condition
becomes true.
2 || (Logical OR) If any of the two operands (A || B) is true.
are non-zero, then the
condition becomes true.
3 ! (Logical NOT) Reverses the logical state of ! (A && B) is false.
its operand. If a condition is
true, then the Logical NOT
operator will make it false.
9|Page
Bitwise Operators
These operate on each bit of its operands. JavaScript supports the following bitwise operators:
Assume variable A holds 2 and variable B holds 3, then:
SNo. Operator Description Example
1 & (Bitwise AND) It performs a Boolean AND (A & B) is 2.
operation on each bit of its integer
arguments.
2 | (BitWise OR) It performs a Boolean OR operation (A | B) is 3.
on each bit of its integer arguments.
Assignment Operators
JavaScript supports the following assignment operators −
SNo. Operator Description Example
1 = (Simple Assigns values from the right side Ex: C = A + B
Assignment ) operand to the left side operand will assign the
value of A + B
into C
2 += (Add and It adds the right operand to the left Ex: C += A is
Assignment) operand and assigns the result to the equivalent to C =
left operand. C+A
10 | P a g e
3 −= (Subtract and It subtracts the right operand from Ex: C -= A is
Assignment) the left operand and assigns the equivalent to C =
result to the left operand. C-A
4 *= (Multiply and It multiplies the right operand with Ex: C *= A is
Assignment) the left operand and assigns the equivalent to C =
result to the left operand. C*A
5 /= (Divide and It divides the left operand with the Ex: C /= A is
Assignment) right operand and assigns the result equivalent to C =
to the left operand. C/A
6 %= (Modules and It takes modulus using two operands Ex: C %= A is
Assignment) and assigns the result to the left equivalent to C =
operand. C%A
11 | P a g e
if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.
if...else statement Syntax
if (expression)
{
Statement(s) to be executed if the expression is true
}
else
{
Statement(s) to be executed if the expression is false
}
In this case, JavaScript expression is evaluated. If the resulting value is true, the given
statement(s) in the ‘if’ block, are executed. If the expression is false, then the given statement(s)
in the else block is executed.
if...else if... statement
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a
correct decision out of several conditions.
if...else if... statement Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1)
{
Statement(s) to be executed if expression 1 is true
}
else if (expression 2)
{
Statement(s) to be executed if expression 2 is true
} else if (expression 3)
{
Statement(s) to be executed if expression 3 is true
}
else
12 | P a g e
{
Statement(s) to be executed if no expression is true
}
This is just a series of if statements, where each if is a part of the else clause of the previous
statement. Statement(s) is executed based on the true condition, if none of the conditions is
true, then the else block is executed.
JavaScript – Switch Case
One can use multiple if...else…if statements, as discussed in the previous section, to perform
a multiway branch. However, this is not always the best solution, especially when all of the
branches depend on the value of a single variable.
Starting with JavaScript 1.2, switch statement is used to handles exactly this situation, and it
does so more efficiently than repeated if...else if statements.
Switch case Syntax
The objective of a switch statement is to give an expression to evaluate and several different
statements to execute based on the value of the expression. The interpreter checks each case
against the value of the expression until a match is found. If nothing matches, a default
condition will be used.
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the interpreter
would continue executing each statement in each of the following cases. Break statements play
a major role in switch-case statements.
Loops
While writing a program, it may be required to perform some actions over and over again. In
such situations, you would need to write loop statements to reduce the number of lines of code.
13 | P a g e
JavaScript supports all the necessary loops to ease down the pressure of programming.
JavaScript - While Loops
The while Loop
The most basic loop in JavaScript is the while loop. The purpose of a while loop is to execute
a statement or code block repeatedly as long as an expression is true. Once the expression
becomes false, the loop terminates.
While loop Syntax
The syntax of while loop in JavaScript is as follows:
while (expression)
{
Statement(s) to be executed if the expression is true
}
The do...while Loop
The do...while loop is similar to the while loop except that the condition check happens at the
end of the loop. This means that the loop will always be executed at least once, even if the
condition is false.
Do…While Loop Syntax
The syntax for the do-while loop in JavaScript is as follows −
do
{
Statement(s) to be executed;
} while (expression);
14 | P a g e
For Loop Syntax
The syntax of for loop in JavaScript is as follows:
for (initialization; test condition; iteration statement)
{
Statement(s) to be executed if the test condition is true
}
JavaScript for...in the loop
The for...in the loop is used to loop through an object's properties.
for..in’ loop Syntax
The syntax of ‘for..in’ loop is:
for (variablename in object)
{
statement or block to execute
}
In each iteration, one property from the object is assigned to variablename and this loop
continues till all the properties of the object are exhausted.
JavaScript - Loop Control
JavaScript provides full control to handle loops and switch statements. There may be a situation
when you need to come out of a loop without reaching its end. There may also be a situation
when you want to skip a part of your code block and start the next iteration of the loop.
To handle all such situations, JavaScript provides break and continue statements. These
statements are used to immediately come out of any loop or to start the next iteration of any
loop respectively.
The break Statement
The break statement, which was briefly introduced with the switch statement, is used to exit a
loop early, breaking out of the enclosing curly braces.
The continue Statement
The continue statement tells the interpreter to immediately start the next iteration of the loop
and skip the remaining code block. When a continue statement is encountered, the program
flow moves to the loop check expression immediately and if the condition remains true, then it
starts the next iteration, otherwise, the control comes out of the loop.
15 | P a g e
JavaScript - Functions
A function is a group of reusable code which can be called anywhere in the program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big program into several small and
manageable functions. Like any other advanced programming language, JavaScript also
supports all the features necessary to write modular code using functions.
JavaScript allows users to write their functions as well. This section explains how to write user-
defined functions in JavaScript.
Function Definition
Before using a function, it needs to be defined. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.
Syntax
The basic syntax is:
<script type = "text/javascript">
<!--
function functionname(parameter-list)
{
statements
}
//-->
</script>
Calling a Function
To invoke a function somewhere later in the script, simply write the name of the function with
the required parameter list in the order of in which they are listed in the function definition.
Function Parameters
Javascript has the facility to pass different parameters while calling a function. These passed
parameters can be captured inside the function and any manipulation can be done over those
parameters. A function can take multiple parameters separated by a comma.
The return Statement
A JavaScript function can have an optional return statement. This is required if you want to
return a value from a function. This statement should be the last in a function.
16 | P a g e
JavaScript - Events
What is an Event?
Events occur when the user or the browser manipulates a page and the JavaScript's interaction
with HTML handled such manipulation. For example, when the page loads, when the user
clicks a button, pressing any key, closing a window, resizing a window, etc. these are called
events.
Developers can use these events to execute JavaScript-coded responses, which cause buttons
to close windows, messages to be displayed to users, data to be validated, and virtually any
other type of response imaginable.
onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left button of
his mouse. You can put your validation, warning, etc., against this event type.
onsubmit Event Type
onsubmit is an event that occurs when a user tries to submit a form. You can put your form
validation against this event type.
onmouseover and onmouseout
These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and the
onmouseout triggers when you move your mouse out from that element. Try the following
example.
JavaScript and Cookies
What are Cookies?
Web Browsers and Servers use the HTTP protocol to communicate and HTTP is a stateless
protocol. But for a commercial website, it is required to maintain session information among
different pages. For example, a user registration ends after completing many pages, but need
to maintain users' session information across all the web pages. In such situations, using
cookies is the most efficient method of remembering and tracking preferences, purchases,
commissions, and other information required for a better visitor experience or site statistics.
Server sends some data to the visitor's browser in the form of a cookie. The browser accepts
the cookie and then stores it as a plain text record on the visitor's hard drive. When the visitor
arrives at another page, the browser sends the same cookie to the server for retrieval. Once
retrieved, server knows/remembers what was stored earlier.
Cookies has 5 variable-length fields describe as follows
Expires − The date the cookie will expire. If this is blank, the cookie will expire when the
visitor quits the browser.
Domain − The domain name of your site.
17 | P a g e
Path − The path to the directory or web page that sets the cookie. This may be blank if you
want to retrieve the cookie from any directory or page.
Secure − If this field contains the word "secure", then the cookie may only be retrieved with a
secure server. If this field is blank, no such restriction exists.
Name=Value − Cookies are set and retrieved in the form of key-value pairs
The data contained in a cookie is automatically transmitted between the web browser and the
web server, the server CGI scripts can then read and write cookie values that are stored on the
client. JavaScript can also manipulate cookies using the cookie property of the Document
object. JavaScript can read, create, modify, and delete the cookies that apply to the current web
page.
Storing Cookies
The simplest way to create a cookie is to assign a string value to the document.cookie object,
which looks like this.
document.cookie = "key1 = value1;key2 = value2;expires = date";
The expires attribute is optional. If it is provided with a valid date or time, then the cookie will
expire on a given date or time and thereafter, the cookies' value will not be accessible.
Reading Cookies
Reading a cookie is just as simple as writing it. The value of the document.cookie object is the
cookie. Thus, use this string to access the cookie. The document.cookie string will keep a list
of name=value pairs separated by semicolons, where name is the name of a cookie and value
is its string value.
Setting Cookies Expiry Date
You can extend the life of a cookie beyond the current browser session by setting an expiration
date and saving the expiry date within the cookie. This can be done by setting the ‘expires’
attribute to a date and time.
Deleting a Cookie
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie
return nothing. To do this, you just need to set the expiry date to a time in the past.
JavaScript - Dialog Boxes
JavaScript supports three important types of dialog boxes. These dialog boxes can be used to
raise an alert, or get confirmation on any input or have a kind of input from the users.
Alert Dialog Box
An alert dialog box is mostly used to give a warning message to the users. For example, if one
input field requires entering some text but the user does not provide any input, then as a part of
the validation, you can use an alert box to give a warning message. Nonetheless, an alert box
can still be used for friendlier messages. The alert box gives only one button "OK" to select
and proceed.
18 | P a g e
Confirmation Dialog Box
A confirmation dialog box is mostly used to take the user's consent on any option. It displays
a dialog box with two buttons: OK and Cancel. If the user clicks on the OK button, the window
method confirms () will return true. If the user clicks on the Cancel button, then confirm()
returns false.
Prompt Dialog Box
The prompt dialog box is very useful when you want to pop up a text box to get user input.
Thus, it enables you to interact with the user. The user needs to fill in the field and then click
OK. This dialog box is displayed using a method called prompt() which takes two parameters:
(i) a label that you want to display in the text box and (ii) a default string to display in the text
box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window
method prompt() will return the entered value from the text box. If the user clicks the Cancel
button, the window method prompt() returns null.
JavaScript - Void Keyword
void is an important keyword in JavaScript that can be used as a unary operator that appears
before its single operand, which may be of any type. This operator specifies an expression to
be evaluated without returning a value.
19 | P a g e