0% found this document useful (0 votes)
10 views49 pages

JavaScript Basics and Applications Guide

JavaScript is a lightweight, object-oriented programming language primarily used for creating interactive websites and enhancing HTML documents. It supports both client-side and server-side scripting, allowing for dynamic content and user interaction. The document also covers JavaScript syntax, variable declaration, functions, arrays, and various methods for displaying data.

Uploaded by

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

JavaScript Basics and Applications Guide

JavaScript is a lightweight, object-oriented programming language primarily used for creating interactive websites and enhancing HTML documents. It supports both client-side and server-side scripting, allowing for dynamic content and user interaction. The document also covers JavaScript syntax, variable declaration, functions, arrays, and various methods for displaying data.

Uploaded by

Samson K
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Dr. M.

SURESH
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
JavaScript (js)
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.
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box), Displaying clocks etc.

Example: Type attribute


<script type=“text/javascript”>
[Link](“welcome”);
</script>
The 'type' attribute indicates which script language you are using with the type attribute.

Example: Language attribute


<script language=“javascript”>
[Link](“welcome”);
</script>
You can also specify the <script language> using the 'language' attribute.

Example:
<script>
[Link](“welcome”);
</script>
You can also specify the <script > without specifying language.

Types of Scripts
[Link]-SideScripting
[Link]-SideScripting

1. 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.
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
Operation of Client-Side Scripting

In the above diagram,


 The user requests a web page from the server.
 The server finds the page and sends it to the user.
 The page is displayed on the browser with any scripts running during or after the
display.
 Client-Side scripting is used to make web page changes after they arrive at the
browser.
 These scripts rely on the user's computer. If the computer is slow, then they may run
slow.
 These scripts may not run at all if the browser does not understand the scripting
language.
2. Server-Side Scripting
 Server-Side Scripting is used in web development.
 The server-side environment runs a scripting language which is called a web server.
 Server-Side Scripting is used to provide interactive web sites.
 It is different from Client-Side Scripting where the scripts are run by viewing the web
browser, usually in JavaScript.
 It is used for allowing the users to have individual accounts and providing data from
databases.
 It allows a level of privacy, personalization and provision of information that is very
useful.
 It includes [Link] and PHP.
 It does not rely on the user having specific browser or plug-in.
 It is affected by the processing speed of the host server.
Operation of Server-Side Scripting

In the above diagram,


Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
 The client requests a web page from the server.
 The script in the page is interpreted by the server, creating or changing the page
content to suit the user (client) and the passing data around.
 The page in its final form is sent to the user(client) and then cannot be changed using
Server-Side Scripting.
 Server-Side Scripting tends to be used for allowing the users to have individual
accounts and provides data from the databases.
 These scripts are never seen by the user.
 Server-Side script runs on the server and generate results which are sent to the user.
 Running all the scripts puts a lot of load onto a server but not on the user's system.

The <script> Tag


In HTML, JavaScript code is inserted between <script> and </script> tags.
<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>
[Link]("Hello JavaScript ");
</script>
</body>
</html>

To access an HTML element, JavaScript can use the [Link](id) method.


The id attribute defines the HTML element. The innerHTML property defines the HTML
content:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Welcome to VIT Bhopal";
</script>
</body>
</html>

The var keyword for variable declaration


<!DOCTYPE html>
<html>
<body>
<h2>Welcome</h2>
<p id="yes"></p>
<script>
var a, b, c;
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
a = 2;
b = 3;
c = a + b;
[Link](
"yes").innerHTML =
"The value of c is " + c + ".";
</script>
</body>
</html>

The let keyword for variable declaration

Variables declared with let have Block Scope


Example:
{
let x = 2;
}
// x can NOT be used here

Variables declared with let must be Declared before use

Variables declared with let cannot be Redeclared in the same scope


Example
<!DOCTYPE html>
<html>
<body>
<h2>Redeclaring a Variable Using let</h2>

<p id="demo"></p>
<script>
let x = 10;
// Here x is 10
let x = 2;
// Here x is 2
[Link]("demo").innerHTML = x;
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h2>Redeclaring a Variable Using var</h2>
<p id="demo"></p>
<script>
var x = 10;
// Here x is 10
var x = 2;
// Here x is 2
[Link]("demo").innerHTML = x;
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
</script>
</body>
</html>

Places to put JavaScript code


1. Between the body tag of html

<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>
[Link]("Hello JavaScript ");
</script>
</body>
</html>

2. Between the head tag of html

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

3. In .js file (external javaScript)

[Link]
function msg(){
alert("Hello Javascript");
}

<html>
<head>
<script type="text/javascript" src="[Link]"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<title>Prompt Example</title>
</head>
<body>

<script>
let name = prompt("Enter your name:");
[Link]("Hello " + name + "!");
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<title>Add Numbers using Prompt</title>
</head>
<body>

<script>
let num1 = prompt("Enter first number:");
let num2 = prompt("Enter second number:");
let sum = parseFloat(num1) + parseFloat(num2);
[Link]("The sum is: " + sum);
</script>

</body>
</html>

<!DOCTYPE html>
<html>
<head>
<title>Prompt with Condition</title>
</head>
<body>
<script>
let age = prompt("Enter your age:");
if (age >= 18) {
[Link]("You are eligible to vote!");
} else {
[Link]("You are not eligible to vote.");
}
</script>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY

</body>
</html>

JavaScript Display Possibilities


JavaScript can "display" data in different ways:
 Writing into an HTML element, using innerHTML.
 Writing into the HTML output using [Link]().
 Writing into an alert box, using [Link]().
 Writing into the browser console, using [Link]().

<!DOCTYPE html>
<html>
<body>

<h2>My First Web Page</h2>


<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = 5 + 6;
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<p>Never call [Link] after the document has finished loading.
It will overwrite the whole document.</p>
<script>
[Link](“hi”);
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<script>
[Link](“hi”);
</script>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
</body>
</html>

<html>
<body>
<script>
var a=10;
var b=20;
var c=a+b;//It adds values of a and b variable
[Link](c);//prints sum of 10 and 20
</script>
</body>
</html>

<html>
<body>
<script>
/* It is multi line comment.
It will not be displayed */
[Link]("example of javascript multiline comment");
</script>
</body>
</html>

//Variables
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
[Link](z);
</script>
</body>
</html>

<html>
<body>
<script>
var a=20;
if(a>10){
[Link]("value of a is greater than 10");
}
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
[Link](result);
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
[Link](i + "<br/>")
}
</script>
</body>
</html>

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).

Function
 Function is a reusable code-block that will be executed whenever it is called.
 Function is a great time saver.
 It is used for performing repetitive tasks where you can call the same function
multiple times to get the same effect.
 It allows code reusability.
 JavaScript provides number of built-in functions.
Common Built-in Functions
Functions Description
isNan() Returns true, if the object is Not a Number.
Returns false, if the object is a number.
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
parseFloat If the string begins with a number, the function reads through the string until it finds the
(string) 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 until it finds
(string) 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.
Syntax:
function function_name()
{
//Code;
}

Example:
<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
</body>
</html>

<html>
<body>
<script>
function getInfo(){
return "hello How r u?";
}
</script>
<script>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
[Link](getInfo());
</script>
</body>
</html>

<html>
<body>
<script type="text/javascript">
function getcube(){
var number=[Link]("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
</script>
</body>
</html>

<html>
<body>
<script type="text/javascript">
function add() // Function Declaration
{
var a = 2,b = 3;
var sum = 0;
sum = a+b;
[Link]("<b>Addition: </b>"+sum);
}
</script>
<p> Click the Button</p>
<input type="button" onClick="add()" value="Click"> //add() - Calling Function
</body>
</html>

Array
An array is an object that can store multiple values at once. For example,
const words = ['hello', 'world', 'welcome'];
Here, words is an array. The array is storing 3 values.

Syntax:
const array_name = [item1, item2, ...];

Create an Array

You can create an array using two ways:


Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
1. Using an array literal
The easiest way to create an array is by using an array literal [].
For example, let array1 = ["eat", "sleep"];
var array2 = ["apple", "orange"];
const array3 = ["day", "night"];

2. Using the new keyword


You can also create an array using JavaScript's new keyword.
const array2 = new Array("eat", "sleep");
In both of the above examples, we have created an array having two elements.

Note: It is recommended to use array literal to create an array.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<p id="demo"></p>
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<[Link];i++){
[Link](emp[i] + "<br/>");
[Link]("demo").innerHTML = emp;
} </script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<script>
let colors = new Array("red", "green", "blue");
[Link](colors);</script>
</body>
</html>

Here are more examples of arrays:


// empty array const myList = [ ];
// array of numbers const numberArray = [ 2, 4, 6, 8];
// array of strings const stringArray = [ 'eat', 'work', 'sleep'];
// array with mixed data types const newData = ['work', 'exercise', 1, true];

You can also store arrays, functions and other objects inside an array. For example,
const newData = [ {'task1': 'exercise'}, [1, 2 ,3], function hello() { [Link]('hello')} ];

Access Elements of an Array


You can access elements of an array using indices (0, 1, 2 …).
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
For example, const myArray = ['h', 'e', 'l', 'l', 'o']; // first element [Link](myArray[0]); //
"h" // second element [Link](myArray[1]); // "

Array indexing in JavaScript

Note: Array's index starts with 0, not 1.

Add an Element to an Array

You can use the built-in method push() and unshift() to add elements to an array.

The push() method adds an element at the end of the array. For example,

let dailyActivities = ['eat', 'sleep']; // add an element at the end


[Link]('exercise'); [Link](dailyActivities); // ['eat', 'sleep', 'exercise']
The unshift() method adds an element at the beginning of the array. For example,

let dailyActivities = ['eat', 'sleep']; //add an element at the start [Link]('work');


[Link](dailyActivities); // ['work', 'eat', 'sleep']

Change the Elements of an Array

You can also add elements or change the elements by accessing the index value.

let dailyActivities = [ 'eat', 'sleep']; // this will add the new element 'exercise' at the 2 index
dailyActivities[2] = 'exercise'; [Link](dailyActivities); // ['eat', 'sleep', 'exercise']

Suppose, an array has two elements. If you try to add an element at index 3 (fourth element),
the third element will be undefined. For example,

let dailyActivities = [ 'eat', 'sleep']; // this will add the new element 'exercise' at the 3 index
dailyActivities[3] = 'exercise'; [Link](dailyActivities); // ["eat", "sleep", undefined,
"exercise"]

Basically, if you try to add elements to high indices, the indices in between will have
undefined value.

Remove an Element from an Array

You can use the pop() method to remove the last element from an array. The pop() method
also returns the returned value. For example,

let dailyActivities = ['work', 'eat', 'sleep', 'exercise']; // remove the last element
[Link](); [Link](dailyActivities); // ['work', 'eat', 'sleep'] // remove the last
element from ['work', 'eat', 'sleep'] const removedElement = [Link](); //get
removed element [Link](removedElement); // 'sleep' [Link](dailyActivities); //
['work', 'eat']

If you need to remove the first element, you can use the shift() method. The shift() method
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
removes the first element and also returns the removed element. For example,

let dailyActivities = ['work', 'eat', 'sleep']; // remove the first element [Link]();
[Link](dailyActivities); // ['eat', 'sleep']

Array length

You can find the length of an element (the number of elements in an array) using
the length property. For example,

const dailyActivities = [ 'eat', 'sleep']; // this gives the total number of elements in an array
[Link]([Link]); // 2

Array Methods

In JavaScript, there are various array methods available that makes it easier to perform useful
calculations.

Some of the commonly used JavaScript array methods are:

[Link](...items) – adds items to the end,


[Link]() – extracts an item from the end,
[Link]() – extracts an item from the beginning,
[Link](...items) – adds items to the beginning.

<html>
<body>
<script>
// Adding elements at the end of an array
// Declaring and initializing arrays
var arr = [ 10, 20, 30, 40, 50 ];
[Link](arr)
[Link]("After push <br>");
// push()
[Link](60);
[Link](arr)
[Link]("<br>");
// We can pass multiple parameters to the push()
// [10, 20, 30, 40, 50, 60, 70, 80, 90]
[Link](70, 80, 90);
[Link](1, 2);
[Link](arr+"<br>");
[Link]([Link]());
[Link](arr)
[Link]("<br>");
[Link]([Link]());
</script>
</body></html>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY

Methods Description

concat() It returns a new array object that contains two or more merged arrays.

copywithin() It copies the part of the given array with its own elements and returns the
modified array.

entries() It creates an iterator object and a loop that iterates over each key/value
pair.

every() It determines whether all the elements of an array are satisfying the
provided function conditions.

flat() It creates a new array carrying sub-array elements concatenated


recursively till the specified depth.

flatMap() It maps all array elements via mapping function, then flattens the result
into a new array.

fill() It fills elements into an array with static values.

from() It creates a new array carrying the exact copy of another array element.

filter() It returns the new array containing the elements that pass the provided
function conditions.

find() It returns the value of the first element in the given array that satisfies the
specified condition.

findIndex() It returns the index value of the first element in the given array that
satisfies the specified condition.

forEach() It invokes the provided function once for each element of an array.

includes() It checks whether the given array contains the specified element.

indexOf() It searches the specified element in the given array and returns the index
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY

of the first match.

isArray() It tests if the passed value ia an array.

join() It joins the elements of an array as a string.

keys() It creates an iterator object that contains only the keys of the array, then
loops through these keys.

lastIndexOf() It searches the specified element in the given array and returns the index
of the last match.

map() It calls the specified function for every array element and returns the new
array

of() It creates a new array from a variable number of arguments, holding any
type of argument.

pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

reduce(function, It executes a provided function for each value from left to right and
initial) reduces the array to a single value.

reduceRight() It executes a provided function for each value from right to left and
reduces the array to a single value.

some() It determines if any element of the array passes the test of the
implemented function.

shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the given array.

sort() It returns the element of the given array in a sorted order.


Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY

splice() It add/remove elements to/from the given array.

toLocaleString() It returns a string containing all the elements of a specified array.

toString() It converts the elements of a specified array into string form, without
affecting the original array.

unshift() It adds one or more elements in the beginning of the given array.

values() It creates a new iterator object carrying values for each index in the array.

Example: JavaScript Array Methods

let dailyActivities = ['sleep', 'work', 'exercise'];


// sorting elements in the alphabetical order
[Link]();
[Link](dailyActivities); // ['exercise', 'sleep', 'work']
//finding the index position of string const position = [Link]('work');
[Link](position); // 2 // slicing the array elements const newDailyActivities =
[Link](1); [Link](newDailyActivities); // [ 'sleep', 'work'] // concatenating
two arrays const routine = [Link](newRoutine); [Link](routine); //
["exercise", "sleep", "work", "eat"]

Note: If the element is not in an array, indexOf() gives -1.

Working of JavaScript Arrays


In JavaScript, an array is an object. And, the indices of arrays are objects keys.

Since arrays are objects, the array elements are stored by reference. Hence, when an array
value is copied, any change in the copied array will also reflect in the original array. For
example,

let arr = ['h', 'e']; let arr1 = arr; [Link]('l'); [Link](arr); // ["h", "e", "l"]
[Link](arr1); // ["h", "e", "l"]
You can also store values by passing a named key in an array. For example,

let arr = ['h', 'e']; [Link] = 'John'; [Link](arr); // ["h", "e"] [Link]([Link]); //
"John" [Link](arr['name']); // "John"

Array indexing in JavaScript

However, it is not recommended to store values by passing arbitrary names in an array.


Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
Hence in JavaScript, you should use an array if values are in ordered collection. Otherwise
it's better to use object with { }.
const person = {firstName:"John", lastName:"Doe", age:46};
script>

// Create one dimensional array


var arr = new Array(3);
// Loop to create 2D array using 1D array
[Link]("Creating 2D array <br>");
for (var i = 0; i < [Link]; i++) {

arr[i] = [];

let n = [9,5,4,3,7];
let x = n;
n = [];
[Link](x);
//Input for one dimensional array

var myarr=[];
var size = 5; // Array size
for(var a=0; a<size; a++)
{

myinputarr[a] = prompt('Enter array Element ' + (a+1));


}

<!DOCTYPE html>
<html>
<head>
<title>
How to take array input using JavaScript
</title>
</head>
<body style="text-align: center;">
<form>
<h1>Please enter data</h1>
<br>
<label for="Name">Name</label>
<input id="name" type="text">
<br>
<br>
<label for="Age">Age</label>
<input id="age" type="text">
<br>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
<br>
<label for="city">City</label>
<input id="City" type="text">
<br>
<br>
<input type="button" value="Save" onclick="savedata()">
<input type="button" value="Show data" onclick="displayData()">
<br>
</form>
<div id="display"></div>
<script type="text/javascript">
var arrCitys=new Array();
var arrNames=new Array();
var arrAges=new Array();
function savedata(){
var name = [Link]('name').value;
var city = [Link]('City').value;
var age = [Link]('age').value;
arrNames[[Link]]=name;
arrCitys[[Link]]=city;
arrAges[[Link]]=age; }
function displayData()
{
var content="<b>Data Entered by User :</b><br>";
content+= [...arrNames]+"</br>";
content+=[...arrAges]+"</br>";
content+=[...arrCitys]+"</br>";
[Link]('display').innerHTML = content;
}
</script>
</body>
</html>

Transpose Matrix
<html>
<head> <h3>Matrix Transpose</h3></head>
<body>
<script>
var r=prompt('Enter row value..: ' );
var c=prompt('Enter column value...: ' );
var arr = [];
for (var i = 0; i< r; i++) {
for(var j = 0; j< c; j++) {
arr[i] = [];
}
}
for (var i = 0; i < r; i++) {
for (var j = 0; j <c; j++) {
arr[i][j] = prompt('Enter array Element...: ' );
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
}
}

[Link]("Matrix before transpose"+"<br>");


for (var i = 0; i< r; i++) {
for(var j = 0; j< c; j++) {
[Link](arr[i][j]+" ");
}[Link]("<br>");
}

[Link]("Matrix After transpose"+"<br>");


for (var i = 0; i< r; i++) {
for(var j = 0; j< c; j++) {
[Link](arr[j][i]+" ");
}[Link]("<br>");
}
</script>
</body>
</html>

Functions Example
1.<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation, and returns the result:</p>

<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
[Link]("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>

2. <!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
var x = myFunction(4, 3);
[Link]("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
</body>
</html>

3. <!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>Accessing a function without () will return the function definition instead of the function
result:</p>
<p id="demo"></p>
<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
[Link]("demo").innerHTML = toCelsius;
</script>
</body>
</html>

4.<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>

<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "xyz",
lastName: "klm",
age: 20,
eyeColor: "black"
};
// Display some data from the object:
[Link]("demo").innerHTML =
[Link] + " is " + [Link] + " years old.";
</script>

</body>
</html>

JavaScript HTML DOM


With the HTML DOM, JavaScript can access and change all the elements of an HTML
document.

What is the DOM?


The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
"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."
The W3C DOM standard is separated into 3 different parts:
 Core DOM - standard model for all document types
 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents

What is the HTML DOM?


The HTML DOM is a standard object model and programming interface for HTML. It
defines:
 The HTML elements as objects
 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML
elements.

HTML DOM methods are actions you can perform (on HTML Elements).
HTML DOM properties are values (of HTML Elements) that you can set or change.
<!DOCTYPE html>
<html>
<body>
<h2>My First Page</h2>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hello World!";
</script>
</body>
</html>

In the example above the getElementById method used id="demo" to find the element.
The innerHTML property is useful for getting or replacing the content of HTML elements.

The HTML DOM Document Object


The document object represents your web page.
If you want to access any element in an HTML page, you always start with accessing the
document object.
Below are some examples of how you can use the document object to access and manipulate
HTML.

Finding HTML Elements

Method Description

[Link](id) Find an element by element id

[Link](name) Find elements by tag name


Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY

[Link](name) Find elements by class name

Changing HTML Elements


Property Description

[Link] = new html content Change the inner HTML of an element

[Link] = new value Change the attribute value of an HTML element

[Link] = new style Change the style of an HTML element

Method Description

[Link](attribute, value) Change the attribute value of an HTML element

Adding and Deleting Elements


Method Description

[Link](element) Create an HTML element

[Link](element) Remove an HTML element

[Link](element) Add an HTML element

[Link](new, old) Replace an HTML element

[Link](text) Write into the HTML output stream

Adding Events Handlers


Method Description

[Link](id).onclick = function(){code} Adding event handler code to an


onclick event

<html>
<body>
<p id="p2">Hello World!</p>
<script>
[Link]("p2").[Link] = "blue";
</script>
</body>
</html>

JavaScript Objects
Example:
[Link] person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
[Link] person = {};
// Add Properties
[Link] = "John";
[Link] = "Doe";
[Link] = 50;
[Link] = "blue";

3. // Create an Object
const person = new Object();

// Add Properties
[Link] = "John";
[Link] = "Doe";
[Link] = 50;
[Link] = "blue";

<!DOCTYPE html>
<html>
<body>
<h1>Creating JavaScript Objects</h1>
<h2>Using an Object Literal</h2>
<p id="demo"></p>
<script>
// Create an Object:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

// Display Data from the Object:


[Link]("demo").innerHTML =
[Link] + " is " + [Link] + " years old.";
</script>
</body>
</html>

Built-in Objects

 These objects are used for simple data processing in the JavaScript.

1. Math Object
 Math object is a built-in static object.
 It is used for performing complex math operations.

Methods Description
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
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.
max() Returns the largest of zero or more numbers.
min() Returns the smallest of zero or more numbers.
pow() Returns base to the exponent power, that is base exponent.
Math Methods

Date Object
 Date is a data type.
 Date object manipulates date and time.
 Date() constructor takes no arguments.
 Date object allows you to get and set the year, month, day, hour, minute, second and
millisecond fields.
Syntax:
var variable_name = new Date();

Example:
var current_date = new Date();

Date Methods

Methods Description
Date() Returns current date and time.
getDate() Returns the day of the month.
getDay() Returns the day of the week.
getFullYear() Returns the year.
getHours() Returns the hour.
getMinutes() Returns the minutes.
getSeconds() Returns the seconds.
getMilliseconds() Returns the milliseconds.
getTime() Returns the number of milliseconds since January 1, 1970 at
12:00 AM.

getTimezoneOffset() Returns the timezone offset in minutes for the current locale.
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
getMonth() Returns the month.
setDate() Sets the day of the month.
setFullYear() Sets the full year.
setHours() Sets the hours.
setMinutes() Sets the minutes.
setSeconds() Sets the seconds.
setMilliseconds() Sets the milliseconds.
setTime() Sets the number of milliseconds since January 1, 1970 at
12:00 AM.

setMonth() Sets the month.


toDateString() Returns the date portion of the Date as a human-readable
string.
toLocaleString() Returns the Date object as a string.
toGMTString() Returns the Date object as a string in GMT timezone.
valueOf() Returns the primitive value of a Date object.

3. String Object
 String objects are used to work with text.
 It works with a series of characters.
Syntax:
var variable_name = new String(string);

Example:
var s = new String(string);

String Properties

Properties Description
Length It returns the length of the string.
prototype It allows you to add properties and methods to an object.
constructor It returns the reference to the String function that created the object.

String Methods

Methods Description
charAt() It returns the character at the specified index.
charCodeAt() It returns the ASCII code of the character at the specified position.
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
concat() It combines the text of two strings and returns a new string.
indexOf() It returns the index within the calling String object.
match() It is used to match a regular expression against a string.
replace() It is used to replace the matched substring with a new substring.
search() It executes the search for a match between a regular expression.
slice() It extracts a session of a string and returns a new string.
split() It splits a string object into an array of strings by separating the string into
the substrings.

toLowerCase() It returns the calling string value converted lower case.


toUpperCase() Returns the calling string value converted to uppercase.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p id="demo"></p>
<script>
let text = "Vit Bhopal University";
let n = [Link](/Univ/i);
[Link]("demo").innerHTML = n;
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<button onclick="replacefunc()">Try it</button>
<p id="demo">Welcome to VIT Bhopal University</p>
<script>
function replacefunc() {
let text = [Link]("demo").innerHTML;
[Link]("demo").innerHTML =
[Link](/u/i, "InterNational U");
}
</script>

</body>
</html>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p>Do a global search for "is" in a string:</p>
<p id="demo"></p>
<script>
let text = "Is 12 all 1212?";
let result = [Link](/12/g);
[Link]("demo").innerHTML = result;
</script>
</body>
</html>

Validation
<html>
<body>
<script>
function validateform(){
var name=[Link];
var password=[Link];

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

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function matchpass(){
var firstpassword=[Link];
var secondpassword=[Link];

if(firstpassword==secondpassword){
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>
</head>
<body>
<form name="f1" action="[Link]" onsubmit="return matchpass()">
Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>

</body>
</html>

<!DOCTYPE html>
<html>
<head>
<script>
function validate(){
var num=[Link];
if (isNaN(num)){
[Link]("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
</head>
<body>
<form name="myform" action="[Link]" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>
</body>
</html>

<html lang="en">
<head>
<title>Form validation</title>
<script>
function printError(elemId, hintMsg) {
[Link](elemId).innerHTML = hintMsg;
}
function validateForm() {
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
var name = [Link];
var email = [Link];
var mobile = [Link];
var country = [Link];
var gender = [Link];
var hobbies = [];
var checkboxes = [Link]("hobbies[]");
for(var i=0; i < [Link]; i++) {
if(checkboxes[i].checked) {
[Link](checkboxes[i].value);
}
}
var nameErr = emailErr = mobileErr = countryErr = genderErr = true;
if(name == "") {
printError("nameErr", "Please enter name");
} else {
var regex = /^[a-zA-Z\s]+$/;
if([Link](name) === false) {
printError("nameErr", "Enter valid name");
} else {
printError("nameErr", "");
nameErr = false;
}
}
if(email == "") {
printError("emailErr", "enter your email");
} else {
var regex = /^\S+@\S+\.\S+$/;
if([Link](email) === false) {
printError("emailErr", "Please enter a valid email");
} else{
printError("emailErr", "");
emailErr = false;
}
}
if(mobile == "") {
printError("mobileErr", "Please enter mobile number");
} else {
var regex = /^[1-9]\d{9}$/;
if([Link](mobile) === false) {
printError("mobileErr", "Please enter a valid mobile number");
} else{
printError("mobileErr", "");
mobileErr = false;
}
}
if(country == "Select") {
printError("countryErr", "Please select country");
} else {
printError("countryErr", "");
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
countryErr = false;
}
if(gender == "") {
printError("genderErr", "Please select gender");
} else {
printError("genderErr", "");
genderErr = false;
}
if((nameErr || emailErr || mobileErr || countryErr || genderErr) == true) {
return false;
} else {
var dataPreview = "You've entered the following details: \n" +
"Full Name: " + name + "\n" +
"Email Address: " + email + "\n" +
"Mobile Number: " + mobile + "\n" +
"Country: " + country + "\n" +
"Gender: " + gender + "\n";
if([Link]) {
dataPreview += "Hobbies: " + [Link](", ");
}
alert(dataPreview);
}
};
</script>
</head>
<body>
<form name="contactForm" onsubmit="return validateForm()"
action="/examples/actions/[Link]" method="post">
<h2>Application Form</h2>
<div class="row">
<label>Full Name</label>
<input type="text" name="name">
<div class="error" id="nameErr"></div>
</div>
<div class="row">
<label>Email Address</label>
<input type="text" name="email">
<div class="error" id="emailErr"></div>
</div>
<div class="row">
<label>Mobile Number</label>
<input type="text" name="mobile" maxlength="10">
<div class="error" id="mobileErr"></div>
</div>
<div class="row">
<label>Country</label>
<select name="country">
<option>Select</option>
<option>Australia</option>
<option>India</option>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
<option>United States</option>
<option>United Kingdom</option>
</select>
<div class="error" id="countryErr"></div>
</div>
<div class="row">
<label>Gender</label>
<div class="form-inline">
<label><input type="radio" name="gender" value="male"> Male</label>
<label><input type="radio" name="gender" value="female"> Female</label>
</div>
<div class="error" id="genderErr"></div>
</div>
<div class="row">
<label>Hobbies <i>(Optional)</i></label>
<div class="form-inline">
<label><input type="checkbox" name="hobbies[]" value="sports"> Sports</label>
<label><input type="checkbox" name="hobbies[]" value="movies"> Movies</label>
<label><input type="checkbox" name="hobbies[]" value="music"> Music</label>
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</form>
</body>
</html>

Regular Expressions

A regular expression is a sequence of characters that forms a search pattern.


Regular expressions can be used to perform all types of text search and text replace
operations.

Syntax:

/pattern/modifiers;

Regular Expression Patterns


Brackets are used to find a range of characters:
Expression Description

[abc] Find any of the characters between the brackets

[0-9] Find any of the digits between the brackets


Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY

(x|y) Find any of the alternatives separated with |

Regular Expression Modifiers


Modifiers can be used to perform case-insensitive more global searches:
Modifier Description

I Perform case-insensitive matching

G Perform a global match (find all)

M Perform multiline matching

D Perform start and end matching

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p id="demo"></p>
<script>
let text = "Vit University!";
let n = [Link](/VIT/i);
[Link]("demo").innerHTML = n;
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Regex Example</title>
</head>
<body>
<script>
let text = "I love JavaScript!";
let pattern = /JavaScript/; // Regular Expression
let result = [Link](text); // test() returns true or false
[Link]("Pattern found: " + result);
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
<title>Find Digits</title>
</head>
<body>
<script>
let text = "My roll number is 12345 and ID is 6789.";
let digits = [Link](/\d+/g); // \d+ means one or more digits
[Link]("Digits found: " + digits);
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<title>Replace using Regex</title>
</head>
<body>
<script>
let text = "I love JavaScript. JavaScript is fun!";
let newText = [Link](/JavaScript/g, "Python"); // g = global
[Link](newText);
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit vit</p>
<script>
function myFunction() {
let text = [Link]("demo").innerHTML;
[Link]("demo").innerHTML =
[Link](/vit/i, "vit university");
}
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p id="demo"></p>
<script>
let text = "Is this all there is?";
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
let result = [Link](/[he]/g);
[Link]("demo").innerHTML = result;
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p id="demo"></p>
<script>
let text = "Rs.1000";
let result = [Link](/\d/g);
[Link]("demo").innerHTML = result;
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p>Search for an "e" in the next paragraph:</p>
<p id="para1">The best things in life are free!</p>
<p id="demo"></p>
<script>
let text = [Link]("para1").innerHTML;
const pattern = /o/;
[Link]("demo").innerHTML = [Link](text);
</script>
</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.
Mouse events:

Event Performed Event Handler Description

Click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY

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

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
1. <html>
2. <head> Javascript Events </head>
3. <body>
4. <script language="Javascript" type="text/Javascript">
5. <!--
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
6. function clickevent()
7. {
8. [Link]("This is Javascript");
9. }
10. //-->
11. </script>
12. <form>
13. <input type="button" onclick="clickevent()" value="Who's this?"/>
14. </form>
15. </body>
16. </html>

MouseOver Event
1. <html>
2. <head>
3. <h1> Javascript Events </h1>
4. </head>
5. <body>
6. <script language="Javascript" type="text/Javascript">
7. <!--
8. function mouseoverevent()
9. {
10. alert("This is Javascript");
11. }
12. //-->
13. </script>
14. <p onmouseover="mouseoverevent()"> Keep cursor over me</p>
15. </body>
16. </html>

Focus Event
1. <html>
2. <head> Javascript Events</head>
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onfocus="focusevent()"/>
6. <script>
7. <!--
8. function focusevent()
9. {
10. [Link]("input1").[Link]=" aqua";
11. }
12. //-->
13. </script>
14. </body>
15. </html>

Keydown Event
1. <html>
2. <head> Javascript Events</head>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onkeydown="keydownevent()"/>
6. <script>
7. <!--
8. function keydownevent()
9. {
10. [Link]("input1");
11. alert("Pressed a key");
12. }
13. //-->
14. </script>
15. </body>
16. </html>

Load event
1. <html>
2. <head>Javascript Events</head>
3. </br>
4. <body onload="[Link]('Page successfully loaded');">
5. <script>
6. <!--
7. [Link]("The page is loaded successfully");
8. //-->
9. </script>
10. </body>
11. </html>

Exception Handling in JavaScript

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.

In exception handling:
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
A throw statement is used to raise an exception. It means when an abnormal condition occurs,
an exception is thrown using throw.

The thrown exception is handled by wrapping the code into the try…catch block. If an error
is present, the catch block will execute, else only the try block statements will get executed.

Thus, in a programming language, there can be different types of errors which may disturb
the proper execution of the program.

Types of Errors

While coding, there can be three types of errors in the code:

1. Syntax Error: When a user makes a mistake in the pre-defined syntax of a


programming language, a syntax error may appear.
2. Runtime Error: When an error occurs during the execution of the program, such an
error is known as Runtime error. The codes which create runtime errors are known as
Exceptions. Thus, exception handlers are used for handling runtime errors.
3. Logical Error: An error which occurs when there is any logical mistake in the
program that may not produce the desired output, and may terminate abnormally.
Such an error is known as Logical error.

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:

1. 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.
2. InternalError: It creates an instance when the js engine throws an internal error.
3. RangeError: It creates an instance for the error that occurs when a numeric variable or
parameter is out of its valid range.
4. ReferenceError: It creates an instance for the error that occurs when an invalid
reference is de-referenced.
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
5. SyntaxError: An instance is created for the syntax error that may occur while parsing
the eval().
6. TypeError: When a variable is not a valid type, an instance is created for such an
error.
7. URIError: An instance is created for the error that occurs when invalid parameters are
passed in encodeURI() or decodeURI().

Exception Handling Statements

There are following statements that handle if any exception occurs:

o throw statements
o try…catch statements
o try…catch…finally statements.

JavaScript try…catch

A try…catch is a commonly used statement in various programming languages. Basically, it


is used to handle the error-prone part of the code. It initially tests the code for all possible
errors it may contain, then it implements actions to tackle those errors (if occur). A good
programming approach is to keep the complex code within the try…catch statements.

Let's discuss each block of statement individually:

try{} statement: Here, the code which needs possible error testing is kept within the try block.
In case any error occur, it passes to the catch{} block for taking suitable actions and handle
the error. Otherwise, it executes the code written within.

catch{} statement: This block handles the error of the code by executing the set of statements
written within the block. This block contains either the user-defined exception handler or the
built-in handler. This block executes only when any error-prone code needs to be handled in
the try block. Otherwise, the catch block is skipped.

Syntax:
1. try{
2. expression; } //code to be written.
3. catch(error){
4. expression; } // code for handling the error.
try…catch example
1. <html>
2. <head> Exception Handling</br></head>
3. <body>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
4. <script>
5. try{
6. var a= ["34","32","5","31","24","44","67"]; //a is an array
7. [Link](a); // displays elements of a
8. [Link](b); //b is undefined but still trying to fetch its value. Thus catch block will be
invoked
9. }catch(e){
10. alert("There is error which shows "+[Link]); //Handling error
11. }
12. </script>
13. </body>
14. </html>

Throw Statement

Throw statements are used for throwing user-defined errors. User can define and throw their
own custom errors. When throw statement is executed, the statements present after it will not
execute. The control will directly pass to the catch block.

Syntax:
1. throw exception;
try…catch…throw syntax
1. try{
2. throw exception; // user can define their own exception
3. }
4. catch(error){
5. expression; } // code for handling exception.

The exception can be a string, number, object, or boolean value.

throw example with try…catch


1. <html>
2. <head>Exception Handling</head>
3. <body>
4. <script>
5. try {
6. throw new Error('This is the throw keyword'); //user-defined throw statement.
7. }
8. catch (e) {
9. [Link]([Link]); // This will generate an error message
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
10. }
11. </script>
12. </body>
13. </html>

With the help of throw statement, users can create their own errors.

try…catch…finally statements

Finally is an optional block of statements which is executed after the execution of try and
catch statements. Finally block does not hold for the exception to be thrown. Any exception
is thrown or not, finally block code, if present, will definitely execute. It does not care for the
output too.

Syntax:
1. try{
2. expression;
3. }
4. catch(error){
5. expression;
6. }
7. finally{
8. expression; } //Executable code
try…catch…finally example
1. <html>
2. <head>Exception Handling</head>
3. <body>
4. <script>
5. try{
6. var a=2;
7. if(a==2)
8. [Link]("ok");
9. }
10. catch(Error){
11. [Link]("Error found"+[Link]);
12. }
13. finally{
14. [Link]("Value of a is 2 ");
15. }
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
16. </script>
17. </body>
18. </html>

JSON (JavaScript Object Notation)

JSON is a text format for storing and transporting data.


JSON is "self-describing" and easy to understand.
The JSON format is syntactically similar to the code for creating JavaScript objects. Because
of this, a JavaScript program can easily convert JSON data into JavaScript objects.
JSON Syntax Rules
JSON syntax is derived from JavaScript object notation syntax:
 Data is in name/value pairs
 Data is separated by commas
 Curly braces hold objects
 Square brackets hold arrays
JSON Example
This example is a JSON string:
'{"name":"John", "age":30, "car":null}'

JSON
{"name":"John"}
JavaScript
{name:"John"}
person = {name:"John", age:31, city:"New York"};
JSON data can easily be sent between computers, and used by any programming language.
JavaScript has a built in function for converting JSON strings into JavaScript objects:
[Link]()
JavaScript also has a built in function for converting an object into a JSON string:
[Link]()
Javascript object
<!DOCTYPE html>
<html>
<body>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
<h2>Access a JavaScript object</h2>
<p id="demo"></p>
<script>
const myObj = {name:"John", age:30, city:"New York"};
[Link]("demo").innerHTML = [Link];
</script>
</body>
</html>

JSON Object(using [Link])


<!DOCTYPE html>
<html>
<body>
<h2>Creating an Object from a JSON String</h2>
<p id="demo"></p>
<script>
const txt = '{"name":"John", "age":30, "city":"New York"}'
const obj = [Link](txt);
[Link]("demo").innerHTML = [Link] + ", " + [Link];
</script>
</body>
</html>

JS Object(using JSON. stringify)

<!DOCTYPE html>
<html>
<body>
<h2>Create a JSON string from a JavaScript object.</h2>
<p id="demo"></p>
<script>
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = [Link](obj);
[Link]("demo").innerHTML = myJSON;
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h2>Looping JavaScript Object Values</h2>
<p id="para1"></p>
<p id="para2"></p>
<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = [Link](myJSON);
let str1 = "";
let str2 = "";
for (const x in myObj) {
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
str1 += x + ", ";
str2 += myObj[x] + ", ";
}
[Link]("para1").innerHTML = str1;
[Link]("para2").innerHTML = str2;
</script>
</body>
</html>

JSON Arrays

This is a JSON string:


'["Ford", "BMW", "Fiat"]'
Inside the JSON string there is a JSON array literal:
["Ford", "BMW", "Fiat"]

JavaScript Array
<!DOCTYPE html>
<html>
<body>
<h2>Creating an Array from a Literal</h2>
<p id="demo"></p>
<script>
const myArray = ["Ford", "BMW", "Fiat"];
[Link]("demo").innerHTML = myArray;
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h2>Creating an Array from JSON</h2>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const myArray1 = ["Ford", "BMW", "Fiat"];
[Link]("demo1").innerHTML = myArray1;
const myJSON = '["Ford", "BMW", "Fiat"]';
const myArray2 = [Link](myJSON);
[Link]("demo2").innerHTML = myArray2;
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h1>Access an Array by Index</h1>
<p id="demo"></p>
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY

<script>
const myJSON = '["Ford", "BMW", "Fiat"]';
const myArray = [Link](myJSON);
[Link]("demo").innerHTML = myArray[0];
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h2>Looping an Array</h2>
<p id="demo"></p>
<script>
const myJSON = '{"cars":["Ford", "BMW", "Fiat","Benz"]}';
const myObj = [Link](myJSON);
let text = "";
for (let i in [Link]) {
text += [Link][i] + ", ";
}
[Link]("demo").innerHTML = text;
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h2>Looping an Array</h2>
<p id="demo"></p>
<script>
const myJSON = '{"cars":["Ford", "BMW", "Fiat","Benz"]}';
const myObj = [Link](myJSON);
let text = "";
for (let i = 0; i < [Link]; i++) {
text += [Link][i] + ", ";
}
[Link]("demo").innerHTML = text;
</script>
</body>
</html>

jQuery
jQuery is a lightweight open-source JavaScript library that simplifies manipulating
the Document Object Model (DOM), handling events, and creating dynamic web
experiences.
jQuery is to simplify the usage of JavaScript on websites.
jQuery simplifies complex JavaScript tasks with single-line methods, it makes your code
more readable and maintainable.
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
Include the jQuery Library:
1. Using jQuery Library Content Delivery Network (CDN) in your HTML project.
<script src="[Link]

2. Once the library is included, you can write jQuery code within <script> tags. jQuery code
typically follows a specific syntax:
<script> $(document).ready(function() { // Your jQuery code here });</script>

The $(document).ready(function() { ... }) function ensures your code executes only after the
document is fully loaded, preventing errors.

Finding HTML Element by Id


<!DOCTYPE html>
<html>
<head>
<script src="[Link]
</head>
<body>
<h2>Finding HTML Elements by Id</h2>
<p id="id01">Hello World!</p>
<p id="demo"></p>
<script>
$(document).ready(function() {
var myElements = $("#id01");
$("#demo").text("The text from the id01 paragraph is: " + myElements[0].innerHTML);
});
</script>
</body>
</html>

To change the style of heading content on mouse move over.

<!DOCTYPE html>
<html>
<head>
<script src=
"[Link]
</script>

<script>
$(document).ready(function () {
$("h1").hover(
function () {
$(this).css(
"color",
"green"
);
},
function () {
$(this).css(
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
"color",
"red"
);
}
);
});
</script>
</head>
<body>
<h1>VIT Bhopal University</h1>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<script src="[Link]
</head>
<body>
<h2>Show HTML Elements</h2>
<p id="01" style="display:none">Hello World!</p>
<p id="02" style="display:none">Hello Sweden!</p>
<p id="03" style="display:none">Hello Japan!</p>
<script>
$(document).ready(function() {
$("#02").show();
});
</script>
</body>
</html>

[Link](jquery Example)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Employee Details</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
th, td {
padding: 10px;
text-align: left;
}
Dr. [Link]
ASSISTANT PROFESSOR
VIT BHOPAL UNIVERSITY
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h2>Employee Details</h2>
<table id="employeeTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Department</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<!-- Employee details will be inserted here by jQuery -->
</tbody>
</table>
<!-- Include jQuery -->
<script src="[Link]
<script src="[Link]"></script>
</body>
</html>

[Link]
$(document).ready(function() {
var employees = [
{ id: 1, name: "John Doe", department: "Engineering", salary: "$100,000" },
{ id: 2, name: "Jane Smith", department: "Marketing", salary: "$90,000" },
{ id: 3, name: "Samuel Johnson", department: "Sales", salary: "$80,000" },
{ id: 4, name: "Chris Lee", department: "Support", salary: "$70,000" }
];

var tableBody = $('#employeeTable tbody');

$.each(employees, function(index, employee) {


var row = $('<tr></tr>');
[Link]('<td>' + [Link] + '</td>');
[Link]('<td>' + [Link] + '</td>');
[Link]('<td>' + [Link] + '</td>');
[Link]('<td>' + [Link] + '</td>');
[Link](row);
});
});

You might also like