Unit - 4
Unit - 4
What is JavaScript
JavaScript (js) is a light-weight object-oriented programming language which is used
by several websites for scripting the webpages. It is an interpreted, full-fledged
programming language that enables dynamic interactivity on websites when applied
to an HTML document. It was introduced in the year 1995 for adding programs to
the webpages in the Netscape Navigator browser. Since then, it has been adopted
by all other graphical web browsers. With JavaScript, users can build modern web
applications to interact directly without reloading the page every time. The
traditional website uses js to provide several forms of interactivity and simplicity.
Features of JavaScript
There are following features of JavaScript:
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
6. It is a case-sensitive language.
https://cgccollegespace.live
History of JavaScript
In 1993, Mosaic, the first popular web browser, came into existence. In 1994,
Netscape was founded by Marc Andreessen. He realized that the web needed to
become more dynamic. Thus, a 'glue language' was believed to be provided to HTML
to make web designing easy for designers and part-time programmers.
Consequently, in 1995, the company recruited Brendan Eich intending to
implement and embed Scheme programming language to the browser. But, before
Brendan could start, the company merged with Sun Microsystems for adding Java
into its Navigator so that it could compete with Microsoft over the web technologies
and platforms. Now, two languages were there: Java and the scripting language.
Further, Netscape decided to give a similar name to the scripting language as Java's.
It led to 'Javascript'. Finally, in May 1995, Marc Andreessen coined the first code of
Javascript named 'Mocha'. Later, the marketing team replaced the name with
'LiveScript'. But, due to trademark reasons and certain other reasons, in December
1995, the language was finally renamed to 'JavaScript'. From then, JavaScript came
into existence.
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
● Client-side validation,
● Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm
dialog box and prompt dialog box),
JavaScript Example
1. <script>
2. document.write("Hello JavaScript by JavaScript");
3. </script>
https://cgccollegespace.live
● Designed for creating web-centric applications.
● Complementary to and integrated with Java.
● Complementary to and integrated with HTML.
● Open and cross-platform
CLIENT-SIDE JAVASCRIPT
JavaScript Versions:
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in
1997.
https://cgccollegespace.live
ECMAScript is the official name of the language.
ECMAScript versions have been abbreviated to ES1, ES2, ES3, ES5, and ES6.
ECMAScript Editions
Added try/catch
Added String.trim()
Added Array.isArray()
https://cgccollegespace.live
ES6 ECMAScript 2015 Added let and const
Added Array.find()
Added Array.findIndex()
Added Array.prototype.includes
Added Object.entries
Added Object.values
Added Promise.finally()
Additions to RegExp
JavaScript Example
1. JavaScript Example
2. Within body tag
3. Within head tag
https://cgccollegespace.live
Javascript examples are easy to code. JavaScript provides 3 places to put the
JavaScript code: within body tag, within head tag and external JavaScript file.
1. <script type="text/javascript">
2. document.write("JavaScript is a simple language for javatpoint learners");
3. </script>
The text/javascript is the content type that provides information to the browser
about the data.
1. <script type="text/javascript">
2. alert("Hello Javatpoint");
3. </script>
https://cgccollegespace.live
To call function, you need to work on event. Here we are using onclick event to call
msg() function.
1. <html>
2. <head>
3. <script type="text/javascript">
4. function msg(){
5. alert("Hello Javatpoint");
6. }
7. </script>
8. </head>
9. <body>
10.<p>Welcome to JavaScript</p>
11.<form>
12.<input type="button" value="click" onclick="msg()"/>
13.</form>
14.</body>
15.</html>
It provides code re usability because single JavaScript file can be used in several
html pages.
Let's create an external JavaScript file that prints Hello Javatpoint in a alert dialog
box.
message.js
1. function msg(){
2. alert("Hello Javatpoint");
3. }
https://cgccollegespace.live
Let's include the JavaScript file into html page. It calls the JavaScript function on
button click.
index.html
1. <html>
2. <head>
3. <script type="text/javascript" src="message.js"></script>
4. </head>
5. <body>
6. <p>Welcome to JavaScript</p>
7. <form>
8. <input type="button" value="click" onclick="msg()"/>
9. </form>
10.</body>
11.</html>
4. It enables both web designers and coders to work with html and js files
parallelly and separately, i.e., without facing any code conflictions.
5. The length of the code reduces as only we need to specify the location of the
js file.
6. Less server interaction: You can validate user input before sending
the page off to the server. This saves server traffic, which means less
load on your server.
7. Immediate feedback to the visitors: They don't have to wait for a
page reload to see if they have forgotten to enter something.
8. Increased interactivity: You can create interfaces that react when the
user hovers over them with a mouse or activates them via the keyboard.
https://cgccollegespace.live
9. Richer interfaces: You can use JavaScript to include such items as
drag and-drop components and sliders to give a Rich Interface to your
site visitors.
1. The stealer may download the coder's code using the url of the js file.
2. If two js files are dependent on one another, then a failure in one file may
affect the execution of the other dependent file.
3. The web browser needs to make an additional http request to get the js code.
4. A tiny to a large change in the js code may cause unexpected results in all its
dependent files.
5. We need to check each file that depends on the commonly created external
javascript file.
LIMITATIONS OF JAVASCRIPT
● Client-side JavaScript does not allow the reading or writing of files. This
has been kept for security reasons.
● JavaScript cannot be used for networking applications because there is
no such support available.
● JavaScript doesn't have any multithreading or multiprocessor
capabilities
JavaScript Comment
1. JavaScript comments
2. Advantage of javaScript comments
3. Single-line and Multi-line comments
https://cgccollegespace.live
The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the
browser.
2. To avoid the unnecessary code It can also be used to avoid the code being
executed. Sometimes, we add the code to perform some action. But after
sometime, there may be a need to disable the code. In such case, it is better
to use comments.
1. Single-line Comment
2. Multi-line Comment
It is represented by double forward slashes (//). It can be used before and after the
statement.
Let’s see the example of single-line comment i.e. added before the statement.
1. <script>
2. // It is single line comment
3. document.write("hello javascript");
4. </script>
https://cgccollegespace.live
Let’s see the example of single-line comment i.e. added after the statement.
1. <script>
2. var a=10;
3. var b=20;
4. var c=a+b;//It adds values of a and b variable
5. document.write(c);//prints sum of 10 and 20
6. </script>
It is represented by forward slash with asterisk then asterisk with forward slash. For
example:
1. <script>
2. /* It is a multi line comment.
3. It will not be displayed */
4. document.write("example of javascript multiline comment");
5. </script>
JavaScript Variable
1. JavaScript variable
2. JavaScript Local variable
3. JavaScript Global variable
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).
https://cgccollegespace.live
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ )
sign.
2. After the first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different
variables.
1. var 123=30;
2. var *aa=320;
1. <script>
2. var x = 10;
3. var y = 20;
4. var z=x+y;
5. document.write(z);
6. </script>
30
1. <script>
2. function abc(){
3. var x=10;//local variable
4. }
5. </script>
Or,
1. <script>
2. If(10<13){
3. var y=20;//JavaScript local variable
4. }
5. </script>
1. <script>
2. var data=200;//global variable
3. function a(){
4. document.writeln(data);
5. }
6. function b(){
7. document.writeln(data);
8. }
9. a();//calling JavaScript function
10.b();
11.</script>
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:
https://cgccollegespace.live
Data Type Description
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands.
For example:
1. var sum=10+20;
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
https://cgccollegespace.live
Operator Description Example
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
https://cgccollegespace.live
=== Identical (equal and of same type) 10==20 = false
https://cgccollegespace.live
~ Bitwise NOT (~10) = -10
https://cgccollegespace.live
= Assign 10+10 = 20
Operator Description
https://cgccollegespace.live
in In Operator checks if object has the given property
JavaScript Statements
Example
z = x + y; // Statement 4
https://cgccollegespace.live
JavaScript Programs
A computer program is a list of "instructions" to be "executed" by a
computer.
JavaScript Statements
JavaScript statements are composed of:
This statement tells the browser to write "Hello Dolly." inside an HTML
element with id="demo":
Example
The statements are executed, one by one, in the same order as they are
written.
https://cgccollegespace.live
JavaScript programs (and JavaScript statements) are often called JavaScript code.
Semicolons ;
Semicolons separate JavaScript statements.
a = 5; b = 6; c = a + b;
var person="Hege";
var x = y + z;
If a JavaScript statement does not fit on one line, the best place to break it is
after an operator:
Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";
function myFunction() {
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript
action to be performed.
Here is a list of some of the keywords you will learn about in this tutorial:
Keyword Description
debugger Stops the execution of JavaScript, and calls (if available) the
debugging function
https://cgccollegespace.live
do ... while Executes a block of statements, and repeats the block, while
a condition is true
JavaScript keywords are reserved words. Reserved words cannot be used as names
for variables.
https://cgccollegespace.live
For detail of if, if - else if statements visit - https://www.javatpoint.com/javascript-if
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript
function many times to reuse the code.
https://cgccollegespace.live
Let’s see the simple example of a function in JavaScript that does not has
arguments.
1. <script>
2. function msg(){
3. alert("hello! this is message");
4. }
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>
1. <script>
2. function getcube(number){
3. alert(number*number*number);
4. }
5. </script>
6. <form>
7. <input type="button" value="click" onclick="getcube(4)"/>
8. </form>
1. <script>
2. function getInfo(){
3. return "hello boy! How r u?";
4. }
5. </script>
6. <script>
7. document.write(getInfo());
https://cgccollegespace.live
8. </script>
Syntax
1. new Function ([arg1[, arg2[, ....argn]],] functionBody)
Parameter
arg1, arg2, .... , argn - It represents the argument used by function.
Method Description
apply() It is used to call a function contains this value and a single array of
arguments.
call() It is used to call a function contains this value and an argument list.
https://cgccollegespace.live
toString() It returns the result in a form of a string.
Example 1
Let's see an example to display the sum of given numbers.
1. <script>
2. var add=new Function("num1","num2","return num1+num2");
3. document.writeln(add(2,5));
4. </script>
Output:
Example 2
Let's see an example to display the power of provided value.
1. <script>
2. var pow=new Function("num1","num2","return Math.pow(num1,num2)");
3. document.writeln(pow(2,3));
4. </script>
Output:
JavaScript Array
JavaScript array is an object that represents a collection of similar type of
elements.
https://cgccollegespace.live
There are 3 ways to construct array in JavaScript
1. By array literal
1. var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Let's see the simple example of creating and using array in JavaScript.
1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </script>
Sonoo
Vimal
Ratan
https://cgccollegespace.live
1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7.
8. for (i=0;i<emp.length;i++){
9. document.write(emp[i] + "<br>");
10.}
11.</script>
Arun
Varun
John
1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>
Jai
Vijay
Smith
https://cgccollegespace.live
JavaScript Objects
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 template based not class based. Here, we don't create class to get the
object. But, we directly create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1. object={property1:value1,property2:value2.....propertyN:valueN}
1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>
https://cgccollegespace.live
The syntax of creating object directly is given below:
1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6. }
7. e=new emp(103,"Vimal Jaiswal",30000);
8.
9. document.write(e.id+" "+e.name+" "+e.salary);
10.</script>
https://cgccollegespace.live
Output of the above example
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6.
7. this.changeSalary=changeSalary;
8. function changeSalary(otherSalary){
9. this.salary=otherSalary;
10.}
11.}
12.e=new emp(103,"Sonoo Jaiswal",30000);
13.document.write(e.id+" "+e.name+" "+e.salary);
14.e.changeSalary(45000);
15.document.write("<br>"+e.id+" "+e.name+" "+e.salary);
16.</script>
https://cgccollegespace.live
JavaScript - Dialog Boxes
JavaScript supports three important types of dialog boxes. These dialog boxes can
be used to raise and alert, or to get confirmation on any input or to have a kind of
input from the users. Here we will discuss each dialog box one by one.
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives
only one button "OK" to select and proceed.
Example
<html>
<head>
<!--
function Warn() {
}
//-->
https://cgccollegespace.live
</script>
</head>
<body>
<form>
</form>
</body>
</html>
If the user clicks on the OK button, the window method confirm() will return true. If
the user clicks on the Cancel button, then confirm() returns false. You can use a
confirmation dialog box as follows.
Example
Live Demo
<html>
<head>
<!--
https://cgccollegespace.live
function getConfirmation() {
return true;
} else {
return false;
}
}
//-->
</script>
</head>
<body>
<form>
</form>
</body>
</html>
https://cgccollegespace.live
Prompt Dialog Box
The prompt dialog box is very useful when you want to pop-up a text box to get user
input. Thus, it enables you to interact with the user. The user needs to fill in the field
and then click OK.
This dialog box is displayed using a method called prompt() which takes two
parameters: (i) a label which you want to display in the text box and (ii) a default
string to display in the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button,
the window method prompt() will return the entered value from the text box. If the
user clicks the Cancel button, the window method prompt() returns null.
Example
Live Demo
<html>
<head>
<!--
function getValue() {
}
//-->
</script>
</head>
https://cgccollegespace.live
<body>
<form>
</form>
</body>
</html>
1. Document Object
2. Properties of document object
3. Methods of document object
4. Example of document object
https://cgccollegespace.live
methods. By the help of document object, we can add dynamic content to our web
page.
1. window.document
Is same as
1. document
According to W3C - "The W3C Document Object Model (DOM) is a platform and
language-neutral interface that allows programs and scripts to dynamically access
and update the content, structure, and style of a document."
https://cgccollegespace.live
Let's see the properties of document object that can be accessed and modified by
the document object.
Method Description
https://cgccollegespace.live
getElementById() returns the element having the given id value.
value.
name.
Here, document is the root element that represents the html document.
value is the property, that returns the value of the input text.
Let's see the simple example of document object that prints name with welcome
message.
1. <script type="text/javascript">
2. function printvalue(){
3. var name=document.form1.name.value;
4. alert("Welcome: "+name);
5. }
6. </script>
7.
https://cgccollegespace.live
8. <form name="form1">
9. Enter Name:<input type="text" name="name"/>
10.<input type="button" onclick="printvalue()" value="print name"/>
11.</form>
Javascript - document.getElementById()
method
1. getElementById() method
2. Example of getElementById()
Let's see the simple example of document.getElementById() method that prints the
cube of the given number.
1. <script type="text/javascript">
2. function getcube(){
3. var number=document.getElementById("number").value;
4. alert(number*number*number);
5. }
6. </script>
7. <form>
8. Enter No:<input type="text" id="number" name="number"/><br/>
9. <input type="button" value="cube" onclick="getcube()"/>
10.</form>
GetElementsByClassName()
The getElementsByClassName() method is used for selecting or getting the elements
through their class name value. This DOM method returns an array-like object that
consists of all the elements having the specified classname. On calling the
https://cgccollegespace.live
getElementsByClassName() method on any particular element, it will search the
whole document and will return only those elements which match the specified or
given class name.
Syntax
1. var ele=document.getELementsByClassName('name');
Here, name is the mandatory argument to be passed. It is the string that specifies
either a single classname or multiple class names to match.
Example
1. <html>
2. <head> <h5>DOM Methods </h5> </head>
3. <body>
4. <div class="Class">
5. This is a simple class implementation
6. </div>
7. <script type="text/javascript">
8. var x=document.getElementsByClassName('Class');
9. document.write("On calling x, it will return an arrsy-like object: <br>"+x);
10.</script>
11.</body>
12.</html>
Output:
https://cgccollegespace.live
Similarly, we can implement the getElementsByClassName() method for returning
collections of elements for multiple classes.
The main point to understand is that all the above-described methods return either
one element or a list, but the getELementsByClassName() method serves the
dynamic updation, and the other two methods serve for the static.
1. document.getElementsByName("name")
https://cgccollegespace.live
Here, name is required.
1. <script type="text/javascript">
2. function totalelements()
3. {
4. var allgenders=document.getElementsByName("gender");
5. alert("Total Genders:"+allgenders.length);
6. }
7. </script>
8. <form>
9. Male:<input type="radio" name="gender" value="male">
10.Female:<input type="radio" name="gender" value="female">
11.
12.<input type="button" onclick="totalelements()" value="Total Genders">
13.</form>
1. getElementsByTagName() method
2. Example of getElementsByTagName()
1. document.getElementsByTagName("name")
https://cgccollegespace.live
1. <script type="text/javascript">
2. function countpara(){
3. var totalpara=document.getElementsByTagName("p");
4. alert("total p tags are: "+totalpara.length);
5.
6. }
7. </script>
8. <p>This is a pragraph</p>
9. <p>Here we are going to count total number of paragraphs by
getElementByTagName() method.</p>
10.<p>Let's see the simple example</p>
11.<button onclick="countpara()">count paragraph</button>
This is a pragraph
count paragraph
In this example, we are going to count the total number of h2 and h3 tags used in
the document.
1. <script type="text/javascript">
2. function counth2(){
3. var totalh2=document.getElementsByTagName("h2");
4. alert("total h2 tags are: "+totalh2.length);
5. }
6. function counth3(){
7. var totalh3=document.getElementsByTagName("h3");
8. alert("total h3 tags are: "+totalh3.length);
https://cgccollegespace.live
9. }
10.</script>
11.<h2>This is h2 tag</h2>
12.<h2>This is h2 tag</h2>
13.<h3>This is h3 tag</h3>
14.<h3>This is h3 tag</h3>
15.<h3>This is h3 tag</h3>
16.<button onclick="counth2()">count h2</button>
17.<button onclick="counth3()">count h3</button>
Javascript - innerHTML
1. javascript innerHTML
2. Example of innerHTML property
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.
In this example, we are dynamically writing the html form inside the div name
having the id mylocation. We are identifying this position by calling the
document.getElementById() method.
https://cgccollegespace.live
7. </script>
8. <form name="myForm">
9. <input type="button" value="comment" onclick="showcommentform()">
10.<div id="mylocation"></div>
11.</form>
https://cgccollegespace.live
Javascript - innerText
1. javascript innerText
2. Example of innerText property
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.
https://cgccollegespace.live
UNIT - 4 COMPLETED
https://cgccollegespace.live