0% found this document useful (0 votes)
23 views

Unit - 4

Uploaded by

Gaurav Dua
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)
23 views

Unit - 4

Uploaded by

Gaurav Dua
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
You are on page 1/ 51

WT Unit -4 Complete

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.

Although, JavaScript has no connectivity with Java programming language. The


name was suggested and provided in the times when Java was gaining popularity in
the market. In addition to web browsers, databases such as CouchDB and MongoDB
use JavaScript as their scripting and query language.

Features of JavaScript
There are following features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in


execution environments.

2. JavaScript follows the syntax and structure of the C programming language.


Thus, it is a structured programming language.

3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).

4. JavaScript is an object-oriented programming language that uses prototypes


rather than using classes for inheritance.

5. It is a light-weighted and interpreted language.

6. It is a case-sensitive language.

7. JavaScript is supportable in several operating systems including, Windows,


macOS, etc.

8. It provides good control to the users over the web browsers.

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,

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

JavaScript Example
1. <script>
2. document.write("Hello JavaScript by JavaScript");
3. </script>

THE ECMA-262 SPECIFICATION DEFINED A STANDARD


VERSION OF CORE JAVASCRIPT LANGUAGE.

● JavaScript is a lightweight, interpreted programming language.

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

● 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 client-side mechanism provides many
advantages over traditional CGI server-side scripts.
● For example, you might use JavaScript to check if the user has
entered a valid email address in a form field.
● 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.

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.

From 2015 ECMAScript is named by year (ECMAScript 2015).

ECMAScript Editions

Ver Official Name Description

ES1 ECMAScript 1 (1997) First edition

ES2 ECMAScript 2 (1998) Editorial changes

ES3 ECMAScript 3 (1999) Added regular expressions

Added try/catch

ES4 ECMAScript 4 Never released

ES5 ECMAScript 5 (2009) Added "strict mode"

Added JSON support

Added String.trim()

Added Array.isArray()

Added Array iteration methods

https://cgccollegespace.live
ES6 ECMAScript 2015 Added let and const

Added default parameter values

Added Array.find()

Added Array.findIndex()

ECMAScript 2016 Added exponential operator (**)

Added Array.prototype.includes

ECMAScript 2017 Added string padding

Added Object.entries

Added Object.values

Added async functions

Added shared memory

ECMAScript 2018 Added rest / spread properties

Added asynchronous iteration

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.

Let’s create the first JavaScript example.

1. <script​ ​type​=​"text/javascript"​>
2. document.write("JavaScript is a simple language for javatpoint learners");
3. </script>

The ​script​ tag specifies that we are using JavaScript.

The ​text/javascript​ is the content type that provides information to the browser
about the data.

The ​document.write()​ function is used to display dynamic content through


JavaScript. We will learn about document object in detail later.

3 Places to put JavaScript code


1. Between the body tag of html

2. Between the head tag of html

3. In .js file (external javaScript)

1) JavaScript Example : code between the body tag


In the above example, we have displayed the dynamic content using JavaScript.
Let’s see the simple example of JavaScript that displays alert dialog box.

1. <script​ ​type​=​"text/javascript"​>
2. alert("Hello Javatpoint");
3. </script>

2) JavaScript Example : code between the head tag


Let’s see the same example of displaying alert dialog box of JavaScript that is
contained inside the head tag.

In this example, we are creating a function msg(). To create function in JavaScript,


you need to write function with function_name as given below.

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>

External JavaScript file


We can create external JavaScript file and embed it in many html page.

It provides ​code re usability​ because single JavaScript file can be used in several
html pages.

An external JavaScript file must be saved by .js extension. It is recommended to


embed all JavaScript files into a single file. It increases the speed of the webpage.

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>

Advantages of External JavaScript


There will be following benefits if a user creates an external javascript:

1. It helps in the reusability of code in more than one HTML file.

2. It allows easy code readability.

3. It is time-efficient as web browsers cache the external js files, which further


reduces the page loading time.

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.

Disadvantages of External JavaScript


There are the following disadvantages of external files:

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.

6. If it is a few lines of code, then better to implement the internal javascript


code.

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

The ​JavaScript comments​ are a meaningful way to deliver messages. It is used to


add information about the code, warnings or suggestions so that end user can easily
interpret the code.

https://cgccollegespace.live
The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the
browser.

Advantages of JavaScript comments


There are mainly two advantages of JavaScript comments.

1. To make code easy to understand​ It can be used to elaborate the code so


that the end user can easily understand the code.

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.

Types of JavaScript Comments


There are two types of comments in JavaScript.

1. Single-line Comment

2. Multi-line Comment

JavaScript Single 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>

JavaScript Multi line Comment


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. For
example:

1. /* your code here */

It can be used before, after and middle of the statement.

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.

Correct JavaScript variables

1. var ​x​ = ​10​;


2. var ​_value​=​"sonoo"​;

Incorrect JavaScript variables

1. var ​123​=​30​;
2. var *​aa​=​320​;

Example of JavaScript variable


Let’s see a simple example of a JavaScript variable.

1. <script>
2. var ​x​ = ​10​;
3. var ​y​ = ​20​;
4. var ​z​=​x​+y;
5. document.write(z);
6. </script>

Output of the above example

30

JavaScript local variable


https://cgccollegespace.live
A JavaScript local variable is declared inside a block or function. It is accessible
within the function or block only. For example:

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>

JavaScript global variable


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:

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 Data Types


https://cgccollegespace.live
JavaScript provides different ​data types​ to hold different types of values. There are
two types of data types in JavaScript.

1. Primitive data type


2. 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:

1. var ​a​=​40​;//holding number


2. var ​b​=​"Rahul"​;//holding string

JavaScript primitive data types


There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all

JavaScript non-primitive data types


The non-primitive data types are as follows:

https://cgccollegespace.live
Data Type Description

Object represents instance through which we can access members

Array represents group of similar values

RegExp represents regular expression

JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands.
For example:

1. var ​sum​=​10​+20;

Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.

https://cgccollegespace.live
Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9

JavaScript Comparison Operators


The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:

Operator Description Example

== Is equal to 10==20 = false

https://cgccollegespace.live
=== Identical (equal and of same type) 10==20 = false

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false

JavaScript Bitwise Operators


The bitwise operators perform bitwise operations on operands. The bitwise operators
are as follows:

Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

https://cgccollegespace.live
~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2

JavaScript Logical Operators


The following operators are known as JavaScript logical operators.

Operator Description Example

&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true

JavaScript Assignment Operators


The following operators are known as JavaScript assignment operators.

Operator Description Example

https://cgccollegespace.live
= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

JavaScript Special Operators


The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the condition. It is like


if-else.

, Comma Operator allows multiple expressions to be evaluated as


single statements.

delete Delete Operator deletes a property from the object.

https://cgccollegespace.live
in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.

JavaScript Statements

Example

var​ x, y, z; ​// Statement 1

x = ​5​; ​// Statement 2

y = ​6​; ​// Statement 3

z = x + y; ​// Statement 4

https://cgccollegespace.live
JavaScript Programs
A computer program is a list of "instructions" to be "executed" by a
computer.

In a programming language, these programming instructions are called


statements.

A JavaScript program is a list of programming statements.

In HTML, JavaScript programs are executed by the web browser.

JavaScript Statements
JavaScript statements are composed of:

Values, Operators, Expressions, Keywords, and Comments.

This statement tells the browser to write "Hello Dolly." inside an HTML
element with id="demo":

Example

document.getElementById(​"demo"​).innerHTML = ​"Hello Dolly."​;

Most JavaScript programs contain many JavaScript statements.

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.

Add a semicolon at the end of each executable statement:

var​ a, b, c; ​// Declare 3 variables

a = ​5​; ​// Assign the value 5 to a

b = ​6​; ​// Assign the value 6 to b

c = a + b; ​// Assign the sum of a and b to c

When separated by semicolons, multiple statements on one line are allowed:

a = ​5​; b = ​6​; c = a + b;

On the web, you might see examples without semicolons.

Ending statements with semicolons is not required, but highly recommended.

JavaScript White Space


JavaScript ignores multiple spaces. You can add white space to your script to
make it more readable.

The following lines are equivalent:


https://cgccollegespace.live
var​ person = ​"Hege"​;

var​ person=​"Hege"​;

A good practice is to put spaces around operators ( = + - * / ):

var​ x = y + z;

JavaScript Line Length and Line Breaks


For best readability, programmers often like to avoid code lines longer than
80 characters.

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!"​;

JavaScript Code Blocks


JavaScript statements can be grouped together in code blocks, inside curly
brackets {...}.

The purpose of code blocks is to define statements to be executed together.

One place you will find statements grouped together in blocks, is in


JavaScript functions:
https://cgccollegespace.live
Example

function​ myFunction() {

document.getElementById(​"demo1"​).innerHTML = ​"Hello Dolly!"​;

document.getElementById(​"demo2"​).innerHTML = ​"How are you?"​;

}​In this tutorial we use 2 spaces of indentation for code blocks.

You will learn more about functions later in this tutorial.

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

break Terminates a switch or a loop

continue Jumps out of a loop and starts at the top

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

for Marks a block of statements to be executed, as long as a


condition is true

function Declares a function

if ... else Marks a block of statements to be executed, depending on a


condition

return Exits a function

switch Marks a block of statements to be executed, depending on


different cases

try ... Implements error handling to a block of statements


catch

var Declares a variable

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

For detail of switch statements visit​ - ​https://www.javatpoint.com/javascript-switch

For detail of loop statements visit​ ​- ​https://www.javatpoint.com/javascript-loop

JavaScript Functions
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.

1. Code reusability​: We can call a function several times so it save coding.


2. Less coding​: It makes our program compact. We don’t need to write many
lines of code each time to perform a common task.

JavaScript Function Syntax


The syntax of the declaring function is given below.

1. function functionName([arg1, arg2, ...argN]){


2. //code to be executed
3. }

JavaScript Functions can have 0 or more arguments.

JavaScript Function Example

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"​/>

JavaScript Function Arguments


We can call functions by passing arguments. Let’s see the example of function that
has one argument.

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>

Function with Return Value


We can call a function that returns a value and use it in our program. Let’s see the
example of a function that returns value.

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>

Output of the above example

hello boy! How r u?

JavaScript Function Object


In JavaScript, the purpose of ​Function constructor​ is to create a new Function
object. It executes the code globally. However, if we call the constructor directly, a
function is created dynamically but in an unsecured way.

Syntax
1. new Function ([arg1[, arg2[, ....argn]],] functionBody)

Parameter
arg1, arg2, .... , argn​ - It represents the argument used by function.

functionBody​ - It represents the function definition.

JavaScript Function Methods


Let's see function methods with description.

Method Description

apply() It is used to call a function contains this value and a single array of
arguments.

bind() It is used to create a new function.

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.

JavaScript Function Object Examples

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

2. By creating instance of Array directly (using new keyword)

3. By using an Array constructor (using new keyword)

1) JavaScript array literal


The syntax of creating array using array literal is given below:

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>

The .length property returns the length of an array.

Output of the above example

Sonoo

Vimal

Ratan

2) JavaScript Array directly (new keyword)


The syntax of creating array directly is given below:

1. var ​arrayname​=​new​ Array();

Here, ​new keyword​ is used to create instance of array.

Let's see the example of creating array directly.

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>

Output of the above example

Arun

Varun

John

3) JavaScript array constructor (new keyword)


Here, you need to create an instance of array by passing arguments in constructor
so that we don't have to provide value explicitly.

The example of creating objects by array constructor is given below.

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>

Output of the above example

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 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 directly create objects.

Creating Objects in JavaScript


There are 3 ways to 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) JavaScript Object by object literal


The syntax of creating object using object literal is given below:

1. object​={property1:value1,property2:value2.....propertyN:valueN}

As you can see, property and value is separated by : (colon).

Let’s see the simple example of creating object in JavaScript.

1. <script>
2. emp​={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>

Output of the above example

102 Shyam Kumar 40000

2) By creating instance of Object

https://cgccollegespace.live
The syntax of creating object directly is given below:

1. var ​objectname​=​new​ Object();

Here, ​new keyword​ is used to create object.

Let’s see the example of creating object directly.

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>

Output of the above example

101 Ravi 50000

3) By using an Object constructor


Here, you need to create a 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.

The example of creating object by object constructor is given below.

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

103 Vimal Jaiswal 30000

Defining method in JavaScript Object


We can define method in JavaScript object. But before defining method, we need to
add property in the function with same name as method.

The example of defining method in object is given below.

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>

Output of the above example

103 Sonoo Jaiswal 30000

103 Sonoo Jaiswal 45000

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.

Alert Dialog Box


An alert dialog box is mostly used to give a warning message to the users. For
example, if one input field requires to enter some text but the user does not provide
any input, then as a part of validation, you can use an alert box to give a warning
message.

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>

​<script​ ​type​ ​=​ ​"text/javascript"​>

​<!--

​function​ ​Warn​()​ ​{

alert ​(​"This is a warning message!"​);

document​.​write ​(​"This is a warning message!"​);

​}

​//-->

https://cgccollegespace.live
​</script>

​</head>

​<body>

​<p>​Click the following button to see the result: ​</p>

​<form>

​<input​ ​type​ ​=​ ​"button"​ ​value​ ​=​ ​"Click Me"​ ​onclick​ ​=


"​Warn​();​"​ ​/>

​</form>

​</body>

</html>

Confirmation Dialog Box


A confirmation dialog box is mostly used to take user's consent on any option. It
displays a dialog box with two buttons: OK and Cancel.

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>

​<script​ ​type​ ​=​ ​"text/javascript"​>

​<!--

https://cgccollegespace.live
​function​ getConfirmation​()​ ​{

​var​ retVal ​=​ confirm​(​"Do you want to continue ?"​);

​if​(​ retVal ​==​ ​true​ ​)​ ​{

document​.​write ​(​"User wants to continue!"​);

​return​ ​true​;

​}​ ​else​ ​{

document​.​write ​(​"User does not want to


continue!"​);

​return​ ​false​;

​}

​}

​//-->

​</script>

​</head>

​<body>

​<p>​Click the following button to see the result: ​</p>

​<form>

​<input​ ​type​ ​=​ ​"button"​ ​value​ ​=​ ​"Click Me"​ ​onclick​ ​=


"​getConfirmation​();​"​ ​/>

​</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

The following example shows how to use a prompt dialog box −

Live Demo

<html>

​<head>

​<script​ ​type​ ​=​ ​"text/javascript"​>

​<!--

​function​ getValue​()​ ​{

​var​ retVal ​=​ prompt​(​"Enter your name : "​,​ ​"your


name here"​);

document​.​write​(​"You have entered : "​ ​+​ retVal​);

​}

​//-->

​</script>

​</head>

https://cgccollegespace.live
​<body>

​<p>​Click the following button to see the result: ​</p>

​<form>

​<input​ ​type​ ​=​ ​"button"​ ​value​ ​=​ ​"Click Me"​ ​onclick​ ​=


"​getValue​();​"​ ​/>

​</form>

​</body>

</html>

Document Object Model

1. Document Object
2. Properties of document object
3. Methods of document object
4. Example of document object

The ​document object​ represents the whole html document.

When a 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

https://cgccollegespace.live
methods. By the help of document object, we can add dynamic content to our web
page.

As mentioned earlier, it is the object of the window. So

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

Properties of document object

https://cgccollegespace.live
Let's see the properties of document object that can be accessed and modified by
the document object.

Methods of document object


We can access and change the contents of documents by its methods.

The important methods of document object are as follows:

Method Description

write("string") writes the given string on the document.

writeln("string") writes the given string on the document with a

newline character at the end.

https://cgccollegespace.live
getElementById() returns the element having the given id value.

getElementsByName() returns all the elements having the given name

value.

getElementsByTagName() returns all the elements having the given tag

name.

getElementsByClassName() returns all the elements having the given class


name.

Accessing field value by document object


In this example, we are going to get the value of input text by user. Here, we are
using ​document.form1.name.value​ to get the value of name field.

Here, ​document​ is the root element that represents the html document.

form1​ is the name of the form.

name​ is the attribute name of the input text.

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

The ​document.getElementById()​ method returns the element of specified id.

In the previous page, we have used ​document.form1.name.value​ to get the value


of the input value. Instead of this, we can use document.getElementById() method
to get the value of the input text. But we need to define id for the input field.

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 of getElementsByClassName() Method


Let's look at some examples to know and understand the practical implementation of
the method.

Example

It is a simple class implementation that returns an array-like object on invoking the


variable x.

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.

Difference between getElementsByClassName(),


querySelector() and querySelectorAll() Methods
getElementsByClassName():​ It matches the elements with the specified class
name, and returns a set of the matched elements. The returned elements are live
HTML​ collection of elements. These live elements can be further updated if any
changes are made in the Document Object Model.

querySelector():​ It returns only a single element that matches the specified


classname. If it does not find any matching element, it returns null.

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

Javascript - document.getElementsByName() method


1. getElementsByName() method
2. Example of getElementsByName()

The ​document.getElementsByName()​ method returns all the elements of the


specified name.

The syntax of the getElementsByName() method is given below:

1. document.getElementsByName("name")

https://cgccollegespace.live
Here, name is required.

Example of document.getElementsByName() method


In this example, we are going to count the total number of genders. Here, we are
using getElementsByName() method to get all the genders.

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>

Javascript - document.getElementsByTagName() method

1. getElementsByTagName() method
2. Example of getElementsByTagName()

The ​document.getElementsByTagName()​ method returns all the element of


specified tag name.

The syntax of the getElementsByTagName() method is given below:

1. document.getElementsByTagName("name")

Here, name is required.

Example of document.getElementsByTagName() method


In this example, we are going to count the total number of paragraphs used in the
document. To do this, we have called the document.getElementsByTagName("p")
method that returns the total paragraphs.

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>

Output of the above example

This is a pragraph

Here we are going to count total number of paragraphs by getElementByTagName()


method.

Let's see the simple example

count paragraph

Another example of document.getElementsByTagName() method

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.

Example of innerHTML property


In this example, we are going to create the html form when the user clicks on the
button.

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.

1. <script​ ​type​=​"text/javascript"​ ​>


2. function showcommentform() {
3. var ​data​="Name:​<input​ ​type​=​'text'
name​=​'name'​><br>​Comment:​<br><textarea​ ​rows​=​'5'
cols​=​'80'​></textarea>
4. <br><input​ ​type​=​'submit'​ ​value​=​'Post Comment'​>​";
5. document.getElementById('mylocation')​.innerHTML​=​data​;
6. }

https://cgccollegespace.live
7. </script>
8. <form​ ​name​=​"myForm"​>
9. <input​ ​type​=​"button"​ ​value​=​"comment"​ ​onclick​=​"showcommentform()"​>
10.<div​ ​id​=​"mylocation"​></div>
11.</form>

Show/Hide Comment Form Example using innerHTML


1. <!DOCTYPE html​>
2. <html>
3. <head>
4. <title>​First JS​</title>
5. <script>
6. var ​flag​=​true​;
7. function commentform(){
8. var ​cform​="​<form​ ​action​=​'Comment'​>​Enter Name:​<br><input​ ​type​=​'text'
name​=​'name'​/><br/>
9. Enter Email:​<br><input​ ​type​=​'email'​ ​name​=​'email'​/><br>​Enter
Comment:​<br/>
10.<textarea​ ​rows​=​'5'​ ​cols​=​'70'​></textarea><br><input​ ​type​=​'submit'
value​=​'Post Comment'​/></form>​";
11.if(flag){
12.document.getElementById("mylocation")​.innerHTML​=​cform​;
13.flag​=​false​;
14.}else{
15.document.getElementById("mylocation")​.innerHTML​=​""​;
16.flag​=​true​;
17.}
18.}
19.</script>
20.</head>
21.<body>
22.<button​ ​onclick​=​"commentform()"​>​Comment​</button>
23.<div​ ​id​=​"mylocation"​></div>
24.</body>
25.</html>

https://cgccollegespace.live
Javascript - innerText
1. javascri​pt 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.

Javascript innerText Example


In this example, we are going to display the password strength when releasing the
key after press.

1. <script​ ​type​=​"text/javascript"​ ​>


2. function validate() {
3. var msg;
4. if(document.myForm.userPass.value.length​>​5){
5. msg​=​"good"​;
6. }
7. else{
8. msg​=​"poor"​;
9. }
10.document.getElementById('mylocation')​.innerText​=​msg​;
11. }
12.
13.</script>
14.<form​ ​name​=​"myForm"​>
15.<input​ ​type​=​"password"​ ​value​=​""​ ​name​=​"userPass"​ ​onkeyup​=​"validate()"​>
16.Strength:​<span​ ​id​=​"mylocation"​>​no strength​</span>
17.</form>

https://cgccollegespace.live
UNIT - 4 COMPLETED

https://cgccollegespace.live

You might also like