46357(1)

45
INTERNET: Internet: the network of networks connected via the public backbone and communicating using TCP/IP communication protocol Global Communication Network Commercial Internet dial-up access offered Economic Increase network usage Reduced unit cost Backbone initially supplied by NSFNET, privately funded (ISP fees) beginning in 1995 Private telecommunication firms TCP/IP: TCP/IPà Single Protocol TCP/IP actually two different protocols. TCP-transport Layer IP-Network layer Treated as one some bulk of services are built on the top of both the TCP and IP protocols -> e-mail, Web browsing, File downloads, accessing remote databases INTERNET PROTOCOL: IP is the fundamental protocol defining the Internet (as the name implies!)

description

Studies

Transcript of 46357(1)

INTERNET:

Internet: the network of networks connected via the public backbone and communicating using TCP/IP communication protocol

Global Communication Network

Commercial Internet dial-up access offered

Economic

Increase network usage

Reduced unit cost

Backbone initially supplied by NSFNET, privately funded (ISP fees) beginning in 1995

Private telecommunication firms

TCP/IP:

TCP/IP( Single Protocol

TCP/IP actually two different protocols.

TCP-transport Layer IP-Network layer

Treated as one some bulk of services are built on the top of both the TCP and IP protocols

-> e-mail, Web browsing, File downloads, accessing remote databases

INTERNET PROTOCOL:IP is the fundamental protocol defining the Internet (as the name implies!)

Internet protocols developed as part of ARPANET research

ARPANET began using TCP/IP in 1982

Designed for use both within local area networks (LANs) and between networks

IP address:

32-bit number (in IPv4)

Each device on the internet has one or more IP addresses

Written as four dot-separated bytes, e.g. 192.0.34.166

Each decimal number represents one byte of the IP address

IP function: transfer data from source device to destination device

IP source software creates a packet representing the data

Header: source and destination IP addresses, length of data, etc.

Data itself

If destination is on another LAN, packet is sent to a gateway that connects to more than one network

Gateway is a device that is connected to the source computers network as well as to at least one other network.

The sequence of computers that a packet travels through from source to destination is known as its route.

How does the computer choose the next computer in the route for a packet?

A separate protocol BGP-4 is used to pass network connectivity information between gateways so that each computer can choose a good next hop for each packet it receives.

IP software adds error detection information ( a checksum) to each packet

Limitations of IP: No guarantee of packet delivery (packets can be dropped)

Unreliable

Communication is one-way (source to destination)

TRANSMISSION CONTROL PROTOCOL (TCP): TCP is a higher-level protocol extends IP to provide additional functionality

Reliable communication based on the concept of communication

TCP adds concept of a connection on top of IP

Provides guarantee that packets delivered

Provide two-way (full duplex) communication

A and B both send messages to one another at the same time.

Reliable data transmission by demanding an ACK for each packet it sends via IP

Splitting longer messages into shorter ones

Reassembling on receiver side.

TCP also adds concept of a port

The port concept allows TCP to communicate with many different applications on a machine.

TCP header contains port number representing an application program on the destination computer

Some port numbers have standard meanings

Example: port 25 is normally used for email transmitted using the Simple Mail Transfer Protocol (SMTP)

Other port numbers are available first-come-first served to any application

Assigned by IANA(Internet Assigned numbers Authority)

0-1023 requested only by the applications that are run by the system at boot-up

1024-65535 used by the first application on a system

USER DATAGRAM PROTOCOL (UDP): Like TCP in that:

Builds on IP

Provides port concept

Unlike TCP in that:

No connection concept

No transmission guarantee

No two way connection

Advantage of UDP vs. TCP:

Lightweight, so faster for one-time messages

less complexity in order to reduce overhead

HIGHER-LEVEL PROTOCOLS: IP ~ the telephone network

TCP ~ calling someone who answers, having a conversation, and hanging up

UDP ~ calling someone and leaving a message

DNS ~ directory assistance (names with numbers)

Many protocols build on TCP

Telephone analogy: TCP specifies how we initiate and terminate the phone call, but some other protocol specifies how we carry on the actual conversation

Some examples:

SMTP (email)

FTP (file transfer)

HTTP (transfer of Web documents)

Primary TCP-based protocol used for communication between web servers and browsers called HTTP

IP is key component in the definition of Internet

HTTP -( WWW

1.3 World Wide Web

Unique feature of Web: support for hypertext (text containing links)

Communication via Hypertext Transport Protocol (HTTP)

Document representation using Hypertext Markup Language (HTML)

The Web is the collection of machines (Web servers) on the Internet that provide information, particularly HTML documents, via HTTP.

Machines that access information on the Web are known as Web clients. The web client(Web browser) is software used by an end user to access the Web.

Machines provide information to the Web are known as Web servers.Hypertext Transport Protocol (HTTP):

HTTP is based on the request-response communication model:

Client sends a request

Server sends a response

Is a Communication Protocol

HTTP is based on the request-response communication model:

Client sends a request

Server sends a response

Format of the message is dictated by HTTP

HTTP send the message using TCP

HTTP is a stateless protocol:

The protocol does not require the server to remember anything about the client requests.

Each request is executed independently, without any knowledge of the requests that came before it

Normally implemented over a TCP connection (80 is standard port number for HTTP)

Typical browser-server interaction: User enters Web address in browser

Browser uses DNS to locate IP address

Browser opens TCP connection to server

Browser sends HTTP request over connection

Server sends HTTP response to browser over connection

Browser displays body of response in the client area of the browser window

HTTP Request Header

Connect to 67.228.171.112 on port 80 ... ok

GET / HTTP/1.0[CRLF]Host: www.stjosephs.ac.in[CRLF]Connection: close[CRLF]User-Agent: Web-sniffer/1.0.46 (+http://web-sniffer.net/)[CRLF]Accept-Encoding: gzip[CRLF]Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7[CRLF]Cache-Control: no-cache[CRLF]Accept-Language: de,en;q=0.7,en-us;q=0.3[CRLF]Referer: http://web-sniffer.net/[CRLF][CRLF]HTTP Response Header

NameValueDelim

Status: HTTP/1.1 200 OK

Date:Tue, 17 Dec 2013 04:23:26 GMT

Server:Apache/2.2.24 (Unix) mod_ssl/2.2.24 OpenSSL/1.0.0-fips mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635

Last-Modified:Sat, 30 Nov 2013 09:20:55 GMT

ETag:"1f02cce-4644-4ec6176bf4b9f"

Accept-Ranges:bytes

Content-Length:17988

Connection:close

Content-Type:text/html

HTTP REQUEST

Connect to 67.228.171.112 on port 80 ... ok

GET / HTTP/1.0[CRLF] ----------------start lineHost: www.stjosephs.ac.in[CRLF] request uriConnection: close[CRLF]User-Agent: Web-sniffer/1.0.46 (+http://web-sniffer.net/)[CRLF]Accept-Encoding: gzip[CRLF]Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7[CRLF]Cache-Control: no-cache[CRLF]Accept-Language: de,en;q=0.7,en-us;q=0.3[CRLF]Referer: http://web-sniffer.net/[CRLF] Each request message begins with a request line (START LINE), which contains three critical pieces of information: After the start line come a set of message headers related to the request, followed by a blank line and then optionally, the message body of the request as shown below

Structure of Request:

start line

header field(s)

blank line

optional body

Start line

A start line (which contains the method the client is requesting; the URI of the resource upon which the client wishes the action to be performed and the version of HTTP that the client is using). Example: GET / HTTP/1.1

Three space-separated parts:

HTTP request method

Request-URI

HTTP version

Request methods:

HEADUsed to ask only for information about a document, not for the document itself. It's often used by clients who use caching, to see if the document has changed since it was last accessed.

GETRequests a representation of the specified resource.

POSTSubmits data to be processed to the identified resource.

PUTUploads a representation of the specified resource.

DELETEDeletes the specified resource.

TRACEEchoes back the received request, so that a client can see what (if any) changes or additions have been made by intermediate servers.

OPTIONSReturns the HTTP methods that the server supports for specified URL

Request URI:

URIs are of two types:

Uniform Resource Name (URN)

Can be used to identify resources with unique names, such as books (which have unique ISBNs)

Uniform Resource Locator (URL)

Specifies location at which a resource can be found

In addition to http, some other URL schemes are https, ftp, mailto, and file

Header field structure:

After the request line come any of the headers that the client wants to include in the message; it is in these headers that details are provided to the server about the request. The headers all use the same structure as

field name : field value

Syntax

Field name is not a case sensitive

Field values may contain MIME types (Multipurpose Internet Mail Extensions), quality values. MIME is a convention for specifying content type of a message.

Some common content types:,

MIME Type Description

text/plain Plain text. Default if data is primarily text and no other type detected.

text/html HTML. Default if common tags detected and server does not supply image/* type.

image/gif Graphics Interchange Format (GIF).

image/jpeg JPEG image.

application/octet-stream Binary file. Default if data is primarily binary.

HTTP RESPONSE :After receiving and interpreting a request message, a server responds with an HTTP response message.

NameValue

Status: HTTP/1.1 200 OK

Date:Tue, 17 Dec 2013 04:23:26 GMT

Server:Apache/2.2.24 (Unix) mod_ssl/2.2.24 OpenSSL/1.0.0-fips mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635

Last-Modified:Sat, 30 Nov 2013 09:20:55 GMT

ETag:"1f02cce-4644-4ec6176bf4b9f"

Accept-Ranges:bytes

Content-Length:17988

Connection:close

Content-Type:text/html

Structure of the response:

status line

header field(s)

blank line

optional body

Status line: The first line of a Response message is the Status-Line, consisting of the protocol version followed by a numeric status code and its associated textual phrase.

Example: HTTP/1.1 200 OK

It has three space-separated parts:

HTTP version

status code

reason phrase in text (intended for human use)

Status code: to display the status of the response message

is a three-digit number

Classified into five classes. First digit is class of the status code:

1xx: Informational Request received, continuing process

2xx: SuccessThe action was successfully received, understood, and accepted

3xx: Redirection

Further action must be taken in order to complete the request

4xx: Client ErrorThe request contains bad syntax or cannot be fulfilled

5xx: Server Error The server failed to fulfill an apparently valid request

Some common status codes:

200: OK.

302: This code indicates that a page has been temporarily redirected to another URL. This means that the page is still active, just temporarily moved to another URL.

403: Some of you may have come across this, also known as the Forbidden Request. Basically it means that you have made a legal request, but the server is refusing to respond to it.

404: The most common of the Broken Site Errors! Basically this is where the URL no longer exists or cannot be found, so you will be redirected to a broken holding page.

500: Just a generic Server error message, this comes up when there is nothing else to explain a problem.

501: This is where the Server you a requesting information from does not understand the method in which you are requesting the information, or there is not a fulfilled request.

502: Simply an invalid response was received by the server, from the request that you have made.

Common header fields:

Accept-Ranges What partial content range types this server supports

Date The date and time that the message was sent

Last-Modified The last modified date for the requested object

Expires Gives the date/time after which the response is considered old

ETag A hash code of the resource returned

Location Used in redirection, or when a new resource has been created

Server A name for the server

Links: Hyperlinks are produced by the anchor element Clicking on a hyperlink causes browser to issue GET request to URL specified in href attribute and render response in client areaMotive element called anchor. Link has two ends : anchors and directionAnchors can be used as source (previous example) or destinationSource anchors

A source anchor is created in anHTMLdocument (webpage) by adding an anchor element () with a hypertext reference (href) containing a uniform resource identifier (URI).Eg:MotiveDestination anchors

To link to a point within a webpage, for example to link to content below thefirst fold, a destination anchor must be added.

A destination anchor is created by adding a fragment identifier, this is either:

An anchor element, with anameattribute, or

Any other element, with anidattribute.Eg:

Introduction

Some background

On a more personal note
..Introduction

...section 1...

Some background

...section 2...

On a more personal note

...section 2.1...

ABSOLUTE URLAND RELATIVE URLAbsolute URLAnAbsolute URLis, thus, something that isindependentorfree from any relationship. When you use an absolute URL, you point directly to a file. Hence, an absolute URL specifies theexactlocation of a file/directory on the internet. It also follows that each absolute URL is uniqueEg: http://www.webdevelopersnotes.com/images/email.gifspecifies an image fileemail.giflocated in theimagesdirectory, under www.webdevelopersnotes.com domain name.Relative URLArelative URLpoints to a file/directory in relation to the present file/directoryUsing an Absolute URL in antag Using a Relative URL in an tag.We, thus, instruct the browser to first go one level up (i.e. to thedocument root) and then move to theimagesdirectory and pick up the fileemail.gif. The two peroids (..) instruct the server to move up one directory (which is therootdirectory)Adv: It is easy to transfer a web site from one domain name to another. Also, relative URLs would be shorter than absolute URLs and hence the file size of the web page would reduce.XHTML DTD: XML is used to define the syntax of XHTML Set of XML files that define a language are known as the document type definition (DTD) DTD primarily consists of declarations: Element type: name and content of elements Attribute list: attributes of an element Entity: define meaning of, e.g., >Eg:

lang

NMTOKEN #IMPLIED

xml:langNMTOKEN #IMPLIED

dir

(ltr|rtl) #IMPLIED

id ID

#IMPLIED

xmlns CDATA #FIXED 'http://www.w3.org/1999/xhtml' >

1) Element type:

Used to specify the set of all valid elements in the language defined by DTDEg:

Content Specification:

Eg: -> Sequence

-> Empty

Eg:

2) Attribute List Declaration:

Provides information about the valid attributes for an element

Eg:

lang

NMTOKEN #IMPLIED

xml:langNMTOKEN #IMPLIED

dir

(ltr|rtl) #IMPLIED

id ID

#IMPLIED

xmlns CDATA #FIXED 'http://www.w3.org/1999/xhtml' >Eg 1:

Valid XML:

Invalid XML:

Eg 2:

Valid XML:

Invalid XML:

3) ENTITY DECLARATION:

Entity declaration is essentially a macro Two types of entity: General: referenced from HTML document using & Parameter: reference from DTD using % Eg:

if a>b -> Prints a>b

UNIT-2SELECTOR STRING:Consist of two parts

Selector string-Indicates the elements to which the rule should apply

Declaration block in { }-Specifies a value for one style property of those elements

List of declaration separated by semicolons

It is syntactically legal to split rules over several lines or write multiple rules on a single line

Parts of a style rule (or statement)

Selector Strings

Type selector :Each of the selector simply the name of an element type

h1,h2,h3,h4,h5,h6 { background-color : purple }

Universal selector : Every possible element type

* { font-weight : bold }

ID selector :

#p1, #p3 { background-color : aqua }

Paragraph with id="P1" and class="takeNote".

.

.

.

This paragraph (id="p3") contains a

hyperlink.

Class selector :

#p1, .takeNote { font-style : italic }

span.special { font-size : x-large }

The difference between an ID and a class is that an ID can be used to identify one element, whereas a class can be used to identify more than one.

Descendant selector : used to select elements that are descendants of another element in the document tree.

ul span { font-variant : small-caps }

ul ol li { letter-spacing : lem }

Predefined pseudo classes associated with anchor element a:link { color : black } link that has not been visited recently

a:visited { color : yellow } visited once next time loaded a:hover { color : green } positioning cursor over link without clicking the mouse button cause link to change green a:active { color : red } - clicking and holding the mouse button change the colour to redDIFFERENT TYPES OF STYLESHEETS:1. To create an inline style

a. Add the style attribute to the HTML tag.

b. The style declaration must be enclosed within double quotation marks.

2. To create an embedded style

a. Insert a tag within the head section of HTML file.

b. Within the tag, enclose the style declarations need to the entire Web page.

c. The style sheet language identifies the type of style used in the document.

d. The default and the most common language is text/css for use with CSS.

3. To create an External styles

a. Create a text file containing style declarations

b. Create a link to that file in each page of the Web site using a tag.

c. Specify the link attributes, such as href, rel, and type.

d. Link a style sheet, the value of the href attribute should be the URL of the linked document, the value of the rel attribute should be stylesheet and the value of the type attribute should be text/css.

4. Write the source code for the separate style sheet and finally terminate the program.

Definitions:

Inline styles are added to each tag within an HTML file using Style attribute.

Embedded styles are applied to an entire HTML file using Style element.

External style sheets are placed in an external file and linked with pages in the Web site.

PROGRAM:

EXTERNAL.CSS

body{background-color:green;}

p{color:blue;}

h3{color:white;}

ul.a {list-style-type: square;}

ul.b {list-style-type: circle;}

ol.c{list-style-type:upper-roman;}

ol.d{list-style-type:lower-alpha;}

#hi{text-color:white;}

body{background-image:url('tamilnadu.jpg');}

h1{text-align:center;}

p.date{text-align:right;}

EXTERNAL.HTML

EXTERNAL STYLE SHEET

a white header

  • liststyletype-circle
  • liststyletype-circle
  • liststyletype-circle
  1. upper-roman
  2. upper-roman
  1. lower_alpha
  2. lower_alpha

This paragraph has a blue font .the back ground colour is green because of external style sheet

INTERNAL.HTML

body{background-color:grey;}

p{color:white;}

ul.a {list-style-type: circle;}

ul.b {list-style-type: square;}

#p1{font-family:"Times New Roman",Times,serif;}

INTERNAL STYLE SHEET

  • liststyletype:square
  • liststyletype:square

This page USES internal css using style tag

INLINE.HTML

inline css

INLINE STYLE SHEET

This page uses inline css using style attribute

Inline Style Sheet has the highest priority amomg all style sheets

Text color is blue and margin left width is 20px.

STYLE RULE CASCADING:

*{ font-weight : bold } applies to every element of HTML

#p1, #p3 { background-color : aqua }

#p3{ font-weight : normal }

What if more than one style declaration applies to a property of an element?Multiple declaration

Browser applies rule cascading

A multistage sorting process that selects a single declaration that supply the property value

The CSS rule cascade determines which style rules declaration applies

Once declaration identified, associate origin and weight with every declaration

PERSON WHO WROTE THE DOCUMENT PERSON WHO IS VIEWING THE DOCUMENT PERSON WHO WROTE THE BROWSER SOFTWARE Origin of a declaration is one of the following: Author-> declaration is part of an external or embed style sheet or part of the value specified by style attribute User agent >A browser define default style property values for HTML elements User-> Modern browsers allow users to provide a style sheet

User style rules defined in two ways: Edit|Preferences|Appearance, Fonts and colors panels allow a user to select various style options

User can explicitly create a style sheet file the browser will input when it is started

Features provided by IE6

Tools|Internet Options Two weight values

Normal

Important

User/important highest priority in CSS to accommodate users with special needs

Rules made important by adding !important:

Cascading orderWhat style will be used when there is more than one style specified for an HTML element?

All the styles will "cascade" into a new "virtual" style sheet by the following rules, where number four has the highest priority:

Browser default External style sheet Internal style sheet (in the head section) Inline style (inside an HTML element)So, an inline style (inside an HTML element) has the highest priority, which means that it will override a style defined inside the tag, or in an external style sheet, or in a browser (a default value).

Note: If the link to the external style sheet is placed after the internal style sheet in HTML , the external style sheet will override the internal style sheet!

STYLE INHERITANCE:Cascading based on structure of style sheets

Inheritance based on tree structure of document

What if no style declaration applies to a property of an element?

Generally, the property value is inherited from the nearest ancestor element that has a value forthe property

If no ancestor has a value (or the property does not inherit) then CSS defines an initial value that is used

Property values:

Specified: value contained in declaration

Absolute: value can be determined without reference to context (e.g., 2cm)

Relative: value depends on context (e.g., larger)

Computed: browser performs calculation depends on particular relative value

absolute representation of relative value (e.g., larger might be 1.2 x parent font size)

Actual: value actually used by browser (e.g., computed value might be rounded)

3.CSS BOX MODEL Each element of HTML , if is rendered visually occupies a rectangular area( a Box

Every box consists conceptually of a nested collection of rectangular subareas

Innermost rectangular ( Content area (actual content of the element)

Padding separates the content area from the boxs border

Margin surrounding the border

Content and margin edges not displayed in the browser(inner and outer edges of the box)

Outer edge define box width and height, inner edge define content width and height

Every rendered element occupies a box:

CSS property names corresponding to 12 distances between adjacent edges in the box model

Box Model shorthand propertiesPADDING:

EMBED PBrush BORDER:

POSITIONING METHODS IN CSS.The CSS positioning properties allow you to position an element. It can also place an Element behind another, and specify what should happen when an element's content is too big. Elements can be positioned using the top, bottom, left, and right properties. However, these properties will not work unless the position property is set first. They also work differently depending on the positioning method. There are four different positioning methods.

Static Positioning:HTML elements are positioned static by default. A static positioned element is always positioned

according to the normal flow of the page. Static positioned elements are not affected by the top,

bottom, left, and right properties.

Fixed Positioning

An element with fixed position is positioned relative to the browser window. It will not move even if the window is scrolled:

Example:p.pos_fixed

{

position:fixed;

top:30px;

right:5px;}Note: Internet Explorer supports the fixed value only if a !DOCTYPE is specified.Fixed positioned elements are removed from the normal flow. The document and other elements behave like the fixed positioned element does not exist. Fixed positioned elements can overlap other elements.Relative PositioningA relative positioned element is positioned relative to its normal position.

Example

h2.pos_left

{

position:relative;

left:-20px;

}

h2.pos_right

{

position:relative;

left:20px;

}

The content of a relatively positioned elements can be moved and overlap other elements, but the reserved space for the element is still preserved in the normal flow.

Example

h2.pos_top

{

position:relative;

top:-50px;

}

Relatively positioned element are often used as container blocks for absolutely positioned elements.

Absolute Positioning

An absolute position element is positioned relative to the first parent element that has a Position other than static. If no such element is found, the containing block is : Example

h2

{

position:absolute;

left:100px;

top:150px;

}

Absolutely positioned elements are removed from the normal flow. The document and other elements behave like the absolutely positioned element does not exist.Absolutely positioned elements can overlap other elements.Float positioning

Float property( none, left, and right

Moves the element box to far left or right

OBJECTS:

An object is a set of properties

A property consists of a unique (within an object) name with an associated value

The type of a property depends on the type of its value and can vary dynamically

Object properties do not have data types

Ex: Single property prop of an object o

There are no classes in JavaScript

Object constructors defined to create objects and automatically define properties for the objects created

Instead, properties and methods can be created and deleted dynamically

Objects are created using new expressionFirst line creates a variable named o1 initialize its value of type object by calling built-in constructor Object()

Second line adds a property named testing to the o1 object and assigns a string value to this property

A constructor is a function-

Constructor performs initialization on the object

Can add properties and methods to object

Can add object to an inheritance hierarchy from which it can inherit additional properties and methods

The Object() built-in constructor

Does not add any properties or methods directly to the object

default toString() and valueOf() methods (used for conversions to String and Number, resp.) Assign a value to an object property

Property with the given name is created in the object and assigned the specified value

delete used to remove a property from an object

delete o1.testing;

Object initializer notation can be used to create an object (using Object() constructor) and one or more properties in a single statement

Enumerating Properties

To know which property an object has at any given time

Special form of for statement used to iterate through all properties of an object:

Array notation

To print the values of those properties The JavaScript object dot notation is actually shorthand for a more general associative array notation in which Strings are array indices:

Expressions can supply property names:

Two different notations for accessing properties

Dot notation

Array reference syntax index is viewed as string value hash

Object can be viewed as a sort of array in which the elements are indexed by strings called associative array

Object reference

StringBuffer s1 = new StringBuffer(Hello);

StringBuffer s2 = s1;

Single StringBuffer is created and both s1 and s2 will be references to it

Copies the reference from s1 to s2

If code followed by s2. append(World!);

System.out.println(s1);Output: Hello World!.Methods JavaScript functions are stored as values of type Object

A function declaration creates a function value and stores it in a variable (property of window) having the same name as the function

A method is an object property for which the value is a function

ARRAY

An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

var car1 = "Saab";

var car2 = "Volvo";

var car3 = "BMW";

Creating an Array

Using an array literal is the easiest way to create a JavaScript Array.

Syntax:

var array-name = [item1, item2, ...];

Example:

var cars = ["Saab", "Volvo", "BMW"];

Using the JavaScript Keyword new

The following example also creates an Array, and assigns values to it:

Example: var cars = new Array("Saab", "Volvo", "BMW");

Access the Elements of an Array

You refer to an array element by referring to the index number.

This statement access the value of the first element in myCars:

var name = cars[0];

This statement modifies the first element in cars:

cars[0] = "Opel";

Note[0] is the first element in an array. [1] is the second. Array indexes start with 0.

Different Objects in One Array

JavaScript variables can be objects. Arrays are special kinds of objects.

Because of this, you can have variables of different types in the same Array.

You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

myArray[0] = Date.now;

myArray[1] = myFunction;

myArray[2] = myCars;

Arrays are Objects

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.But, JavaScript arrays are best described as arrays. Arrays use numbers to access its "elements". In this example, person[0] returns John:

Array: var person = ["John", "Doe", 46];

Object: var person = {firstName:"John", lastName:"Doe", age:46};

Array Properties and Methods

The real strength of JavaScript arrays are the built-in array properties and methods:

Examples

var x = cars.length; // The length property returns the number of elements in cars

var y = cars.sort(); // The sort() method sort cars in alphabetical order

The length Property

The length property of an array returns the length of an array (the number of array elements).Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.length; // the length of fruits is 4

Adding Array Elements

The easiest way to add a new element to an array is to use the length property:

Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits

Adding elements with high indexes can create undefined "holes" in an array:

Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits[10] = "Lemon"; // adds a new element (Lemon) to fruits

Looping Array Elements

The best way to loop through an array is using a standard for loop:

Example

var index; var fruits = ["Banana", "Orange", "Apple", "Mango"];

for(index = 0; index < fruits.length; index++)

{ text += fruits[index]; }

Dynamically changing Array length Properties to an array can be added.

Changing the number of elements

Elements can be removed by decreasing

the value of length property

Creates an array with length 200 but does not

create or initialize the properties

Value of length is not necessarily the same as the actual number of elements

Array methods

JAVASCRIPT PROGRAM TO FIND FACTORIAL OF A GIVEN NUMBER

var n = parseInt(window.prompt("Enter the Number:"));

var result = fact(n);

window.alert("Factorial of the given number " + result);

function fact(n)

{

if(n == 0)

return 1;

else

return (n*fact(n-1));

}

JAVASCRIPT PROGRAM TO FIND LARGEST AMONG FIVE NUMBERS

var number1, number2, number3,number4, number5,largest;

largest = number1 = window.prompt("Please input first number", 0);

number2 = window.prompt("Please input second number", 0);

number3 = window.prompt("Please input third number", 0);

number4 = window.prompt("Please input fourth number", 0);

number5 = window.prompt("Please input fifth number", 0);

if ( number2 > largest )

largest = number2;

if (number3 > largest)

largest = number3;

if (number4 > largest)

largest = number4;

if (number5 > largest)

largest = number5;

document.write("The largest number among " + number1 + ", " + number2 + ", " + number3 + ", " + number4 + ", and " + number5 + " is " + largest + "
");

Click refresh to reload JavaScript

JAVASCRIPT PROGRAM TO FIND SUM OF FIRST N EVEN NUMBER

Function series()

{

var i=0

var n=document.f1.t1.value;

while(i