Module 2 Notes
Module 2 Notes
MODULE 2
JavaScript
. By
Prof. Likhith S R
Assistant. Professor
Dept. of CSE(DS), NCET
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.
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.
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
}
</script>
</body>
</html>
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
<!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>
</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>
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.";
let x = y + z;
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
JavaScript Syntax
• JavaScript syntax is the set of rules, how JavaScript programs are constructed:
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.
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.
• 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:
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.
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.
• 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">
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:
JavaScript Numbers
JavaScript has only one type of numbers.
Numbers can be written with, or without decimals:
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.
Empty Values
• An empty value has nothing to do with undefined.
• An empty string has both a legal value and a type.
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.
JavaScript Objects
• JavaScript objects are written with curly braces {}.
• Object properties are written as name:value pairs, separated by commas.
<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>
<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()
Number(false) // returns 0
Number(true) // returns 1
Arithmetic Operators
• JavaScript supports the following arithmetic operators −
• Assume variable A holds 10 and variable B holds 20, then −
1 + (Addition)
Adds two operands
Ex: A + B will give 30
2 - (Subtraction)
Subtracts the second operand from the first
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 />";
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>
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.
Ex:
<html> <body>
Logical Operators
• JavaScript supports the following logical operators −
• Assume variable A holds 10 and variable B holds 20, then −
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);
Bitwise Operators
• JavaScript supports the following bitwise operators −
• Assume variable A holds 2 and variable B holds 3, then −
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.
<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);
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
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);
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.
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);
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.
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.
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>
<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
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
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.
switch(expression)
{
case condition 1:
//Statements;
break;
case condition 2:
//Statements;
break;
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.
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>
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 (..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;">
<p id="demo"></p>
<script>
function name() {
var Platform= {fname:“Likhith", Mname:“S", lname:“R", };
}
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.
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.
while (condition)
{
//Statements;
}
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>
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.
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>
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;
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>
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.
<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:
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
Ex2:
• 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:
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);
• 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";
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:
• The function has full access to the outer variable. It can modify it as well.
Parameters
• We can pass arbitrary data to functions using parameters.
• In the example below, the function has two parameters: from and text.
• When the function is called in lines (*) and (**), the given values are copied to local
variables from and text. Then the function uses them.
<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.
• 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:
mouseover onmouseover When the cursor of the mouse comes over the
element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Keyboard events:
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
Form events:
change onchange When the user modifies or changes the value of a form element
Window/Document events
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>
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>
</script>
</body>
</html>
• 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>
<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>
<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>
<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
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 −
Brackets
• Brackets ([]) have a special meaning when used in the context of regular
expressions. They are used to find a range of characters.
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.
• 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.
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
1 Alphanumeric
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.
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
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.
• 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:
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:
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:
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);