WT Unit-3.1 Javascript

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Unit-3

Scripting: Java script: Introduction, documents, forms, statements, functions, objects;


introduction to AJAX, Networking : Internet Addressing, InetAddress, Factory Methods,
Instance Methods, TCP/IP Client Sockets, URL, URL Connection, TCP/IP Server Sockets,
Datagram.

 What is JavaScript
1. JavaScript is a light-weight object-oriented programming language which is used by
several websites for scripting the web pages.
2. It is an interpreted, programming language that enables dynamic interactivity on websites
when applied to an HTML document.
3. It was introduced in the year 1995 for adding programs to the web pages in the Netscape
Navigator browser. Since then, it has been adopted by all other graphical web browsers.
4. 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:
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.

 History of JavaScript

In 1993, Mosaic, the first popular web browser, came into existence. In the year
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:
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),
o Displaying clocks etc.

Example of JavaScript
<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>//Start tag
document.write("Hello JavaScript");
// document is object instance of Document object and write is a function
</script>//End Tag
</body>
</html>

Welcome to JavaScript
Hello JavaScript

External JavaScript file


 We can create external JavaScript file and embed it in many html page.
 It provides code reusability 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.

File name is: mgs.js


function msg()
{
alert("Hello JavaScript");
}
//HTML File name is index.html
<html>
<head>
<script type="text/javascript" src="cc.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
//Note: External JavaScript file must be included in head tag of HTML

After Click on Button this alert message will be display on same browser window

 Introduction to JavaScript Documents


 JavaScript Document object is an object that provides access to all HTML elements of a
document. When an HTML document is loaded into a browser window, then it becomes a
document object.
 The document object stores the elements of an HTML document, such as HTML, HEAD,
BODY, and other HTML tags as objects.
 A document object is a child object of the Window object, which refers to the browser.
 You can access a document object either using window.document property or using object
directly.
JavaScript Document Object Methods
We can access and change the contents of document by its methods.
The important methods of document object are as follows:

Method Description
write("string") writes the given string on the doucment.
writeln("string") writes the given string on the doucment with newline character at the
end.
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.

 JavaScript comments
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.

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.
Example of single-line comment
<script>
// It is single line comment
document.write("hello JavaScript");
</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:
/* your code here */
It can be used before, after and middle of the statement.
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of JavaScript multiline comment");
</script>
 JavaScript Variable
A JavaScript variable is simply a name of storage location.
There are two types of variables in JavaScript:
1. Local variable
2. Global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2. After 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.
JavaScript variables Syntax
var x = 10;
var _value="sonoo";
Example: //Sum of two variables
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
1. JavaScript local variable
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>
2. 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:
<html>
<body>
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data); }
function b(){
document.writeln(data); }
a();//calling JavaScript function
b();
</script>
</html>
</body>
 Data Types
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:
var a=40;//holding number
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:
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:
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
1. Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands. The following
operators are known as JavaScript arithmetic operators.
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

2. Relational Operators
The JavaScript comparison operator compares the two operands. The comparison operators are
as follows:
Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of same 10==20 = false


type)

!= 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


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

~ Bitwise NOT (~10) = -10

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

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

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


Zero

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


5. Assignment Operators
The following operators are known as JavaScript assignment operators.
Operator Description Example

= 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


6. 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 statement.

delete Delete Operator deletes a property from the object.

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 If-else
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.
1. If Statement
2. If else statement
3. if else if statement
If Statement
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
JavaScript If...else Statement
It evaluates the content whether condition is true of false. The syntax of JavaScript if-else
statement is given below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
// Program for find out even or odd number
<html>
<body>
<script>
var a=20;
if(a%2==0){
document.write("a is even number"); }
else{
document.write("a is odd number"); }
</script>
</body>
</html>
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is given below.
<script>
var a=20;
if(a==10){
document.write("a is equal to 10"); }
else if(a==15){
document.write("a is equal to 15"); }
else if(a==20){
document.write("a is equal to 20"); }
else{
document.write("a is not equal to 10, 15 or 20"); }
</script>
 JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while loops. It
makes the code compact. It is mostly used in array.
There are four types of loops in JavaScript.
1. for loop
2. while loop
3. do-while loop
1) JavaScript For loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be used if
number of iteration is known. The syntax of for loop is given below.
for (initialization; condition; increment)
{
code to be executed
}
Let’s see the simple example of for loop in javascript.
<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>
2) JavaScript while loop
The JavaScript while loop iterates the elements for the infinite number of times. It should be
used if number of iteration is not known. The syntax of while loop is given below.
while (condition)
{
code to be executed
}
Let’s see the simple example of while loop in javascript.
<script>
var i=11;
while (i<=15) {
document.write(i + "<br/>");
i++; }
</script>
3) JavaScript do while loop
The JavaScript do while loop iterates the elements for the infinite number of times like while
loop. But, code is executed at least once whether condition is true or false. The syntax of do
while loop is given below.
do{
code to be executed
}while (condition);
Let’s see the simple example of do while loop in javascript.
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
Output:
21
22
23
24
25

 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 declaring function is given below.
function functionName([arg1, arg2, ...argN]){
//code to be executed
}
JavaScript Functions can have 0 or more arguments. 7
<html>
<body>
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>
Output:
JavaScript Function Arguments
We can call function by passing arguments. Let’s see the example of function that has one
argument.
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Function with Return Value
We can call function that returns a value and use it in our program. Let’s see the example of
function that returns value.
<script>
function getInfo(){
return "hello ! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
 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
direct 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:
object={
property1:value1,property2:value2.....propertyN:valueN
}
As you can see, property and value is separated by: (colon).
Simple example of creating object in JavaScript:
<script>
emp={
id:102,name:"Shyam Kumar",salary:40000
}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Output:
102 Shyam Kumar 40000
2) By creating instance of Object
The syntax of creating object directly is given below:
var object_name=new Object();
Here, new keyword is used to create object.
Let’s see the example of creating object directly.
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
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.
The example of creating object by object constructor is given below.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
Output:
103 Vimal Jaiswal 30000

 JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
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:
var arrayname=[value1,value2.....valueN];
values are contained inside [ ] and separated by , (comma).
Let's see the simple example of creating and using array in JavaScript.
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
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.
Let's see the example of creating array directly.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
3) JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so that we don't
have to provide value explicitly.
The example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Array Properties
Here is a list of the properties of the Array object along with their description.

Sr.No. Property & Description


1 constructor
Returns a reference to the array function that created the object.

2 index
The property represents the zero-based index of the match in the string
3 input
This property is only present in arrays created by regular expression matches.
4 length
Reflects the number of elements in an array.
5 prototype
The prototype property allows you to add properties and methods to an object.

Introduction to Forms

Forms are the basics of HTML. We use HTML form element in order to create
the JavaScript form. For creating a form, we can use the following sample code:

<html>
<head>
<title> Login Form</title>
</head>
<body>
<h3> LOGIN </h3>
<form form ="Login_form" onsubmit="submit_form()">
<h4> USERNAME</h4>
<input type="text" placeholder="Enter your email id"/>
<h4> PASSWORD</h4>
<input type="password" placeholder="Enter your password"/></br></br>
<input type="submit" value="Login"/>
<input type="button" value="SignUp" onClick="create()"/>
</form>
</html>
In the code:
o Form name tag is used to define the name of the form. The name of the form here is
"Login_form". This name will be referenced in the JavaScript form.
o The action tag defines the action, and the browser will take to tackle the form when it is
submitted. Here, we have taken no action.
o The method to take action can be either post or get, which is used when the form is to be
submitted to the server. Both types of methods have their own properties and rules.
o The input type tag defines the type of inputs we want to create in our form. Here, we have
used input type as 'text', which means we will input values as text in the textbox.
o Net, we have taken input type as 'password' and the input value will be password.
o Next, we have taken input type as 'button' where on clicking, we get the value of the form
and get displayed.
Other than action and methods, there are the following useful methods also which are provided
by the HTML Form Element
o submit (): The method is used to submit the form.
o reset (): The method is used to reset the form values.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy