Prepared by
Dr. G. PRABU KANNA
Assistant Professor
School of Computing Science and Engineering
VIT Bhopal University.
JavaScript Introduction
Data Types
Operators
Control Structures
Arrays
Functions
Unit III 4/6/2025 2
JavaScript is the world's most popular programming language.
JavaScript is the programming language of the Web.
JavaScript is easy to learn.
JavaScript is an object-based scripting language which is lightweight
and cross-platform.
JavaScript is not a compiled language, but it is a translated language.
The JavaScript Translator (embedded in the browser) is responsible
for translating the JavaScript code for the web browser.
Unit III 4/6/2025 3
What is JavaScript
JavaScript is a lightweight, interpreted programming language.
It is designed for creating network-centric applications. It is
complimentary to and integrated with Java.
JavaScript is very easy to implement because it is integrated with
HTML. It is open and cross-platform.
Unit III 4/6/2025 4
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.
Unit III 4/6/2025 5
Application of JavaScript
Javascript is one of the most widely used programming
languages (Front-end as well as Back-end). It has it's presence in
almost every area of software development.
Client side validation - This is really important to verify any user
input before submitting it to the server and Javascript plays an
important role in validating those inputs at front-end itself.
Manipulating HTML Pages - Javascript helps in manipulating HTML
page on the fly. This helps in adding and deleting any HTML tag very
easily using javascript and modify your HTML to change its look and
feel based on different devices and requirements.
Unit III 4/6/2025 6
User Notifications - You can use Javascript to raise dynamic pop-ups on
the webpages to give different types of notifications to your website
visitors.
Back-end Data Loading - Javascript provides Ajax library which helps in
loading back-end data while you are doing some other processing. This
really gives an amazing experience to your website visitors.
Presentations - JavaScript also provides the facility of creating
presentations which gives website look and feel. JavaScript provides
RevealJS and BespokeJS libraries to build a web-based slide
presentations.
Server Applications - Node JS is built on Chrome's Javascript runtime for
building fast and scalable network applications. This is an event based
library which helps in developing very sophisticated server applications
including Web Servers.
Unit III 4/6/2025 7
Client-side JavaScript is the most common form of the language. The
script should be included in or referenced by an HTML document for
the code to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include
programs that interact with the user, control the browser, and
dynamically create HTML content.
The JavaScript code is executed when the user submits the form, and
only if all the entries are valid, they would be submitted to the Web
Server.
JavaScript can be used to trap user-initiated events such as button
clicks, link navigation, and other actions that the user initiates
explicitly or implicitly.
Unit III 4/6/2025 8
Less server interaction
Immediate feedback to the visitors
Increased interactivity
Richer interfaces
Unit III 4/6/2025 9
<script>
[Link]("Hello Everyone");
</script>
Unit III 4/6/2025 10
<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>
[Link]("Hello JavaScript by JavaScript");
</script>
</body>
</html>
Unit III 4/6/2025 11
The JavaScript comments are meaningful way to deliver message. It is
used to add information about the code, warnings or suggestions so
that end user can easily interpret the code.
The JavaScript comment is ignored by the JavaScript engine i.e.
embedded in the browser.
Unit III 4/6/2025 12
There are two types of comments in JavaScript.
Single-line Comment
Multi-line Comment
Unit III 4/6/2025 13
<html>
<body>
<script>
// It is single line comment
[Link]("hello javascript");
</script>
</body>
</html>
Unit III 4/6/2025 14
<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>
Unit III 4/6/2025 15
It can be used to add single as well as multi line comments. So, it is more
convenient.
It is represented by forward slash with asterisk then asterisk with forward slash
<script>
/* It is multi line comment.
It will not be displayed */
[Link]("example of javascript multiline comment");
</script>
Unit III 4/6/2025 16
A JavaScript variable is simply a name of storage location. There are
two types of variables in JavaScript : local variable and global
variable.
There are some rules while declaring a JavaScript variable (also
known as identifiers).
Name must start with a letter (a to z or A to Z), underscore( _ ), or
dollar( $ ) sign.
After first letter we can use digits (0 to 9), for example value1.
JavaScript variables are case sensitive, for example x and X are
different variables.
var x = 10;
var _value="sonoo";
Unit III 4/6/2025 17
<script>
var x = 10;
var y = 20;
var z=x+y;
[Link](z);
</script>
Unit III 4/6/2025 18
A JavaScript local variable is declared inside block or function. It is accessible
within the function or block only. For example:
<script>
function abc(){
var x=10;//local variable
}
</script>
Unit III 4/6/2025 19
A JavaScript local variable is declared inside block or function. It is accessible
within the function or block only. For example:
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>
Unit III 4/6/2025 20
A JavaScript global variable is accessible from any function. A variable i.e.
declared outside the function or declared with window object is known as global
variable. For example:
<script>
var data=200;//gloabal variable
function a(){
[Link](data);
}
function b(){
[Link](data);
}
a();//calling JavaScript function
b();
</script>
Unit III 4/6/2025 21
JavaScript provides different data types to hold different types of values. There are
two types of data types in JavaScript.
Primitive data type
Non-primitive (reference) data type
JavaScript is a dynamic type language, means you don't need to specify type of
the variable because it is dynamically used by JavaScript engine. You need to
use var here to specify the data type. It can hold any type of values such as
numbers, strings etc. For example:
var a=40;//holding number
var b="Rahul";//holding string
Unit III 4/6/2025 22
The JavaScript if-else statement is used to execute the code whether condition is
true or false. There are three forms of if statement in JavaScript.
If Statement
If else statement
if else if statement
Unit III 4/6/2025 23
<script>
var a=20;
if(a>10){
[Link]("value of a is greater than 10");
}
</script>
Unit III 4/6/2025 24
<script>
var a=20;
if(a%2==0){
[Link]("a is even number");
}
else{
[Link]("a is odd number");
}
</script>
Unit III 4/6/2025 25
<script>
var a=20;
if(a==10){
[Link]("a is equal to 10");
}
else if(a==15){
[Link]("a is equal to 15");
}
else if(a==20){
[Link]("a is equal to 20");
}
else{
[Link]("a is not equal to 10, 15 or 20");
}
Unit III 4/6/2025 26
</script>
JavaScript functions are used to perform operations. We can call JavaScript
function many times to reuse the code.
Advantage of JavaScript function
There are mainly two advantages of JavaScript functions.
Code reusability: We can call a function several times so it save coding.
Less coding: It makes our program compact. We don’t need to write many lines of
code each time to perform a common task.
Unit III 4/6/2025 27
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Unit III 4/6/2025 28
<script>
function getInfo(){
return "hello How r u?";
}
</script>
<script>
[Link](getInfo());
</script>
Unit III 4/6/2025 29
A javaScript object is an entity having state and behavior (properties
and method). For example: car, pen, bike, chair, glass, keyboard,
monitor etc.
JavaScript is an object-based language. Everything is an object in
JavaScript.
JavaScript is template based not class based. Here, we don't create
class to get the object. But, we direct create objects.
Unit III 4/6/2025 30
There are 3 ways to create objects.
By object literal
By creating instance of Object directly (using new keyword)
By using an object constructor (using new keyword)
Unit III 4/6/2025 31
1) JavaScript Object by object literal
The syntax of creating object using object literal is given below:
object={property1:value1,property2:value2.....propertyN:valueN}
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
[Link]([Link]+" "+[Link]+" "+[Link]);
</script>
Unit III 4/6/2025 32
<html>
<body>
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
[Link]([Link]+" "+[Link]+" "+[Link]);
</script>
</body>
</html>
102 Shyam Kumar 40000
Unit III 4/6/2025 33
2) By creating instance of Object
The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
<script>
var emp=new Object();
[Link]=101;
[Link]="Ravi Malik";
[Link]=50000;
[Link]([Link]+" "+[Link]+" "+[Link]);
</script>
Unit III 4/6/2025 34
<html>
<body>
<script>
var emp=new Object();
[Link]=101;
[Link]="Ravi Malik";
[Link]=50000;
[Link]([Link]+" "+[Link]+" "+[Link]);
</script>
</body>
</html>
101 Ravi Malik 50000
Unit III 4/6/2025 35
3) By using an Object constructor
Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.
The this keyword refers to the current object.
<script>
function emp(id,name,salary){
[Link]=id;
[Link]=name;
[Link]=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
[Link]([Link]+" "+[Link]+" "+[Link]);
</script>
Unit III 4/6/2025 36
<html>
<body>
<script>
function emp(id,name,salary){
[Link]=id;
[Link]=name;
[Link]=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
[Link]([Link]+" "+[Link]+" "+[Link]);
</script>
</body>
</html> 103 Vimal Jaiswal 30000
Unit III 4/6/2025 37
<html>
<body>
<script>
function emp(id,name,salary){
[Link]=id;
[Link]=name;
[Link]=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
[Link]([Link]+" "+[Link]+" "+[Link]);
</script>
</body>
</html> 103 Vimal Jaiswal 30000
Unit III 4/6/2025 38
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
By array literal
By creating instance of Array directly (using new keyword)
By using an Array constructor (using new keyword)
Unit III 4/6/2025 39
1) JavaScript array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<[Link];i++){
[Link](emp[i] + "<br/>");
} </script>
Sonoo
Vimal
Ratan
Unit III 4/6/2025 40
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
Unit III 4/6/2025 41
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John"; Arun
Varun
John
for (i=0;i<[Link];i++){
[Link](emp[i] + "<br>");
}
</script>
.
Unit III 4/6/2025 42
3) JavaScript array constructor (new keyword)
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<[Link];i++){
[Link](emp[i] + "<br>");
}
</script>
Jai
Vijay
Smith
Unit III 4/6/2025 43
The document object represents the whole html document.
When html document is loaded in the browser, it becomes a
document object. It is the root element that represents the html
document.
It has properties and methods. By the help of document object, we
can add dynamic content to our web page.
With the HTML DOM, JavaScript can access and change all the
elements of an HTML document.
Unit III 4/6/2025 44
What is the DOM?
DOM stands for Document Object Model. It is a programming
interface that allows us to create, change, or remove elements from
the document. We can also add events to these elements to make our
page more dynamic.
The DOM views an HTML document as a tree of nodes. A node
represents an HTML element.
Unit III 4/6/2025 45
Unit III 4/6/2025 46
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>DOM tree structure</title>
</head>
<body>
<h1>DOM tree structure</h1>
<h2>Learn about the DOM</h2>
</body>
</html>
Unit III 4/6/2025 47
Our document is called the root node and contains one child node
which is the <html> element. The <html> element contains two
children which are the <head> and <body> elements.
Both the <head> and <body> elements have children of their own.
We can access these elements in the document and make changes to
them using JavaScript.
Unit III 4/6/2025 48
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.
Unit III 4/6/2025 49
There are a few different methods for selecting an element in the HTML document.
Here we will focus on three of those methods:
getElementById()
[Link]()
[Link]() method
querySelector()
Javascript - innerHTML
Unit III 4/6/2025 50
getElementById()
In HTML, ids are used as unique identifiers for the HTML elements. This means you
cannot have the same id name for two different elements.
This would be incorrect:
<p id="para">This is my first paragraph.</p>
<p id="para">This is my second paragraph.</p>
Unit III 4/6/2025 51
getElementById()
In HTML, ids are used as unique identifiers for the HTML elements. This means you
cannot have the same id name for two different elements.
You would have to make sure those ids are unique like this:
<p id="para1">This is my first paragraph.</p>
<p id="para2">This is my second paragraph.</p>
Unit III 4/6/2025 52
In JavaScript, we can grab an HTML tag by referencing the id name.
[Link]("id name goes here")
This code tells the computer to get the <p> element with the id of para1 and
print the element to the console.
const paragraph1 = [Link]("para1");
[Link](paragraph1);
Unit III 4/6/2025 53
If we wanted to just read the content of the paragraph, then we can use the
textContent property inside the [Link]().
const paragraph1 = [Link]("para1");
[Link]([Link]);
Unit III 4/6/2025 54
<script type="text/javascript">
function printvalue(){
var name=[Link];
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
Unit III 4/6/2025 55
The [Link]() method returns the element of specified id.
In the previous page, we have used [Link] to get the value
of the input value.
Instead of this, we can use [Link]() method to get value of the
input text. But we need to define id for the input field.
Unit III 4/6/2025 56
<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>
Unit III 4/6/2025 57
[Link]()
Example of [Link]() method
In this example, we going to count total number of genders. Here, we are using
getElementsByName() method to get all the genders.
Unit III 4/6/2025 58
<script type="text/javascript">
function totalelements()
{
var allgenders=[Link]("gender");
alert("Total Genders:"+[Link]);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" onclick="totalelements()" value="Total Genders">
</form>
Unit III 4/6/2025 59
[Link]() method
In this example, we going to count total number of paragraphs used in the
document. To do this, we have called the [Link]("p")
method that returns the total paragraphs.
Unit III 4/6/2025 60
<script type="text/javascript">
function countpara(){
var totalpara=[Link]("p");
alert("total p tags are: "+[Link]);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by getElementByTagNa
me() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
Unit III 4/6/2025 61
You can use this method to find elements with one or more CSS selectors.
This HTML example of my favorite tv shows:
<h1>Favorite TV shows</h1>
<ul class="list">
<li>Golden Girls</li>
<li>Archer</li>
<li>Rick and Morty</li>
<li>The Crown</li>
</ul>
Unit III 4/6/2025 62
If I wanted to find and print to the console the h1 element, then I could use
that tag name inside the querySelector().
const h1Element = [Link]("h1");
[Link](h1Element);
Unit III 4/6/2025 63
The next part is to add a couple of <li> elements inside the <ul> element
using the createElement() method.
listItem1 = [Link]("li");
listItem2 = [Link]("li");
Then we can use the textContent property to add the text for our list items.
listItem1 = [Link]("li");
[Link] = "It's free";
listItem2 = [Link]("li");
[Link] = "It's awesome";
Unit III 4/6/2025 64
The last part is to use the appendChild() method so the list items can be
added to the unordered list.
listItem1 = [Link]("li");
[Link] = "It's free";
[Link](listItem1);
listItem2 = [Link]("li");
[Link] = "It's awesome";
[Link](listItem2);
Unit III 4/6/2025 65
The innerHTML property can be used to write the dynamic html on the html
document.
It is used mostly in the web pages to generate the dynamic html such as
registration form, comment form, links etc.
Unit III 4/6/2025 66
In this example, we are going to create the html form when user clicks on the
button.
we are dynamically writing the html form inside the div name having the id
mylocation. We are identifing this position by calling the
[Link]() method.
Unit III 4/6/2025 67
<script type="text/javascript" >
function showcommentform() {
var data="Name:<input type='text' name='name'><br>Comment:<br><textarea r
ows='5' cols='80'></textarea>
<br><input type='submit' value='Post Comment'>";
[Link]('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
Unit III 4/6/2025 68
The innerText property can be used to write the dynamic text on the html
document. Here, text will not be interpreted as html text but a normal text.
It is used mostly in the web pages to generate the dynamic content such as writing
the validation message, password strength etc.
Unit III 4/6/2025 69
The innerText property can be used to write the dynamic text on the html
document. Here, text will not be interpreted as html text but a normal text.
It is used mostly in the web pages to generate the dynamic content such as writing
the validation message, password strength etc.
To display the password strength when releases the key after press
Unit III 4/6/2025 70
The innerText property can be used to write the dynamic text on the html
document. Here, text will not be interpreted as html text but a normal text.
It is used mostly in the web pages to generate the dynamic content such as writing
the validation message, password strength etc.
To display the password strength when releases the key after press
Unit III 4/6/2025 71
<script type="text/javascript" >
function validate() {
var msg;
if([Link]>5){
msg="good";
}
else{
msg="poor";
}
[Link]('mylocation').innerText=msg;
}
Unit III 4/6/2025 72
</script>
The JavaScript inheritance is a mechanism that allows us to create
new classes on the basis of already existing classes.
It provides flexibility to the child class to reuse the methods and
variables of a parent class.
The JavaScript extends keyword is used to create a child class on the
basis of a parent class.
It facilitates child class to acquire all the properties and behavior of
its parent class.
Unit III 4/6/2025 73
It maintains an IS-A relationship.
The extends keyword is used in class expressions or class
declarations.
Using extends keyword, we can acquire all the properties and
behavior of the inbuilt object as well as custom classes.
We can also use a prototype-based approach to achieve inheritance.
Unit III 4/6/2025 74
JavaScript extends Example: inbuilt object
In this example, we extends Date object to display today's date.
Unit III 4/6/2025 75
JavaScript extends Example: Custom class
In this example, we declare sub-class that extends the properties of its parent class.
Unit III 4/6/2025 76
The JavaScript Encapsulation is a process of binding the data (i.e. variables) with
the functions acting on that data. It allows us to control the data and validate it. To
achieve an encapsulation in JavaScript: -
Use var keyword to make data members private.
Use setter methods to set the data and getter methods to get that data.
The encapsulation allows us to handle an object using the following properties:
Read/Write - Here, we use setter methods to write the data and getter methods
read that data.
Read Only - In this case, we use getter methods only.
Write Only - In this case, we use setter methods only.
Unit III 4/6/2025 77
Unit III 4/6/2025 78
The polymorphism is a core concept of an object-oriented paradigm that provides
a way to perform a single action in different forms.
It provides an ability to call the same method on different JavaScript objects. As
JavaScript is not a type-safe language, we can pass any type of data members with
the methods.
Unit III 4/6/2025 79
<script>
class A
{
display()
{
[Link]("A is invoked");
}
} Output:
A is invoked
class B extends A A is invoked
{
}
var b=new B();
[Link]();
Unit III 4/6/2025 80
</script>
A is invoked B is invoked
Output:
A is invoked
B is invoked
A is invoked
Unit III 4/6/2025 81