Module 2-1
Module 2-1
Advantages of JavaScript
JavaScript saves server traffic.
It performs the operations very fast.
It is simple to learn and implement.
It is versatile.
JavaScript pages are executed on the client side.
JavaScript extends its functionality to the web pages.
Disadvantages of JavaScript
JavaScript cannot be used for networking applications.
It doesn't have any multithreading or multiprocessor capabilities. It has security issues
being a client-side scripting language.
What is a script?
Script is a small , embedded program.
The most popular scripting languages on the web are,
JavaScript or VBScript.
HTML does not have scripting capability, you need to use
<script> tag. The <script> tag is used to generate a script.
The </script> tag indicates the end of the script or program.
<script type = “text/javascript”>
[Link](“TutorialRide”);
</script>
Client-Side Scripting
Client-Side Scripting is an important part of the Dynamic HTML (DHTML).
JavaScript is the main client-side scripting language for the web.
The scripts are interpreted by the browser.
Client-Side scripting is used to make changes in the web page after they
arrive at the browser.
It is useful for making the pages a bit more interesting and user- friendly.
It provides useful gadgets such as calculators, clocks etc.
It enables interaction within a web page.
It is affected by the processing speed of the user's computer.
Operation of Client-Side Scripting
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!-- [Link]("Hello World!") //-->
</script>
</body>
</html>
Ways to write/execute JavaScript: (Where to
write? JavaScript in <head> or <body>??)
You can place any number of scripts in an HTML document. Scripts can be placed in the
<body>, or in the <head> section of an HTML page, or in both.
There are three ways of executing JavaScript on a web browser.
Inside <HEAD> tag
Within <BODY> tag
In an External File
Scripts can also be placed in external files:
o External scripts are practical when the same code is used in many different
web pages.
o JavaScript files have the file extension .js.
o To use an external script, put the name of the script file in the src (source)
attribute of a <script> tag.
o Example: <script src="[Link]"></script>
If you assign values to variables that have not yet been declared, the variables will automatically be declared. These
statements:x=5;
carname="Volvo"; have the same effect as:
var x=5;
var carname="Volvo";
After the execution of the statements above, the variable x will still have the value of 5. The value of x
is not reset (or cleared) when you redeclare it.
JavaScript Operators
There are different types of JavaScript operators:
•Arithmetic Operators
•Assignment Operators
•Comparison Operators
•String Operators
•Logical Operators
•Bitwise Operators
•Ternary Operators
•Type Operators
Arithmetic Operators are used to perform arithmetic on numbers:
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
JavaScript Assignment Operators
• Assignment operators assign values to JavaScript variables.
• The Addition Assignment Operator (+=) adds a value to a variable.
== equal to
!= not equal
? ternary operator
JavaScript Logical Operators
Operat Description
or
&& logical and
|| logical or
! logical not
Operator
Operator Description
Description
typeof
typeof Returnsthe
Returns thetype
typeof
ofaavariable
variable
instanceof
instanceof Returnstrue
Returns trueififan
anobject
objectisisan
aninstance
instance
ofan
of anobject
objecttype
type
JavaScript Bitwise Operators
Operator Description Example Same as Result Decimal
& AND 5&1 0101 & 0001 1
0001
| OR 5|1 0101 | 0101 5
0001
~ NOT ~5 ~0101 1010 10
^ XOR 5^1 0101 ^ 0100 4
0001
<< left shift 5 << 1 0101 << 1010 10
1
>> right shift 5 >> 1 0101 >> 0010 2
1
>>> unsigned right 5 >>> 1 0101 0010 2
JavaScript Control and Looping Structure
If Statement
IF statement is a conditional branching statement.
In 'IF' statement, if the condition is true a group of
statement is executed. And if the condition is false, the
following statement is skipped.
if(condition)
{
//Statement 1;
//Statement 2;
}
Example : Simple Program for IF Statement
<html>
<body>
<script type="text/javascript">
var num = prompt("Enter
Number");
if (num > 0)
{
alert("Given number is
Positive!!!");
}
</script>
</body>
</html>
If – Else Statement
If – Else is a two-way decision statement.
It is used to make decisions and execute statements conditionally.
{ if (isNaN(no))
//Statement 2; {
else }
{ else if (no == 0)
//Statement 3; {
<script type="text/javascript">
case (day="3"):
[Link]("Tuesday"); break;
case (day="4"):
[Link]("Wednesday"); break;
default:
</script>
</head>
</html>
For Loop
For loop is a compact form of looping.
It includes three important parts:
Loop Initialization
Test Condition
Iteration
All these three parts come in a single line separated by semicolons(;).
Syntax:
for(initialization; test-condition;
increment/decrement)
{
Syntax
//Statements;
}
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.
<html>
<body>
<script
type="text/javascript"> var
no1=0,no2=1,no3=0;
[Link]("Fibonacci Series:"+"<br>");
while (no2<=10)
{
no3 = no1+no2; no1 = no2;
no2 = no3; [Link](no3+"<br>");
}
</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.
<html>
<body>
<script type Output:
="text/javascript"> 0
var i = 0; 1
2
do{ 3
[Link](i+"<br>") 4
i+ 5
+;
}
while (i <= 5)
</script>
</body>
</html>
Difference between While Loop
and Do – While Loop
While Loop Do – While Loop
In while loop, first it checks the In Do – While loop, first it executes the
condition and then executes the program and then checks the
program. condition.
It is an entry – controlled loop. It is an exit – controlled loop.
The condition will come before the The condition will come after the body.
body.
If the condition is false, then it It runs at least once, even though the
terminates the loop. conditional is false.
It is a counter-controlled loop. It is a iterative control loop.
Break Statement
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).
Functions Description
isNan() Returns true, if the object is Not a Number.
Returns false, if the object is a number.
parseFloat If the string begins with a number, the function reads through the
(string) string until it finds the end of the number; cuts off the remainder of the
string and returns the result.
If the string does not begin with a number, the function returns NaN.
parseInt If the string begins with an integer, the function reads through the
(string) string until it finds the end of the integer, cuts off the remainder of the
string and returns the result.
If the string does not begin with an integer, the function returns NaN
(Not a Number).
String Converts the object into a string.
(object)
eval() Returns the result of evaluating an arithmetic expression.
User-defined Functions
User-defined function means you can create a function for your own use.
You can create yourself according to your need.
In JavaScript, these functions are written in between the <HEAD> tag of the HTML
page.
Celsius");
}
</script>
</head>
<body>
<h2>JavaScript Functions</h2>
<button onclick='toCelsius(98);'>Click
Here</button>
</body>
</html>
JavaScript Arrays
Creating and Initializing Arrays
Array Description
Properti
Iteration through Arrays es
function show_array(arr)
Constructor It returns a reference to the array
{
function that created the object.
for (var i = 0; i < [Link]; i++ )
{
[Link](array[i]);
Index It represents the zero-based index of the
[Link]('<br/>'); match in the string.
}
} Length It reflects the number of elements in an
var arr1 = [1, 2,3]; array.
show_array(arr1); Input It presents only an array created by
regular expression matches.
Methods Description
<html>
<head>
<head>
<title>My Page</title>
<body> <title>
</head>
<body> <h1>
<h1> Hello! </h1>
</body>
</html>
• At the top level, there is an html node, with two children: head and
body, among which only head has a child tag title.
• HTML tags are element nodes in DOM tree, pieces of text becomet
ext nodes. Both of them are nodes, just the type is different.
ACCESSING DOM:
My PageHello!
✓
The HTML DOM can be accessed with JavaScript (and with other
programming languages).
✓ In the DOM, all HTML elements are defined as objects.
✓ With the object model, JavaScript gets all the power it needs to
create dynamic HTML:
· JavaScript can change all the HTML elements in the page
· JavaScript can change all the HTML attributes in the page
· JavaScript can change all the CSS styles in the page
· JavaScript can remove existing HTML elements and attributes
JavaScript can add new HTML elements and attributes
JavaScript can react to all existing HTML events in the page
· JavaScript can create new HTML events in the page
The following table lists the node types commonly encountered
in HTML documents and the nodeType value for each one.
Element Node.ELEMENT_NODE 1
Text Node.TEXT_NODE 3
Document Node.DOCUMENT_NODE 9
Comment Node.COMMENT_NODE 8
DocumentFragment Node.DOCUMENT_FRAGMENT_NODE 11
Attr Node.ATTRIBUTE_NODE 2
The following table lists the method properties of Node object.
The HTML DOM Document:
In the HTML DOM object model, the document object represents our web page.
The document object is the owner of all other objects in our web page.
Finding HTML Elements:
Often, with JavaScript, we may want to manipulate HTML elements.
To do so, we have to find the elements first. There are a three of ways to do this:
· Finding HTML elements by id
Method Description
Method Description
Adding event
[Link](id).onclick=function() handler code to an
{code}
onclick event
Reacting to Events
✓ A JavaScript can be executed when an event occurs, like when a user clicks on
an HTML element.
✓ To execute code when a user clicks on an element, add
JavaScript code to an HTML event attribute:
onclick=JavaScript
<script type="text/javascript">
var ck_name = /^[A-Za-z0-9 ]{3,20}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a- z]{2,6}(?:\.[a-z]{2})?)$/i
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
var ck_password = /^[A-Za-z0-9!@#$%^S*()_]{6,20}$/;
function validate(){
var name = [Link]; var email = [Link];
var username = [Link]; var password = [Link]; var gender =
[Link];
var errors = [];
if (!ck_name.test(name)) { if ([Link] > 0) { reportErrors(errors); return false;
errors[[Link]] = "Enter your valid }
Name ."; } return true;
}
if (!ck_email.test(email)) {
errors[[Link]] = "You must enter a function reportErrors(errors){
valid email address.";
var msg = "Please Enter Valide Data...\n"; for (var i = 0;
} i<[Link]; i++) {
if (!ck_username.test(username)) { var numError = i + 1;
errors[[Link]] = "You must enter valid msg += "\n" + numError + ". " + errors[i];
UserName with no special char ."; }
} alert(msg);
}
if (!ck_password.test(password)) { </script>
errors[[Link]] = "You must enter a </head>
valid Password min 6 char."; <body>
}
if (gender==0) { <center> REGISTRATION FORM</center> <hr>
errors[[Link]] = "Select Gender"; <form action="[Link]" name="form">
}
<label> Full Name </label>
<input type="text" name="name" value="" />
<br><br>
Event Handlers: Functions that handle events are called event handlers.
They contain the script that gets executed in response to the events.
Advantage of Event Handling: Events and Event Handler makes web applications more
responsive, dynamic and interactive.
1. Inline model: Treating events as attributes of HTML elements. These event attributes are
called as intrinsic event attributes.
Example: <p onclick=‖myfunction()‖>
Where,
Onclick – intrinsic event attribute.
Myfunction() – event handler to handle the event.
1. Traditional Model: Registering event handler through DOM.
Example:
<!DOCTYPE html>
<html>
<head>
<title> Event Handling in JavaScript</title>
<script type="text/javascript"> function handleSubmit()
{
[Link]("Data Successfully submitted!");
}
function handleReset()
{
[Link]("Clearing Form Data ! ");
}
function registerEvent()
{
var reset=[Link]("clear"); [Link]=handleReset;
}
</script>
</head>
<body onload="[Link]('Welcome! opening your
page'); registerEvent()">
<form onsubmit="handleSubmit();">
<input type="text" onselect="[Link]('text selected')" /><br />
<input type="submit" value="submit data" /><br />
<input type="reset" id="clear" value="Clear data" /><br />
</form>
</body>
</html>
Javascript | Error and Exceptional Handling
An error is an action which is inaccurate or incorrect. There are
three types of error in programming
1. Syntax error
2. Logical error
3. Runtime error
Syntax error:
Syntax errors, also called parsing errors, occur at compile
time in traditional programming languages and at interpret time in
JavaScript.
For example, the following line causes a syntax error because it is missing a closing
parenthesis.
<script type = "text/javascript">
<!--
[Link](;
//-->
</script>
When a syntax error occurs in JavaScript, only the code
contained within the same thread as the syntax error is affected
and the rest of the code in other threads gets executed assuming
nothing in them depends on the code containing the error.
Logical error:
Logic errors can be the most difficult type of errors to track down. These errors are not the result of a
syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script
and you do not get the result you expected.
You cannot catch those errors, because it depends on your business requirement what type of logic you
want to put in your program.
Runtime Error:
Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).
For example, the following line causes a runtime error because here the syntax is correct, but at runtime,
it is trying to call a method that does not exist.
<script type = "text/javascript">
<!--
[Link]();
//-->
</script>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue
normal execution.
What is an Exception?
An exception signifies the presence of an abnormal condition which requires special
operable techniques.
In programming terms, an exception is the anomalous code that breaks the normal flow of
the code. Such exceptions require specialized programming constructs for its execution.
What is Exception Handling?
In programming, exception handling is a process or method used for handling the
abnormal statements in the code and executing them.
It also enables to handle the flow control of the code/program.
For handling the code, various handlers are used that process the exception and execute the
code.
For example, the Division of a non-zero value with zero will result into infinity always, and
it is an exception. Thus, with the help of exception handling, it can be executed and
handled.
Error Object
When a runtime error occurs, it creates and throws an Error object. Such an object can be used as
a base for the user-defined exceptions too. An error object has two properties:
1. name: This is an object property that sets or returns an error name.
2. message: This property returns an error message in the string form.
Although Error is a generic constructor, there are following standard built- in error types or error
constructors beside it:
3. EvalError: It creates an instance for the error that occurred in the eval(), which is a global function
used for evaluating the js string code.
4. InternalError: It creates an instance when the js engine throws an internal error.
5. RangeError: It creates an instance for the error that occurs when a numeric variable or parameter is
out of its valid range.
6. ReferenceError: It creates an instance for the error that occurs when an invalid reference is de-
referenced.
7. SyntaxError: An instance is created for the syntax error that may occur while parsing the eval().
8. TypeError: When a variable is not a valid type, an instance is created for such an error.
9. URIError: An instance is created for the error that occurs when invalid parameters are passed in
encodeURI() or decodeURI().
The try...catch...finally Statement
The latest versions of JavaScript added exception handling capabilities. JavaScript
implements the try...catch...finally construct as well as the throw operator to
handle exceptions.
❖ The try statement lets you test a block of code for errors.
❖ The catch statement lets you handle the error.
❖ The throw statement lets you create custom errors.
❖ The finally statement lets you execute code, after try and catch, regardless of
the result.
You can catch programmer-generated and runtime exceptions, but you cannot
catch JavaScript syntax errors.
Here is the try...catch...finally block syntax −
The try block must be followed by either exactly one catch block
or one finally block (or one of both). When an exception
occurs in the try block, the exception is placed in e and the catch
block is executed. The optional finally block executes
unconditionally after try/catch.
<!DOCTYPE html> try
<html> {
<body> if(x == "") throw "is empty";
<p>Please input a number between 5 and if(isNaN(x)) throw "is not a number";
10:</p> x =Number(x); if(x > 10) throw "is too high"; if(x <
5) throw "is too low";
}
<input id="demo" type="text">
catch(err)
<button type="button"
onclick="myFunction()">Test {
Input</button> [Link] = "Input " + err;
}
<p id="p01"></p> finally
{
You can use throw statement to raise your built-in exceptions or your customized
exceptions. Later these exceptions can be captured and you can take an appropriate
action.
Built-in Objects
Built-in objects are not related to any Window or DOM object model.
These objects are used for simple data processing in the JavaScript
1) Date
2) Math
3) String, Number, Boolean
4) RegExp
5) window (Global Obejct)
1) Math Object
Math object is a built-in static object.
It is used for performing complex math operations.
Math Properties
Math Description
Property
SQRT2 Returns square root of 2.
PI Returns Π value.
E\ Returns Euler's Constant.
LN2 Returns natural logarithm of 2.
LN10 Returns natural logarithm of 10.
LOG2E Returns base 2 logarithm of E.
LOG10E Returns 10 logarithm of E.
Math Methods
Methods Description
abs() Returns the absolute value of a number.
acos() Returns the arccosine (in radians) of a number.
ceil() Returns the smallest integer greater than or equal to a number.
cos() Returns cosine of a number.
floor() Returns the largest integer less than or equal to a number.
log() Returns the natural logarithm (base E) of a number.
EXAMPLE:
<html>
Output
<head>
<title>JavaScript Math Object Methods</title>
ABS Test Value : 20
</head>
<body> ACOS Test Value :
<script type="text/javascript"> 3.14159265358979
var value = [Link](20); ASIN Test Value :
[Link]("ABS Test Value : " + value +"<br>"); 1.57079632679482
ATANTest
var value = [Link](-1); Value:
[Link]("ACOS Test Value : " + value +"<br>"); 0.46364760900080
</script>
</center>
</body>
</html>
String Object
Properties Description
length It returns the length of the string.
prototype It allows you to add properties and methods to an
object.
construct It returns the reference to the String function that
or created the object.
String Methods
Methods Description
Syntax
Use the following syntax to create a boolean
object. var val = new Boolean(value);
Method Description
DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML.
Dynamic HTML is not a markup or programming language but it is a term that
combines the features of various web development technologies for creating the web
pages dynamic and interactive.
Components of Dynamic HTML
DHTML consists of the following four components or languages:
o HTML 4.0
o CSS
o JavaScript
o DOM.
HTML 4.0
HTML is a client-side markup language, which is a core component of the DHTML. It
defines the structure of a web page with various defined basic elements or tags.
CSS
CSS stands for Cascading Style Sheet, which allows the web users or developers for
controlling the style and layout of the HTML elements on the web pages.
JavaScript
JavaScript is a scripting language which is done on a client-side. The various
browser supports JavaScript technology. DHTML uses the JavaScript technology
for accessing, controlling, and manipulating
DOM
DOM is the document object model. It is a w3c standard, which is a
standard interface of programming for HTML. It is mainly used for
defining the objects and properties of all elements in HTML.
Uses of DHTML
✓ It is used for designing the animated and interactive web pages that are developed in real-
time.
✓ DHTML helps users by animating the text and images in their documents.
✓ It allows the authors for adding the effects on their pages.
✓ It also allows the page authors for including the drop-down menus or rollover buttons.
✓ This term is also used to create various browser-based action games.
✓ It is also used to add the ticker on various websites, which needs to refresh their
content automatically.
HTML (Hypertext Markup language) DHTML (Dynamic Hypertext Markup
language)
2. It is used for developing and creating 2. It is used for creating and designing the
web pages. animated and interactive
web sites or pages.
3. This markup language creates static web 3. This concept creates dynamic web pages.
pages.
4. It does not contain any server-side 4. It may contain the code of server-
6. A simple page which is created by a user 6. A page which is created by a user using the
without using the scripts or styles called as an HTML, CSS, DOM, and JavaScript technologies
HTML page. called a DHTML page.
7. This markup language does not need 7. This concept needs database connectivity
database connectivity. because it interacts with users.
Example: Webpage using DHTML (HTML + DOM + CSS + JavaScript)
<html>
<head>
<title>
changes the particular HTML element example
</title>
</head>
<body>
<p id="demo"> This text changes color when click on the following different buttons. </p>
<button onclick="change_Color('green');"> Green </button>
<button onclick="change_Color('blue');"> Blue </button>
<script type="text/javascript">
Function change_Color(newColor)
{
var element = [Link]('demo').[Link] = newColor;
}
</script>
</body>+
</html>
JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format.
It is based on a text format that is easy for humans to read/write and easy for machines
to parse/generate.
JSON is language-independent, but it uses conventions familiar to C, C++, Java, and
JavaScript.
Widely used in APIs, web services, and data storage.
1. JSON Syntax
{
"student": {
"name": "Ravi",
"age": 21,
"marks": [85, 90, 92],
"isPassed": true
}
}
JSON Syntax Rules
JSON syntax is derived from JavaScript object notation syntax:
❖ JSON Values
In JSON, values must be one of the following data types:
• a function
• a date
• undefined
JSON Functions in JavaScript
JavaScript provides two main functions:
[Link]. parse() → Converts JSON string into a JavaScript object.
// Output: {"name":"Ravi","age":21}