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

Web Programming(20CSI43) Module-2

Nagarjuna College of Engineering and Technology,


Bengaluru
Autonomous College Under VTU
Department of CSE (Data Science)

WEB PROGRAMMING (IC)


20CSI43

MODULE 2

JavaScript

. By
Prof. Likhith S R
Assistant. Professor
Dept. of CSE(DS), NCET

Dept. of CSE(Data Science), NCET 1 2021-22


Web Programming(20CSI43) Module-2

Module - II
JavaScript: Introduction, Scripts and HTML Document, JS Output Statements, Variables,
Data Types and Conversions, Operators, Expressions, Control Structure, Decisions Loops,
and Functions, Document Object Model, Forms and Form Handling Elements, Scripting,
Event Handling, Regular Expressions, WEB SQL database

What is JavaScript
• JavaScript (js) is a light-weight object-oriented programming language which is used
by several websites for scripting the webpages.
• It is an interpreted, full-fledged programming language that enables dynamic
interactivity on websites when applied to an HTML document. It was introduced in
the year 1995 for adding programs to the webpages in the Netscape Navigator
browser.
• Since then, it has been adopted by all other graphical web browsers. With JavaScript,
users can build modern web applications to interact directly without reloading the
page every time.
• The traditional website uses js to provide several forms of interactivity and
simplicity.
Features of JavaScript
There are following features of JavaScript:
• All popular web browsers support JavaScript as they provide built-in execution
environments.
• JavaScript follows the syntax and structure of the C programming language. Thus, it
is a structured programming language.
• JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
• JavaScript is an object-oriented programming language that uses prototypes rather
than using classes for inheritance.
• It is a light-weighted and interpreted language.
• It is a case-sensitive language.
• JavaScript is supportable in several operating systems including, Windows, macOS,
etc.
• It provides good control to the users over the web browsers.

Dept. of CSE(Data Science), NCET 2 2021-22


Web Programming(20CSI43) Module-2

Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
• Client-side validation,
• Dynamic drop-down menus,
• Displaying date and time,
• Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm
dialog box and prompt dialog box),
• Displaying clocks etc.

Scripts and HTML Document


The HTML <script> Tag
• The HTML <script> tag is used to define a client-side script (JavaScript).
• The <script> element either contains script statements, or it points to an external
script file through the src attribute.
• Common uses for JavaScript are image manipulation, form validation, and dynamic
changes of content.
• In html, java script code must be inserted b/w <script></script> tag
JavaScript Can Change HTML Content
 One of many JavaScript HTML methods is getElementById().
 This example uses the method to "find" an HTML element (with id="demo") and
changes the element content (innerHTML) to "Hello JavaScript":

document.getElementById("demo").innerHTML = "Hello JavaScript";

JavaScript Can Change HTML Styles (CSS)


 Changing the style of an HTML element, is a variant of changing an HTML
attribute:
document.getElementById("demo").style.fontSize = "35px";

JavaScript Can Hide HTML Elements


 Hiding HTML elements can be done by changing the display style:
document.getElementById("demo").style.display = "none";

Dept. of CSE(Data Science), NCET 3 2021-22


Web Programming(20CSI43) Module-2

3 Places to put JavaScript code


1. Between the body tag of html
2. Between the head tag of html
3. In .js file (external javascript)

JavaScript Example: code between the head tag


In this example, a JavaScript function is placed in the <head> section of an HTML
page.The function is invoked (called) when a button is clicked:
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
}
</script>
</head>
<body>
<h1>Welcome to JavaScript</h1>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

JavaScript Example: code between the body tag


JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.
The function is invoked (called) when a button is clicked:
<html>
<head>
</head>
<body>
<h1>Welcome to JavaScript</h1>

Dept. of CSE(Data Science), NCET 4 2021-22


Web Programming(20CSI43) Module-2

<form>
<input type="button" value="click" onclick="msg()"/>
</form>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
}
</script>
</body>
</html>

External JavaScript file


• We can create external JavaScript file and embed it in many html page.
• It provides code re usability because single JavaScript file can be used in several
html pages.
• An external JavaScript file must be saved by .js extension. It is recommended to
embed all JavaScript files into a single file. It increases the speed of the webpage.

message.js
function msg(){
alert("Hello Javatpoint");
}
Demo.HTML
<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Dept. of CSE(Data Science), NCET 5 2021-22
Web Programming(20CSI43) Module-2

Advantages of External JavaScript


• There will be following benefits if a user creates an external javascript:
• It helps in the reusability of code in more than one HTML file.
• It allows easy code readability.
• It is time-efficient as web browsers cache the external js files, which further reduces
the page loading time.
• It enables both web designers and coders to work with html and js files parallelly
and separately, i.e., without facing any code conflictions.
• The length of the code reduces as only we need to specify the location of the js file.
JS Output Statements
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
• Writing into an HTML element, using innerHTML.
• Writing into the HTML output using document.write().
• Writing into an alert box, using window.alert().
• Writing into the browser console, using console.log().
Using inner HTML
• To access an HTML element, JavaScript can use
the document.getElementById(id) method.
• Changing the innerHTML property of an HTML element is a common way to
display data in HTML.
• The id attribute defines the HTML element. The innerHTML property defines the
HTML content:

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

Dept. of CSE(Data Science), NCET 6 2021-22


Web Programming(20CSI43) Module-2

</body>
</html>

Using document.write()
For testing purposes, it is convenient to use document.write():
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>

Ex:2
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button type="button" onclick="document.write(5 + 6)">Try it</button>
</body>
</html>
 Using document.write() after an HTML document is loaded, will delete all existing
HTML:

Using window.alert()
 You can use an alert box to display data:
<!DOCTYPE html>
<html>
<body>

Dept. of CSE(Data Science), NCET 7 2021-22


Web Programming(20CSI43) Module-2

<h1>My First Web Page</h1>


<p>My first paragraph.</p>
<script>
window.alert(5 + 6);<!--alert(5 + 6); You can skip window-->
</script>
</body>
</html>

JavaScript Programs
• A computer program is a list of "instructions" to be "executed" by a computer.
• In a programming language, these programming instructions are called statements.
• A JavaScript program is a list of programming statements.
var x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
JavaScript Statements
• JavaScript statements are composed of:
• Values, Operators, Expressions, Keywords, and Comments.
• This statement tells the browser to write "Hello Dolly." inside an HTML element
with id="demo":
.
document.getElementById("demo").innerHTML = "Hello Dolly.";

• Most JavaScript programs contain many JavaScript statements.


• The statements are executed, one by one, in the same order as they are written.
• JavaScript programs (and JavaScript statements) are often called JavaScript code.
Semicolons ;
• Semicolons separate JavaScript statements.
• Add a semicolon at the end of each executable statement:

Dept. of CSE(Data Science), NCET 8 2021-22


Web Programming(20CSI43) Module-2

let a, b, c; // Declare 3 variables


a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c

• When separated by semicolons, multiple statements on one line are allowed:


a = 5; b = 6; c = a + b;

JavaScript White Space


• JavaScript ignores multiple spaces. You can add white space to your script to make
it more readable.
• The following lines are equivalent:

let person = "Hege";


let person="Hege";

• A good practice is to put spaces around operators ( = + - * / ):

let x = y + z;

JavaScript Line Length and Line Breaks


• For best readability, programmers often like to avoid code lines longer than 80
characters.
• If a JavaScript statement does not fit on one line, the best place to break it is after an
operator:
document.getElementById("demo").innerHTML =
"Hello Dolly!";
JavaScript Code Blocks
• JavaScript statements can be grouped together in code blocks, inside curly brackets
{...}.
• The purpose of code blocks is to define statements to be executed together.
• One place you will find statements grouped together in blocks, is in JavaScript
functions:

Dept. of CSE(Data Science), NCET 9 2021-22


Web Programming(20CSI43) Module-2

function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}

JavaScript Keywords
• JavaScript statements often start with a keyword to identify the JavaScript action to
be performed. JavaScript keywords are reserved words. Reserved words cannot be
used as names for variables. Here is a list of some of the keywords

Keyword Description

var Declares a variable

let Declares a block variable

const Declares a block constant

if Marks a block of statements to be executed on a condition

switch Marks a block of statements to be executed in different cases

for Marks a block of statements to be executed in a loop

function Declares a function

return Exits a function

try Implements error handling to a block of statements

JavaScript Syntax
• JavaScript syntax is the set of rules, how JavaScript programs are constructed:

// How to create variables:


var x;
let y;

Dept. of CSE(Data Science), NCET 10 2021-22


Web Programming(20CSI43) Module-2

// How to use variables:


x = 5;
y = 6;
let z = x + y;
JavaScript Comments
 Not all JavaScript statements are "executed". Code after double slashes // or
between /* and */ is treated as a comment. Comments are ignored, and will not be
executed:
var x = 5; // I will be executed

// var x = 6; I will NOT be executed

JavaScript Identifiers
Identifiers are names. In JavaScript, identifiers are used to name variables (and keywords,
and functions, and labels).
All JavaScript variables must be identified with unique names. These unique names are
called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
 Names can contain letters, digits, underscores, and dollar signs.
 Names must begin with a letter
 Names can also begin with $ and _
 Names are case sensitive (y and Y are different variables)
 Reserved words (like JavaScript keywords) cannot be used as names. JavaScript
identifiers are case-sensitive.

Dept. of CSE(Data Science), NCET 11 2021-22


Web Programming(20CSI43) Module-2

JavaScript Values
The JavaScript syntax defines two types of values:
• Fixed values
• Variable values
Fixed values are called Literals.
Variable values are called Variables.

JavaScript Literals
The two most important syntax rules for fixed values are:
1. Numbers are written with or without decimals: 10.50, 1001
2. Strings are text, written within double or single quotes: "John Doe“, 'John Doe'

JavaScript Variables
• Variables in JavaScript are containers that hold reusable data. It is the basic unit of
storage in a program.
• The value stored in a variable can be changed during program execution.
• A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
• In JavaScript, all the variables must be declared before they can be used.
• JavaScript uses the keywords var, let and const to declare variables.
• An equal sign is used to assign values to variables.
• In this example, x is defined as a variable. Then, x is assigned (given) the value 6:

let x;
x = 6;

var keyword
• Variables are declared with the var keyword as follows.
var var_name;
var x;

• The var_name is the name of the variable which should be defined by the user and
should be unique.
• These types of names are also known as identifiers.

Dept. of CSE(Data Science), NCET 12 2021-22


Web Programming(20CSI43) Module-2

• The rules for creating an identifier in JavaScript are, the name of the identifier
should not be any pre-defined word(known as keywords), the first character must be
a letter, an underscore (_), or a dollar sign ($). Subsequent characters may be any
letter or digit or an underscore or dollar sign.
• We can initialize the variables either at the time of declaration or also later when we
want to use them. Below are some examples of declaring and initializing variables in
JavaScript:

// declaring single variable


var name;
// declaring multiple variables
var name, title, num;
// initializing variables
var name = "Harsh";
name = "Rakesh";
• JavaScript is also known as untyped language.
• This means, that once a variable is created in JavaScript using the keyword var, we
can store any type of value in this variable supported by JavaScript.
• Below is the example for this:

// creating variable to store a number


var num = 5;
// store string in the variable num
num = "GeeksforGeeks";

• Variables in JavaScript can also evaluate simple mathematical expressions and


assume their value.

// storing a mathematical expression


var x = 5 + 10 + 1;
console.log(x); // 16

Dept. of CSE(Data Science), NCET 13 2021-22


Web Programming(20CSI43) Module-2

let keyword
• The variable type Let shares lots of similarities with var but unlike var, it has scope
constraints.
• var and let are both used for variable declaration in javascript but the difference
between them is that var is function scoped and let is block scoped.

// let variable
let x; // undefined
let name = 'Mukul';
// can also declare multiple values
let a=1,b=2,c=3;
// assignment
let a = 3; a = 4; // works same as var.
• Variables defined with let cannot be Redeclared.
• Variables defined with let must be Declared before use.

let x = "John Doe";


let x = 0;

// SyntaxError: 'x' has already been declared

const keyword

• Const is another variable type assigned to data whose value cannot and will not
change throughout the script.
// const variable
const name = 'Mukul';
name = 'Mayank'; // will give Assignment to constant variable error.

Variable Scope in Javascript


The scope of a variable is the region of your program in which it is defined. JavaScript
variables have only two scopes.

Dept. of CSE(Data Science), NCET 14 2021-22


Web Programming(20CSI43) Module-2

• Global Variables − A global variable has 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 you declare a local variable or function parameter with the same name as
a global variable, you effectively hide the global variable. Take a look into the following
example.

<html>
<body onload = checkscope();>
<script type = "text/javascript">

var myVar = "global"; // Declare a global variable


function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
</script>
</body>
</html>
 This produces the following result: local

Javascript Data Types


JavaScript provides different data types to hold different types of values. There are two
types of data types in JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type
JavaScript is a dynamic type language; means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine. You need to use var here to
specify the data type. It can hold any type of values such as numbers, strings etc. For
example:

Dept. of CSE(Data Science), NCET 15 2021-22


Web Programming(20CSI43) Module-2

var a=40;//holding number


var b="Rahul";//holding string

JavaScript primitive data types


• There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all

JavaScript Strings
 A string (or a text string) is a series of characters like "John Doe".
 Strings are written with quotes. You can use single or double quotes:

let carName1 = "Volvo XC60"; // Using double quotes


let carName2 = 'Volvo XC60'; // Using single quotes
 You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:

let answer1 = "It's alright"; // Single quote inside double quotes


let answer2 = "He is called 'Johnny'"; // Single quotes inside double quotes
let answer3 = 'He is called "Johnny"'; // Double quotes inside single quotes

JavaScript Numbers
 JavaScript has only one type of numbers.
 Numbers can be written with, or without decimals:

let x1 = 34.00; // Written with decimals


let x2 = 34; // Written without decimals

Dept. of CSE(Data Science), NCET 16 2021-22


Web Programming(20CSI43) Module-2

 Extra-large or extra small numbers can be written with scientific (exponential)


notation:

let y = 123e5; // 12300000


let z = 123e-5; // 0.00123

JavaScript Booleans
 Booleans can only have two values: true or false.
 Booleans are often used in conditional testing.

let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false

Undefined
• In JavaScript, a variable without a value, has the value undefined. The type is
also undefined.

let car; // Value is undefined, type is undefined

Empty Values
• An empty value has nothing to do with undefined.
• An empty string has both a legal value and a type.

let car = ""; // The value is "", the typeof is "string"

Null
• In JavaScript null is "nothing". It is supposed to be something that doesn't exist.
• Unfortunately, in JavaScript, the data type of null is an object.
• You can consider it a bug in JavaScript that typeof null is an object. It should be
null.
• You can empty an object by setting it to null.

typeof undefined // undefined


typeof null // object

null === undefined// false


null == undefined // true

Dept. of CSE(Data Science), NCET 17 2021-22


Web Programming(20CSI43) Module-2

let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};


person = null; // Now value is null, but type is still an object

JavaScript non-primitive data types


• The non-primitive data types are as follows

Data Type Description

Object represents instance through which we can access


members

Array represents group of similar values

RegExp represents regular expression

JavaScript non-primitive data types


JavaScript Arrays
• JavaScript arrays are written with square brackets.
• Array items are separated by commas.
• The following code declares (creates) an array called cars, containing three items
(car names):

const cars = ["Saab", "Volvo", "BMW"];

JavaScript Objects
• JavaScript objects are written with curly braces {}.
• Object properties are written as name:value pairs, separated by commas.

const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

The typeof Operator


• You can use the JavaScript typeof operator to find the type of a JavaScript variable.
• The typeof operator returns the type of a variable or an expression:

typeof "" // Returns "string"


typeof "John" // Returns "string"
typeof "John Doe" // Returns "string“

Dept. of CSE(Data Science), NCET 18 2021-22


Web Programming(20CSI43) Module-2

typeof 0 // Returns "number"


typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"

JavaScript Type Conversion


JavaScript variables can be converted to a new variable and another data type:
• By the use of a JavaScript function
• Automatically by JavaScript itself
Converting Strings to Numbers
• The global method Number() can convert strings to numbers.
• Strings containing numbers (like "3.14") convert to numbers (like 3.14).
• Empty strings convert to 0.
• Anything else converts to NaN (not a number)

Number("3.14") // returns 3.14


Number(" ") // returns 0
Number("") // returns 0
Number("99 88") // returns NaN

<script>
var x1=Number("3.14") +"<br>" ; // returns 3.14<br>
var x2=Number(" ") +"<br>" ; // returns 0
var x3=Number("")+"<br>" ; // returns 0
var x4=Number("9 988") +"<br>" ; // returns NaN
document.write(x1);
document.write(x2);
document.write(x3);
document.write(x4);
</script>

Dept. of CSE(Data Science), NCET 19 2021-22


Web Programming(20CSI43) Module-2

Converting Numbers to Strings


• The global method String() can convert numbers to strings.
• It can be used on any type of numbers, literals, variables, or expressions:

<script>
let x = 123;
document.getElementById("demo")
.innerHTML = String(x) + "<br>" +
String(123) + "<br>" +
String(100 + 23);
</script>
 The number method toString() will do the same:

x.toString()
(123).toString()
(100 + 23).toString()

Converting Booleans to Numbers


• The global method Number() can also convert booleans to numbers.

Number(false) // returns 0
Number(true) // returns 1

Converting Booleans to Strings


• The global method String() can convert booleans to strings.

String(false) // returns "false"


String(true) // returns "true"

• The Boolean method toString() does the same.

false.toString() // returns "false"


true.toString() // returns "true

Dept. of CSE(Data Science), NCET 20 2021-22


Web Programming(20CSI43) Module-2

Automatic Type Conversion


• When JavaScript tries to operate on a "wrong" data type, it will try to convert the
value to a "right" type.
• The result is not always what you expect:

5 + null // returns 5 because null is converted to 0


"5" + null // returns "5null" because null is converted to "null"
"5" + 2 // returns "52" because 2 is converted to "2"
"5" - 2 // returns 3 because "5" is converted to 5
"5" * "2" // returns 10 because "5" and "2" are converted to 5 and 2

JavaScript Operators and Expressions


What is an Operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and
‘+’ is called the operator. JavaScript supports the following types of operators.
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators

Arithmetic Operators
• JavaScript supports the following arithmetic operators −
• Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description

1 + (Addition)
Adds two operands
Ex: A + B will give 30

2 - (Subtraction)
Subtracts the second operand from the first

Dept. of CSE(Data Science), NCET 21 2021-22


Web Programming(20CSI43) Module-2

Ex: A - B will give -10

3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200

4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2

5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0

6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11

7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9

8 **(Exponent)
Ex: A**B

Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give
"a10".

Ex:
<html>
<body>
<script type = "text/javascript">
<
var a = 33;
var b = 10;
var c = "Test"; var linebreak = "<br />";

Dept. of CSE(Data Science), NCET 22 2021-22


Web Programming(20CSI43) Module-2

document.write("a + b = ");
result = a + b;
document.write(result); document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result); document.write(linebreak);

document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);

a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
</script>
</body>
</html>

Dept. of CSE(Data Science), NCET 23 2021-22


Web Programming(20CSI43) Module-2

Comparison Operators
• JavaScript supports the following comparison operators −
• Assume variable A holds 10 and variable B holds 20, then −

1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the
condition becomes true.
Ex: (A == B) is not true.

2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values
are not equal, then the condition becomes true.
Ex: (A != B) is true.

3 > (Greater than)


Checks if the value of the left operand is greater than the value of the
right operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.

4 < (Less than)


Checks if the value of the left operand is less than the value of the right
operand, if yes, then the condition becomes true.
Ex: (A < B) is true.

5 >= (Greater than or Equal to)


Checks if the value of the left operand is greater than or equal to the
value of the right operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.

6 <= (Less than or Equal to)


Checks if the value of the left operand is less than or equal to the value of
the right operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.

Ex:
<html> <body>

Dept. of CSE(Data Science), NCET 24 2021-22


Web Programming(20CSI43) Module-2

<script type = "text/javascript">


var a = 10;
var b = 20;
var linebreak = "<br />";
document.write("(a == b) => ");
result = (a == b);
document.write(result);
document.write(linebreak);
document.write("(a < b) => ");
result = (a < b);
document.write(result);
document.write(linebreak);
document.write("(a > b) => ");
result = (a > b);
document.write(result);
document.write(linebreak);

document.write("(a != b) => ");


result = (a != b);
document.write(result);
document.write(linebreak);
document.write("(a >= b) => ");
result = (a >= b);
document.write(result);
document.write(linebreak);
document.write("(a <= b) => ");
result = (a <= b);
document.write(result);
document.write(linebreak);
</script>
</body>
</html>

Dept. of CSE(Data Science), NCET 25 2021-22


Web Programming(20CSI43) Module-2

Logical Operators
• JavaScript supports the following logical operators −
• Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description

1 && (Logical AND)


If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.

2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes
true.
Ex: (A || B) is true.

3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the
Logical NOT operator will make it false.
Ex: ! (A && B) is false.

<html>
<body>
<script type = "text/javascript">
var a = true;
var b = false;
var linebreak = "<br />";
document.write("(a && b) => ");
result = (a && b);
document.write(result);
document.write(linebreak);
document.write("(a || b) => ");
result = (a || b);
document.write(result);
document.write(linebreak);

Dept. of CSE(Data Science), NCET 26 2021-22


Web Programming(20CSI43) Module-2

document.write("!(a && b) => ");


result = (!(a && b));
document.write(result);
document.write(linebreak);
</script>
</body>
</html>

Bitwise Operators
• JavaScript supports the following bitwise operators −
• Assume variable A holds 2 and variable B holds 3, then −

Sr.No. Operator & Description

1 & (Bitwise AND)


It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.

2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.

3 ^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer
arguments. Exclusive OR means that either operand one is true or operand two
is true, but not both.

4 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the
operand.
Ex: (~B) is -4.

5 << (Left Shift)


It moves all the bits in its first operand to the left by the number of places
specified in the second operand. New bits are filled with zeros. Shifting a

Dept. of CSE(Data Science), NCET 27 2021-22


Web Programming(20CSI43) Module-2

value left by one position is equivalent to multiplying it by 2, shifting two


positions is equivalent to multiplying by 4, and so on.
Ex: (A << 1) is 4.

6 >> (Right Shift)


Binary Right Shift Operator. The left operand’s value is moved right by
the number of bits specified by the right operand.
Ex: (A >> 1) is 1.

7 >>> (Right shift with Zero)


This operator is just like the >> operator, except that the bits shifted in on
the left are always zero.
Ex: (A >>> 1) is 1.

<html>
<body>
<script type = "text/javascript">
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
document.write("(a & b) => ");
result = (a & b);
document.write(result); document.write(linebreak);
document.write("(a | b) => ");
result = (a | b);
document.write(result); document.write(linebreak);
document.write("(a ^ b) => ");
result = (a ^ b);
document.write(result); document.write(linebreak);

document.write("(~b) => ");


result = (~b);
document.write(result);
document.write(linebreak);

Dept. of CSE(Data Science), NCET 28 2021-22


Web Programming(20CSI43) Module-2

document.write("(a << b) => ");


result = (a << b);
document.write(result);
document.write(linebreak);
document.write("(a >> b) => ");
result = (a >> b);
document.write(result);
document.write(linebreak);
</script>
</body>
</html>

Assignment Operators
Sr.No. Operator & Description

1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C

2 += (Add and Assignment)


It adds the right operand to the left operand and assigns the result to the left
operand.
Ex: C += A is equivalent to C = C + A

3 −= (Subtract and Assignment)


It subtracts the right operand from the left operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C - A

4 *= (Multiply and Assignment)


It multiplies the right operand with the left operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C * A

5 /= (Divide and Assignment)


It divides the left operand with the right operand and assigns the result to the left
operand.

Dept. of CSE(Data Science), NCET 29 2021-22


Web Programming(20CSI43) Module-2

Ex: C /= A is equivalent to C = C / A

6 %= (Modules and Assignment)


It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A

Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=,
&=, |= and ^=

<html>
<body>
<script type = "text/javascript">
var a = 33;
var b = 10;
var linebreak = "<br />";
document.write("Value of a => (a = b) => ");
result = (a = b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a += b) => ");
result = (a += b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a -= b) => ");
result = (a -= b);
document.write(result); document.write(linebreak);

document.write("Value of a => (a *= b) => ");


result = (a *= b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a /= b) => ");

Dept. of CSE(Data Science), NCET 30 2021-22


Web Programming(20CSI43) Module-2

result = (a /= b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a %= b) => ");
result = (a %= b);
document.write(result);
document.write(linebreak);
</script>
</body>
</html>

Conditional Operator (? :)
• The conditional operator first evaluates an expression for a true or false value and
then executes one of the two given statements depending upon the result of the
evaluation.

Sr.No. Operator and Description

1 ? : (Conditional )
If Condition is true? Then value X : Otherwise value Y

<html>
<body>
<script type = "text/javascript">
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write ("((a > b) ? 100 : 200) => ");
result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);
document.write ("((a < b) ? 100 : 200) => ");
result = (a < b) ? 100 : 200;
document.write(result);

Dept. of CSE(Data Science), NCET 31 2021-22


Web Programming(20CSI43) Module-2

document.write(linebreak);
</script>
</body>
</html>

Control Structures
• Control Structures are just a way to specify flow of control in programs. Any
algorithm or program can be more clear and understood if they use self-contained
modules called as logic or control structures. It basically analyzes and chooses in
which direction a program flows based on certain parameters or conditions.
• While writing a program, there may be a situation when you need to adopt one out of
a given set of paths. In such cases, you need to use conditional statements that allow
your program to make correct decisions and perform right actions.
• JavaScript supports conditional statements which are used to perform different
actions based on different conditions
There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement

if statement
• The if statement is the fundamental control statement that allows JavaScript to make
decisions and execute statements conditionally.

Dept. of CSE(Data Science), NCET 32 2021-22


Web Programming(20CSI43) Module-2

Syntax:

if (expression){
//content to be evaluated
}

Ex:

<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>

• Here a JavaScript expression is evaluated. If the resulting value is true, the given
statement(s) are executed. If the expression is false, then no statement would be not
executed

If else statement
• If – Else is a two-way decision statement.
• It is used to make decisions and execute statements conditionally.

Dept. of CSE(Data Science), NCET 33 2021-22


Web Programming(20CSI43) Module-2

Syntax:

if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}

Ex:
<html> <body>
<script type = "text/javascript">
var age = 15;
if( age > 18 ) {
document.write("<b>Qualifies for driving</b>");
}
else { document.write("<b>Does not qualify for driving</b>");
}
</script>
</body> </html>

Ex2:

<!DOCTYPE html>

Dept. of CSE(Data Science), NCET 34 2021-22


Web Programming(20CSI43) Module-2

<html>
<body>
<h2>JavaScript if .. else</h2>
<p>A time-based greeting:</p>
<p id="demo"></p>
<script>
var hour = new Date().getHours();
let greeting;
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
</script>
</body>
</html>
If else if statement
• if-else if is conditional control structure, helps to execute the part code which
matches or passes the predefined condition. And if else statement takes the decision

if (condition1) {
} else if (condition2) {
} else if (condition3) {
} else {
}

<html>
<head>
<script type="text/javascript">
var no = prompt("Enter a Number to find Odd or Even");
no = parseInt(no);
if (isNaN(no))
{
Dept. of CSE(Data Science), NCET 35 2021-22
Web Programming(20CSI43) Module-2

alert("Please Enter a Number");


}
else if (no == 0)
{
alert("The Number is Zero");
}
else if (no % 2)
{
alert("The Number is Odd");
}
else
{
alert("The Number is Even");
}
</script>
</head>
</html>

Dept. of CSE(Data Science), NCET 36 2021-22


Web Programming(20CSI43) Module-2

Ex:
let user = {
name: 'John',
isAdmin: true,
isActive : false
};
if(user.isAdmin === true || user.isActive === true) {
console.log('User has admin access');
console.log('Execute this part of the code');
} else {
console.log('User dont have admin access');
console.log('Execute this part of the code');
}
// out put
// User has admin access
// Execute this part of the code

Ex:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if .. else</h2>
<p>A time-based greeting:</p>
<p id="demo"></p>
<script>
var time = new Date().getHours();
let greeting;
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
Dept. of CSE(Data Science), NCET 37 2021-22
Web Programming(20CSI43) Module-2

greeting = "Good evening";


}
document.getElementById("demo").innerHTML = greeting;
</script>
</body>
</html>

Ex:
<html> <body>
<script type = "text/javascript">
var book = "maths";
if( book == "history" )
{ document.write("<b>History Book</b>"); }
else if( book == "maths" )
{ document.write("<b>Maths Book</b>"); }
else if( book == "economics" )
{ document.write("<b>Economics Book</b>"); }
else { document.write("<b>Unknown Book</b>"); }
</script>
</body>
<html>

Switch Statement
• Switch is used to perform different actions on different conditions.
• It is used to compare the same expression to several different values.

Dept. of CSE(Data Science), NCET 38 2021-22


Web Programming(20CSI43) Module-2

switch(expression)
{
case condition 1:
//Statements;
break;
case condition 2:
//Statements;
break;

Dept. of CSE(Data Science), NCET 39 2021-22


Web Programming(20CSI43) Module-2

case condition 3:
//Statements;
break;
case condition n:
//Statements;
break;
default:
//Statement;
}

Ex1:
<html>
<head>
<script type="text/javascript">
var day = prompt("Enter a number between 1 and 7");
switch (day)
{
case (day="1"):
document.write("Sunday");
break;
case (day="2"):
document.write("Monday");
break;
case (day="3"):
document.write("Tuesday");
break;

Ex:
case (day="4"):
document.write("Wednesday");
break;
case (day="5"):
document.write("Thursday");
break;
Dept. of CSE(Data Science), NCET 40 2021-22
Web Programming(20CSI43) Module-2

case (day="6"):
document.write("Friday");
break;
case (day="7"):
document.write("Saturday");
break;
default:
document.write("Invalid Weekday");
break;
}
</script>
</head>
</html>

For Loop
• The 'for' loop is the most compact form of looping. It includes the following three
important parts −
• The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
• The test statement which will test if a given condition is true or not. If the condition
is true, then the code given inside the loop will be executed, otherwise the control
will come out of the loop.
• The iteration statement where you can increase or decrease your counter.

Dept. of CSE(Data Science), NCET 41 2021-22


Web Programming(20CSI43) Module-2

for (begin; condition; step)


{
// ... loop body ...
}

Ex:
<html>
<body>
<script type = "text/javascript">
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++)
{
document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
</script>
</body>
</html>

Dept. of CSE(Data Science), NCET 42 2021-22


Web Programming(20CSI43) Module-2

Ex: <html>
<body>
<script type="text/javascript">
function palindrome()
{
var revstr = " ";
var strr = document.getElementById("strr").value;
var i = strr.length;
for(var j=i; j>=0; j--)
{
revstr = revstr+strr.charAt(j);
}
if(strr == revstr)
{
alert(strr+" - is Palindrome");
}
else
{
alert(strr+" - is not a Palindrome");
}
}

For-in Loop
• For-in loop is used to traverse all the properties of an object.
• It is designed for looping through arrays.

for (variable_name in Object)


{
//Statements;
}

Dept. of CSE(Data Science), NCET 43 2021-22


Web Programming(20CSI43) Module-2

• The for in loop iterates over a person object


• Each iteration returns a key (x)
• The key is used to access the value of the key
• The value of the key is person[x]

const person = {fname:"John", lname:"Doe", age:25};

let text = "";


for (let x in person) {
text += person[x];
}

for (..in) loop: The JavaScript for (..in) statement loops through the enumerable properties
of an object. The loop will iterate over all enumerable properties of the object itself and
those the object inherits from its constructor’s prototype.

Ex:
<!DOCTYPE html>
<html>
<body style = "text-align:center;">

<h1 style = "color:green;" >


Data Science
</h1>

<button onclick=“name()">Try it</button>

<p id="demo"></p>

<script>
function name() {
var Platform= {fname:“Likhith", Mname:“S", lname:“R", };

var text = "";


var x;
for (x in Platform) {
text += Platform[x] + " ";
Dept. of CSE(Data Science), NCET 44 2021-22
Web Programming(20CSI43) Module-2

}
document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

for (..of) loop: This for (..of) statement lets you loop over the data structures that are
iterable such as Arrays, Strings, Maps, Node Lists, and more. It calls a custom iteration
hook with instructions to execute on the value of each property of the object.

for (variable of iterable)


{
Statement
}

Ex:

let arr1=[45,5,6,7,8,6]
for (var z of arr1)
{
document.write(z+" , ");
}

While Loop
• While loop is an entry-controlled loop statement.
• It is the most basic loop in JavaScript.
• It executes a statement repeatedly as long as expression is true.
• Once the expression becomes false, the loop terminates.

Dept. of CSE(Data Science), NCET 45 2021-22


Web Programming(20CSI43) Module-2

while (condition)
{
//Statements;
}

Ex: Fibonacci Series Program using While Loop


<html>
<body>
<script type="text/javascript">
var no1=0,no2=1,no3=0;
document.write("Fibonacci Series:"+"<br>");
while (no2<=10)
{
no3 = no1+no2;
no1 = no2;
no2 = no3;
document.write(no3+"<br>");
}
</script>
</body>
</html>

Dept. of CSE(Data Science), NCET 46 2021-22


Web Programming(20CSI43) Module-2

Ex:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript While loop</title>
</head>
<body style="text-align:center;">
<div>
<h1>Data Science</h1>
<h2>JavaScript While Loop</h2>
</div>
<p id=“my"></p>

<!-- Script to use while loop -->


<script>
var print = "";
var val = 1;
while(val < 6) {
print += “Data " + val;
print += "<br>"
val += 1;
}
document.getElementById(“my").innerHTML = print;
</script>
</body>
</html>

Ex:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript While Loop</h2>
Dept. of CSE(Data Science), NCET 47 2021-22
Web Programming(20CSI43) Module-2

<p id="demo"></p>
<script>
let text = "";
let i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Do-While Loop
• Do-While loop is an exit-controlled loop statement.
• Similar to the While loop, the only difference is condition will be checked at the end
of the loop.
• The loop is executed at least once, even if the condition is false.

Dept. of CSE(Data Science), NCET 48 2021-22


Web Programming(20CSI43) Module-2

do
{
//Statements;
}
while(condition);

Ex:
<html>
<body>
<script type ="text/javascript">
var i = 0;
do
{
document.write(i+"<br>")
i++;
}
while (i <= 5)
</script>
</body>
</html>

Ex:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript While loop</title>
</head>
<body style="text-align:center;">
<div>
<h1>Data science</h1>
<h2>JavaScript Do-while Loop</h2> </div>
<p id=“my"></p>

<!-- Script to use do-while loop -->


Dept. of CSE(Data Science), NCET 49 2021-22
Web Programming(20CSI43) Module-2

<script>
var print = ""
var val = 0;
do {
print += “Data " + val;
print += "<br>";
val += 1;
}
while (val < 6);
document.getElementById(“my").innerHTML = print;
</script>
</body>
</html>

Ex:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Do While Loop</h2>
<p id="demo"></p>
<script>
let text = ""
let i = 0;
do {
text += "<br>The number is " + i;
i++;
}
while (i < 10);
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Ex:
Dept. of CSE(Data Science), NCET 50 2021-22
Web Programming(20CSI43) Module-2

<!DOCTYPE html>
<html>
<body>
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
</body>
</html>

Break Statement
• Break statement is used to jump out of a loop.
• It is used to exit a loop early, breaking out of the enclosing curly braces.
Syntax:break;

Dept. of CSE(Data Science), NCET 51 2021-22


Web Programming(20CSI43) Module-2

Continue Statement
• Continue statement causes the loop to continue with the next iteration.
• It skips the remaining code block.
• Syntax:continue;

JavaScript Functions
• A JavaScript function is a block of code designed to perform a particular task.
• A JavaScript function is executed when "something" invokes it (calls it).
Syntax
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
}

ex:
<script type = "text/javascript">
function sayHello()
{ alert("Hello there"); } </script>

Dept. of CSE(Data Science), NCET 52 2021-22


Web Programming(20CSI43) Module-2

JavaScript Function Syntax


• A JavaScript function is defined with the function keyword, followed by a name,
followed by parentheses ().
• Function names can contain letters, digits, underscores, and dollar signs (same rules
as variables).
• The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
• The code to be executed, by the function, is placed inside curly brackets: {}
<script type = "text/javascript">
function functionname(parameter-list) { statements }
</script>

Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)

function showMessage()
{ alert( 'Hello everyone!' ); }
showMessage();
showMessage();

• The call showMessage() executes the code of the function. Here we will see the
message two times.
• This example clearly demonstrates one of the main purposes of functions: to avoid
code duplication.
• If we ever need to change the message or the way it is shown, it’s enough to modify
the code in one place: the function which outputs it.

Dept. of CSE(Data Science), NCET 53 2021-22


Web Programming(20CSI43) Module-2

<html> <head>
<script type = "text/javascript">
function sayHello() {
document.write ("Hello there!");
} </script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
</body>
</html>

Function Return
• When JavaScript reaches a return statement, the function will stop executing.
• If the function was invoked from a statement, JavaScript will "return" to execute the
code after the invoking statement.
• Functions often compute a return value. The return value is "returned" back to the
"caller":
• Calculate the product of two numbers, and return the result:

let x = myFunction(4, 3); // Function is called, return value will end up in x

function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}

Ex2:

function sum(a, b) { return a + b; }


let result = sum(1, 2);
alert( result ); // 3

• The directive return can be in any place of the function. When the execution reaches
it, the function stops, and the value is returned to the calling code (assigned
to result above).
• There may be many occurrences of return in a single function. For instance:

Dept. of CSE(Data Science), NCET 54 2021-22


Web Programming(20CSI43) Module-2

function checkAge(age)
{
if (age >= 18)
{ return true; }
else
{ return confirm('Do you have permission from your parents?'); }
}
let age = prompt('How old are you?', 18);
if ( checkAge(age) ) {
alert( 'Access granted' ); }
else {
alert( 'Access denied' ); }

Why Functions?
• You can reuse code: Define the code once, and use it many times.
• You can use the same code many times with different arguments, to produce
different results.
Convert Fahrenheit to Celsius

function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);

The () Operator Invokes the Function

• Using the example above, toCelsius refers to the function object, and toCelsius()
refers to the function result.
• Accessing a function without () will return the function object instead of the function
result.
Example
• Instead of using a variable to store the return value of a function:

var x = toCelsius(77);
var text = "The temperature is " + x + " Celsius";

 You can use the function directly, as a variable value:

var text = "The temperature is " + toCelsius(77) + " Celsius";

Dept. of CSE(Data Science), NCET 55 2021-22


Web Programming(20CSI43) Module-2

Local Variables
• Variables declared within a JavaScript function, become LOCAL to the function.
• Local variables can only be accessed from within the function.

function showMessage()
{ let message = "Hello, I'm JavaScript!"; // local variable
alert( message );
}
showMessage(); // Hello, I'm JavaScript!
alert( message ); // <-- Error! The variable is local to the function

• Since local variables are only recognized inside their functions, variables with the
same name can be used in different functions.
• Local variables are created when a function starts, and deleted when the function is
completed.

Outer variables
• A function can access an outer variable as well, for example:

let userName = 'John';


function showMessage()
{
let message = 'Hello, ' + userName; alert(message);
}
showMessage(); // Hello, John

• The function has full access to the outer variable. It can modify it as well.

let userName = 'John';


function showMessage()
{ userName = "Bob"; // (1) changed the outer variable let
message = 'Hello, ' + userName;
alert(message); }
Dept. of CSE(Data Science), NCET 56 2021-22
Web Programming(20CSI43) Module-2

alert( userName ); // John before the function call


showMessage();
alert( userName ); // Bob, the value was modified by the function

• The outer variable is only used if there’s no local one.


• If a same-named variable is declared inside the function then it shadows the outer
one. For instance, in the code below the function uses the local userName. The outer
one is ignored:
let userName = 'John';
function showMessage()
{
let userName = "Bob"; // declare a local variable
let message = 'Hello, ' + userName; // Bob
alert(message);
}
// the function will create and use its own userName
showMessage();
alert( userName ); // John, unchanged, the function did not access the outer variable

Parameters
• We can pass arbitrary data to functions using parameters.
• In the example below, the function has two parameters: from and text.

function showMessage(from, text)


{
// parameters: from, text
alert(from + ': ' + text); }
showMessage('Ann', 'Hello!'); // Ann: Hello! (*)
showMessage('Ann', "What's up?"); // Ann: What's up? (**)

• When the function is called in lines (*) and (**), the given values are copied to local
variables from and text. Then the function uses them.

Dept. of CSE(Data Science), NCET 57 2021-22


Web Programming(20CSI43) Module-2

<html> <head>
<script type = "text/javascript">
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p> <form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say
Hello">
</form>
</body>
</html>

Ex2:

<html> <head>
<script type = "text/javascript">
function concatenate(first, last)
{ var full; full = first + last; return full; }
function secondFunction()
{ var result; result = concatenate('Zara', 'Ali'); document.write (result ); }
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call
Function">
</form>
</body>
</html>

JavaScript Events
• The change in the state of an object is known as an Event. In html, there are various
events which represents that some activity is performed by the user or by the
browser. When javascript
• code is included in HTML
• , js react over these events and allow the execution. This process of reacting over the
events is called Event Handling. Thus, js handles the HTML events via Event
Handlers.

Dept. of CSE(Data Science), NCET 58 2021-22


Web Programming(20CSI43) Module-2

• For example, when a user clicks over the browser, add js code, which will execute
the task to be performed on the event.
• Some of the HTML events and their event handlers are:
Mouse events:

Event Event Handler Description


Performed

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the
element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.

Keyboard events:

Event Performed Event Handler Description

Keydown & Keyup onkeydown & onkeyup When the user press and then release the key

Form events:

Event Event Description


Performed Handler

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

Dept. of CSE(Data Science), NCET 59 2021-22


Web Programming(20CSI43) Module-2

blur onblur When the focus is away from a form element

change onchange When the user modifies or changes the value of a form element

Window/Document events

Event Event Description


Performed Handler

load onload When the browser finishes the loading of the page

unload onunload When the visitor leaves the current webpage, the browser
unloads it

resize onresize When the visitor resizes the window of the browser

Click Event

<html>
<head> Javascript Events </head>
<body>
<script type="text/Javascript">

function clickevent()
{
document.write("This is me");
}

</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>

Dept. of CSE(Data Science), NCET 60 2021-22


Web Programming(20CSI43) Module-2

Focus Event

<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}

</script>
</body>
</html>

Keydown Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
</script>
</body>
</html>

Load event
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>

document.write("The page is loaded successfully");

</script>
</body>
</html>

Dept. of CSE(Data Science), NCET 61 2021-22


Web Programming(20CSI43) Module-2

Document Object Model


• The document object represents the whole html document.
• When html document is loaded in the browser, it becomes a document object. It is
the root element that represents the html document. It has properties and methods.
By the help of document object, we can add dynamic content to our web page.
• According to W3C - "The W3C Document Object Model (DOM) is a platform and
language-neutral interface that allows programs and scripts to dynamically access
and update the content, structure, and style of a document."
Properties of document object
• Let's see the properties of document object that can be accessed and modified by the
document object.
• The above diagram demonstrates the parent/child relationships between the nodes.
The topmost node i.e. the Document node is the root node of the DOM tree, which
has one child, the <html> element. Whereas, the <head> and <body> elements are
the child nodes of the <html> parent node.
• The <head> and <body> elements are also siblings since they are at the same level.
Further, the text content inside an element is a child node of the parent element. So,
for example, "Mobile OS" is considered as a child node of the <h1> that contains it,
and so on.

JavaScript Form Validation


• It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is must to authenticate user.

Dept. of CSE(Data Science), NCET 62 2021-22


Web Programming(20CSI43) Module-2

• JavaScript provides facility to validate the form on the client-side so data processing
will be faster than server-side validation. Most of the web developers prefer
JavaScript form validation.
• Through JavaScript, we can validate name, password, email, date, mobile numbers
and more fields.
JavaScript Form Validation Example
• In this example, we are going to validate the name and password. The name can’t be
empty and password can’t be less than 6 characters long.
• Here, we are validating the form on form submit. The user will not be forwarded to
the next page until given values are correct.

<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>

Dept. of CSE(Data Science), NCET 63 2021-22


Web Programming(20CSI43) Module-2

JavaScript Retype Password Validation

<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;

if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>

<form name="f1" action="register.jsp" onsubmit="return matchpass()">


Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>

JavaScript Number Validation


• Let's validate the textfield for numeric value only. Here, we are using isNaN()
function.

<script>
function validate(){
var num=document.myform.num.value;
if (isNaN(num)){
document.getElementById("").innerHTML="Enter Numeric value only"; numloc
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>

Dept. of CSE(Data Science), NCET 64 2021-22


Web Programming(20CSI43) Module-2

JavaScript email validation


• We can validate the email by the help of JavaScript.
• There are many criteria that need to be follow to validate the email id such as:
• email id must contain the @ and . character
• There must be at least one character before and after the @.
• There must be at least two characters after . (dot).
• Let's see the simple example to validate the email field.

<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");

if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){


alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n
dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>

<input type="submit" value="register">


</form>

Regular Expressions
• A regular expression is an object that describes a pattern of characters.
• The JavaScript RegExp class represents regular expressions, and both String
and RegExp define methods that use regular expressions to perform powerful
pattern-matching and search-and-replace functions on text.
Dept. of CSE(Data Science), NCET 65 2021-22
Web Programming(20CSI43) Module-2

• Syntax
• A regular expression could be defined with the RegExp () constructor, as follows −

var pattern = new RegExp(pattern, attributes);


or
simply var pattern = /pattern/attributes;

Here is the description of the parameters −


• pattern − A string that specifies the pattern of the regular expression or another
regular expression.
• attributes − An optional string containing any of the "g", "i", and "m" attributes that
specify global, case-insensitive, and multi-line matches, respectively.

Brackets
• Brackets ([]) have a special meaning when used in the context of regular
expressions. They are used to find a range of characters.

Sr.No. Expression & Description

1 [...]
Any one character between the brackets.

2 [^...]
Any one character not between the brackets.

3 [0-9]
It matches any decimal digit from 0 through 9.

4 [a-z]
It matches any character from lowercase a through lowercase z.

5 [A-Z]
It matches any character from uppercase A through uppercase Z.

6 [a-Z]
It matches any character from lowercase a through uppercase Z.

Dept. of CSE(Data Science), NCET 66 2021-22


Web Programming(20CSI43) Module-2

• The ranges shown above are general; you could also use the range [0-3] to match
any decimal digit ranging from 0 through 3, or the range [b-v] to match any
lowercase character ranging from b through v
Quantifiers
• The frequency or position of bracketed character sequences and single characters can
be denoted by a special character. Each special character has a specific connotation.
The +, *, ?, and $ flags all follow a character sequence.

Sr.No. Expression & Description

1 p+
It matches any string containing one or more p's.

2 p*
It matches any string containing zero or more p's.

3 p?
It matches any string containing at most one p.

4 p{N}
It matches any string containing a sequence of N p's

5 p{2,3}
It matches any string containing a sequence of two or three p's.

6 p{2, }
It matches any string containing a sequence of at least two p's.

7 p$
It matches any string with p at the end of it.

8 ^p
It matches any string with p at the beginning of it.

Literal characters

Sr.No. Character & Description

1 Alphanumeric

Dept. of CSE(Data Science), NCET 67 2021-22


Web Programming(20CSI43) Module-2

Itself

2 \0
The NUL character (\u0000)

3 \t
Tab (\u0009

4 \n
Newline (\u000A)

5 \v
Vertical tab (\u000B)

6 \f
Form feed (\u000C)

7 \r
Carriage return (\u000D)

8 \xnn
The Latin character specified by the hexadecimal
number nn; for example, \x0A is the same as \n

9 \uxxxx
The Unicode character specified by the hexadecimal
number xxxx; for example, \u0009 is the same as \t

10 \cX
The control character ^X; for example, \cJ is
equivalent to the newline character \n

Metacharacters
• A metacharacter is simply an alphabetical character preceded by a backslash that
acts to give the combination a special meaning.
• For instance, you can search for a large sum of money using the '\d'
metacharacter: /([\d]+)000/, Here \d will search for any string of numerical
character.
Dept. of CSE(Data Science), NCET 68 2021-22
Web Programming(20CSI43) Module-2

• The following table lists a set of metacharacters which can be used in PERL Style
Regular Expressions.

Sr.No. Character & Description

1 .
a single character

2 \s
a whitespace character (space, tab, newline)

3 \S
non-whitespace character

4 \d
a digit (0-9)

5 \D
a non-digit

6 \w
a word character (a-z, A-Z, 0-9, _)

7 \W
a non-word character

8 [\b]
a literal backspace (special case).

9 [aeiou]
matches a single character in the given set

10 [^aeiou]
matches a single character outside the given set

11 (foo|bar|baz)
matches any of the alternatives specified

Modifiers
 Several modifiers are available that can simplify the way you work with regexps, like
case sensitivity, searching in multiple lines, etc.
Dept. of CSE(Data Science), NCET 69 2021-22
Web Programming(20CSI43) Module-2

Sr.No. Modifier & Description

1 i
Perform case-insensitive matching.

2 m
Specifies that if the string has newline or carriage return characters, the ^
and $ operators will now match against a newline boundary, instead of a
string boundary

3 g
Performs a global matchthat is, find all matches rather than stopping after
the first match.

What is WEB SQL?


Web SQL is a web page API for storing or managing the data in databases that can be
queried using a variant of SQL like creating databases, opening the transaction, creating
tables, inserting values to tables, deleting values, and reading data.
Methods:
There are three basic methods as shown below as follows:

Method Action Performed

It can be used to create a new database or can create the database


openDatabase
object using an existing database.

It transaction can control a transaction and perform either commit


transaction
or rollback depending upon the situation.

executeSql It is used to execute a real SQL query.

Creating or Opening web SQL Database:


We can use the openDatabase function to create a database that has four parameters:
• Database name
• Version number

Dept. of CSE(Data Science), NCET 70 2021-22


Web Programming(20CSI43) Module-2

• Description
• Size
• Creation callback.
The creation callback gets called while the database is being created.
Use the openDatabase() method to access a database. If the database doesn’t exist, the
method first creates it and then opens it:

. Syntax: var gfgDb = openDatabase(database name, version number, description, size);

Creating transaction:
We can use the function called transaction from our database instance.
Syntax:

gfgDb.transaction(function (tx){});

• Here, gfgDb is our database instance and tx is the transaction object that we will be
using for upcoming operations. If any operation throws an error, the transaction will
be rollbacked. Error logs can easily be managed by the use of transactions.

Executing queries:
To execute a query you use the database.transaction() function.It has a single argument, that
executes the query as below:

Executing queries:
To execute a query you use the database.transaction() function.It has a single argument, that
executes the query as below:

var gfgDb = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);


gfgDb.transaction(function (tx)
{
tx.executeSql('CREATE TABLE IF NOT EXISTS CLASS (id unique, class)');
});

The above code will create a table named CLASS in the ‘gfgDb’ database.
Dept. of CSE(Data Science), NCET 71 2021-22
Web Programming(20CSI43) Module-2

INSERT Operation:
To create entries into the table as follows:

var gfgDb = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);


gfgDb.transaction(function (tx)
{
tx.executeSql('CREATE TABLE IF NOT EXISTS CLASS (id unique, class)');
tx.executeSql('INSERT INTO CLASS (id, class) VALUES (1, "First")');
tx.executeSql('INSERT INTO CLASS (id, class) VALUES (2, "Second")');
}
);

READ Operation:
To read already existing records we use a callback:

db.transaction(function (tx) {
tx.executeSql('SELECT * FROM CLASS', [], function (tx, results)
{
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;
for (i = 0; i < len; i++) { alert(results.rows.item(i).class ); } }, null);

Dept. of CSE(Data Science), NCET 72 2021-22

You might also like