0% found this document useful (0 votes)
3 views124 pages

MODULE 1 (3)

The document provides an overview of web page design using HTML and scripting, covering client-side and server-side scripting, JavaScript, and web technologies like HTML5 and CSS3. It traces the history of the Internet and the World Wide Web, highlighting key developments and protocols such as HTTP and MIME. Additionally, it discusses various programming tools and languages used in web development, including PHP, Java, and Ruby on Rails.

Uploaded by

rekhadivya121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views124 pages

MODULE 1 (3)

The document provides an overview of web page design using HTML and scripting, covering client-side and server-side scripting, JavaScript, and web technologies like HTML5 and CSS3. It traces the history of the Internet and the World Wide Web, highlighting key developments and protocols such as HTTP and MIME. Additionally, it discusses various programming tools and languages used in web development, including PHP, Java, and Ruby on Rails.

Uploaded by

rekhadivya121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 124

SCRIPTING

Web page Designing using HTML, Scripting basics- Client side and server side scripting. Java Script Object,
names, literals, operators and expressions- statements and features- events - windows - documents - frames -
data types - built-in functions- Browser object model - Verifying forms.-HTML5- CSS3- HTML 5 canvas - Web
site creation using tools.

Introduction to Internet:- A global computer network providing a variety of information and


communication facilities, consisting of interconnected networks using standardized
communication protocols. "the guide is also available on the Internet"

The Internet is the global system of interconnected computer networks that use the
Internetprotocol suite (TCP/IP) to link devices worldwide. It is a network of networks that
consists of private, public, academic, business, and government networks of local to global
scope, linked by a broad array of electronic, wireless, and optical networking technologies. The
Internet carries a vast range of information resources and services.

History of Internet
This marvelous tool has quite a history that holds its roots in the cold war scenario. A
need was realized to connect the top universities of the United States so that they can share all
the research data without having too much of a time lag. This attempt was a result of Advanced
Research Projects Agency (ARPA) which was formed at the end of 1950s just after the Russians
had climbed the space era with the launch of Sputnik. After the ARPA got success in 1969, it
didn‘t take the experts long to understand that how much potential can this interconnection tool
have. In 1971 Ray Tomlinson made a system to send electronic mail. This was a big step in the
making as this opened gateways for remote computer accessing i.e.telnet.

During all this time, rigorous paper work was being done in all the elite research
institutions. From giving every computer an address to setting out the rules, everything was
getting penned down. 1973 saw the preparations for the vital TCP/IP and Ethernet services. At
the end of 1970s, Usenet groups had surfaced up. By the time the 80s had started, IBM came up
with its PC based on Intel 8088 processor which was widely used by students and universities for
it solved the purpose of easy computing. By 1982, the Defense Agencies made the TCP/IP
compulsory and the term ―internet‖ was coined. The domain name services arrived in the year
1984 which is also the time around which various internet based marked their debut. A worm, or
a rust the computers, attacked in 1988 and disabled over 10% of the computer systems all over
the world. While most of the researchers regarded it as an opportunity to enhance computing as it
was still in its juvenile phase, quite a number of computer companies became interested in
dissecting the cores of the malware which resulted to the formation Computer Emergency
Rescue Team (CERT). Soon after the world got over with the computer worm, World Wide Web
came into existence. Discovered by Tim Berners-Lee, World Wide Web was seen as a service to
connect documents in websites usinghyperlinks.

orld Wide Web


The World Wide Web (abbreviated WWW or the Web) is an information space where
documents and other web resources are identified by Uniform Resource Locators (URLs),
interlinked by hypertext links, and can be accessed via the Internet. English scientist
TimBerners-Lee invented the World Wide Web in 1989. He wrote the first web browser
computerprogram in 1990 while employed at CERN in Switzerland. The Web browser was
released outside CERN in 1991, first to other research institutions starting in January 1991 and to
the general public on the Internet in August 1991.
The World Wide Web has been central to the development of the Information Age and is
the primary tool billions of people use to interact on the Internet. Web pages are primarily text
documents formatted and annotated with Hypertext Markup Language (HTML). In addition to
formatted text, web pages may contain images, video, audio, and software components that are
rendered in the user's web browser as coherent pages of multimedia content.
Embedded hyperlinks permit users to navigate between web pages. Multiple web pages
with a common theme, a common domain name, or both, make up a website. Website content
can largely be provided by the publisher, or interactively where users contribute content or the
content depends upon the users or their actions. Websites may be mostly informative, primarily
for entertainment, or largely for commercial, governmental, or non-governmental organizational
purposes

WWW is another example of client/server computing. Each time a link is followed, the client is
requesting a document (or graphic or sound file) from a server (also called a Web server) that's
part of the World Wide Web that "serves" up the document. The server uses a protocol called
HTTP or Hyper Text Transport Protocol. The standard for creating hypertext documents for the
WWW is Hyper Text Markup Language or HTML. HTML essentially codes plain text
documents so they can be viewed on the Web.

Browsers:
WWW Clients, or "Browser": The program you use to access the WWW is known as a
browser because it "browses" the WWW and requests these hypertext documents. Browsers can
be graphical, allows to see and hear the graphics and audio;

text-only browsers (i.e., those with no sound or graphics capability) are also available. All of
these programs understand http and other Internet protocols such as FTP, gopher, mail, and
news, making the WWW a kind of "one stop shopping" for Internetusers.
1991 World Wide Web (Nexus)
1992 Viola WWW, Erwise, MidasWWW, MacWWW (Samba)
1993 Mosaic,Cello,[2] Lynx 2.0, Arena, AMosaic 1.0
IBM WebExplorer, Netscape Navigator, SlipKnot 1.0, MacWeb, IBrowse, Agora
1994
(Argo), Minuet
Internet Explorer 1, Internet Explorer 2, Netscape Navigator 2.0, OmniWeb,
1995 UdiWWW, Grail

Arachne 1.0, Internet Explorer 3.0, Netscape Navigator 3.0,Opera 2.0,


1996
PowerBrowser 1.5,[4] Cyberdog,Amaya 0.9,[5] AWeb,Voyager
Internet Explorer 4.0, Netscape Navigator 4.0, Netscape Communicator 4.0,
1997
Opera3.0,[6] Amaya 1.0[5]
1998 iCab, Mozilla
1999 Amaya 2.0,[5] Mozilla M3, Internet Explorer 5.0
Konqueror,Netscape 6, Opera 4,[7] Opera 5,[8] K-Meleon 0.2, Amaya 3.0,[5] Amaya
2000 4.0[5]

2001 Internet Explorer 6, Galeon 1.0, Opera 6,[9] Amaya 5.0[5]


2002 Netscape 7, Mozilla 1.0, Phoenix 0.1, Links 2.0, Amaya 6.0,[5] Amaya 7.0[5]
2003 Opera 7,[10] Apple Safari 1.0, Epiphany 1.0, Amaya 8.0[5]
2004 Firefox 1.0, Netscape Browser, OmniWeb 5.0
Opera8,[11]Apple Safari2.0, Netscape Browser 8.0, Epiphany 1.8, Amaya
2005
9.0,[5] AOL Explorer 1.0, Maxthon 1.0,Shiira 1.0
Mozilla Firefox 2.0, Internet Explorer 7,Opera 9,[12], SeaMonkey 1.0, K-Meleon 1.0,
2006
Galeon 2.0, Camino 1.0, Avant11, iCab 3
Apple Safari 3.0, Maxthon 2.0, Netscape
2007
Navigator9,NetSurf 1.0, Flock 1.0, Conkeror
Google Chrome 1, Mozilla Firefox 3, Opera 9.5,[13], Apple Safari 3.1, Konqueror 4,
2008
Amaya 10.0,[5] Flock 2, Amaya 11.0[5]
Google Chrome 2–3, Mozilla Firefox 3.5, Internet Explorer 8,Opera 10,[14], Apple
2009 Safari 4, SeaMonkey 2, Camino 2,surf, Pale Moon 3.0[15]

Google Chrome 4–8, Mozilla Firefox 3.6, Opera 10.50,[16], Opera 11, Apple Safari 5,
2010
K-Meleon 1.5.4,
Google Chrome 9–16, Mozilla Firefox 4-9, Internet Explorer 9,Opera 11.50, Apple
2011 Safari 5.1, Maxthon 3.0, SeaMonkey 2.1–2.6

Google Chrome 17–23, Mozilla Firefox 10–17, Internet Explorer 10, Opera 12, Apple
2012
Safari 6, Maxthon 4.0, SeaMonkey 2.7-2.14
Google Chrome24–31,Mozilla Firefox 18–26,Internet Explorer 11, Opera
2013
15– 18, Apple Safari 7, SeaMonkey 2.15-2.23
2014 Google Chrome 32–39, Mozilla Firefox 27–34, Opera 19–26, Apple Safari 8
2015 Google Chrome 40–47, Microsoft Edge,Mozilla Firefox 35–43, Opera 27–34, Vivaldi
Google Chrome 48–55,Mozilla Firefox 44–50,Microsoft Edge 14,
2016 Opera35– 42, Apple Safari 10, SeaMonkey 2.24–2.30, Pale Moon 26.0.0[17], Pale
Moon
27.0.0[18]
Google Chrome56–60,Microsoft Edge 15,Mozilla Firefox 51–55.0.2, Opera43–
2017
45, Opera Neon
Uniform Resource Locators, or URLs: A Uniform Resource Locator, or URL is the address of
a document found on the WWW. Browser interprets the information in the URL in order to
connect to the proper Internet server and to retrieve your desired document. Each time a click on
a hyperlink in a WWW document instructs browser to find the URL that's embedded within the
hyperlink.
The elements in a URL: Protocol://server's address/filename

Hypertext protocol:
http://www.aucegypt.eduFile Transfer
Protocol: ftp://ftp.dartmouth.eduTelnet
Protocol: telnet://pac.carl.org
News Protocol: news:alt.rock-n-roll.stones
What are Domains? Domains divide World Wide Web sites into categories based on the nature
of their owner, and they form part of a site's address, or uniform resource locator (URL).
Common top-level domainsare:

.com—commercial enterprises .mil—military site

org—organization site (non-profits, etc.) int—organizations established by


international treaty
.net—network .biz—commercial and personal

.edu—educational site (universities, schools, .info—commercial and personal


etc.)
.gov—government organizations .name—personal sites

Additional three-letter, four-letter, and longer top-level domains are frequently added.
Each country linked to the Web has a two-letter top-level domain, for example .fr is France, .ie is
Ireland.
MIME (Multi-Purpose Internet Mail Extensions):- MIME is an extension of the original
Internet e-mail protocol that lets people use the protocol to exchange different kinds of data files
on the Internet: audio, video, images, application programs, and other kinds, as well as the ASCII
text handled in the original protocol, the Simple Mail Transport Protocol (SMTP). In 1991,
Nathan Borenstein of Bellcore proposed to the IETF that SMTP be extended so that Internet (but
mainly Web) clients and servers could recognize and handle other kinds of data than ASCII text. As a
result, new file types were added to "mail" as a supported Internet Protocol file type.

Servers insert the MIME header at the beginning of any Web transmission. Clients use
this header to select an appropriate "player" application for the type of data the header indicates.
Some of these players are built into the Web client or browser (for example, all browsers come
with GIF and JPEG image players as well as the ability to handle HTML files); other players
may need to bedownloaded.
New MIME data types are registered with the Internet Assigned Numbers Authority
(IANA).
MIME is specified in detail in Internet Request for Comments 1521 and 1522, which
amend the original mail protocol specification, RFC 821 (the Simple Mail Transport Protocol)
and the ASCII messaging header, RFC 822.

Hypertext Transport Protocol:

HTTP means HyperText Transfer Protocol. HTTP is the underlying protocol used by the World
Wide Web and this protocol defines how messages are formatted and transmitted, and what
actions Web servers and browsers should take in response to various commands.
For example, when you enter a URL in your browser, this actually sends an HTTP command to
the Web server directing it to fetch and transmit the requested Web page. The other main
standard that controls how the World Wide Web works is HTML, which covers how Web pages
are formatted anddisplayed.
HTTP is called a stateless protocol because each command is executed independently, without
any knowledge of the commands that came before it. This is the main reason that it is difficult to
implement Web sites that react intelligently to user input.
HTTPS: A similar abbreviation, HTTPS means Hyper Text Transfer Protocol Secure. Basically,
it is the secure version of HTTP. Communications between the browser and website are
encrypted by Transport Layer Security (TLS), or its predecessor, Secure Sockets Layer (SSL).
The Web Programmer‟sToolbox:
 HTML - a markuplanguage
o To describe the general form and layout ofdocuments
 HTML is not a programming language - it cannot
beused describe computations.
o An HTML document is a mix of content and controls
 Controls are tags and theirattributes
 Tags often delimit content and specify something about
howthe content should be arranged in thedocument
For example, <p>Write a paragraph here </p> is an element.
 Attributes provide additional information about the content of a
tag For example, <img src = "redhead.jpg"/><font color ="Red"/>
 Plugins
o Integrated into tools like word processors, effectively converting
themto WYSIWYG HTMLeditors
 Filters
o Convert documents in other formats toHTML
 Advantages of both filters and plug-ins:
o Existing documents produced with other tools can be converted to
HTML documents
o Use a tool you already know to produceHTML
 Disadvantages of both filters andplug-ins:
o HTML output of both is not perfect - must be finetuned
o HTML may benon-standard
o You have two versions of the document, which are difficult tosynchronize
 XML
o A meta-markup language (a language for defining markuplanguage)
o Used to create a new markup language for a particular purpose orarea
o Because the tags are designed for a specific area, they can bemeaningful
 JavaScript
o A client-side HTML-embedded scriptinglanguage
o Provides a way to access elements of HTML documents and
dynamicallychange them
 Flash
o A system for building and displaying text, graphics, sound, interactivity,and
animation(movies)
o Twoparts:
1. Authoringenvironment
2. Player
Supports both motion and shape animation
PHP
A server-side scripting language
Great for form processing and database access through the Web
Ajax
Asynchronous JavaScript + XML
 No new technologies orlanguages
Much faster for Web applications that have extensive user/server interactions
Uses asynchronous requests to the server
Requests and receives small parts of documents, resulting in much faster
responses
Java Web Software
Servlets – server-side Java classes
JavaServer Pages (JSP) – a Java-based approach to server-side scripting
JavaServer Faces – adds an event-driven interface model on JSP
ASP.NET
Does what JSP and JSF do, but in the .NET environment
Allows.NET languages to be used as server-side scripting language
Ruby
A pure object-oriented interpreted scripting language
Every data value is an object, and all operations are via method calls
Both classes and objects are dynamic
Rails
WEB PROGRAMMING

A development framework for Web-based applications


Particularly useful for Web applications that access databases
Written in Ruby and uses Ruby as its primary user language

HTML Common tags:-

HTML is the building block for web pages. HTML is a format that tells a computer how to
display a web page. The documents themselves are plain text files with special "tags" or codes
that a web browser uses to interpret and display information on your computer screen.

 HTML stands for Hyper Text MarkupLanguage


 An HTML file is a text file containing small markuptags
 The markup tags tell the Web browser how to display thepage
 An HTML file must have an htm or html fileextension.

HTML Tags:- HTML tags are used to mark-up HTML elements .HTML tags are surrounded by
the two characters < and >. The surrounding characters are called angle brackets. HTML tags
normally come in pairs like and The first tag in a pair is the start tag, the second tag is the end
tag . The text between the start and end tags is the element content . HTML tags are not case
sensitive, <B>means the same as<b>.
The most important tags in HTML are tags that define headings, paragraphs and line breaks.

Tag Description
<!DOCTYPE...> This tag defines the document type and HTML version.
<html> This tag encloses the complete HTML document and mainly comprises of
document header which is represented by <head>...</head> and
document body which is represented by <body>...</body> tags.
<head> This tag represents the document's header which can keep other HTML tags
like <title>, <link> etc.
<title> The <title> tag is used inside the <head> tag to mention the document title.
<body> This tag represents the document's body which keeps other HTML tags like
<h1>, <div>, <p> etc.
<p> This tag represents a paragraph.
<h1> to <h6> Defines header 1 to header 6

<br> Inserts a single line break

<hr> Defines a horizontal rule

<!--> Defines a comment

Headings:-
Headings are defined with the <h1> to <h6> tags. <h1> defines the largest heading while <h6>
defines the smallest.
<h1>This is a heading</h1>

Web Programming Page


WEB PROGRAMMING

<h2>This is aheading</h2>
<h3>This is aheading</h3>
<h4>This is aheading</h4>
<h5>This is aheading</h5>
<h6>This is aheading</h6>
Paragraphs:-

Paragraphs are defined with the <p> tag. Think of a paragraph as a block of text. You can use the
align attribute with a paragraph tag as well.

<p align="left">This is a paragraph</p>


<p align="center">this is another paragraph</p>

Note: You must indicate paragraphs with <p> elements. A browser ignores any
indentations or blank lines in the source text. Without <p> elements, the documentbecomes
one large paragraph. HTML automatically adds an extra blank line before and after a paragraph.

Line Breaks:-
The <br> tag is used when you want to start a new line, but don't want to start a new paragraph.
The <br> tag forces a line break wherever you place it. It is similar to single spacing in a
document.
This Code output
<p>This <br> is a para<br> graph with This
is a para
line breaks</p> graph with line breaks

Horizontal Rule The element is used for horizontal rules that act as dividers between sections
like this:

The horizontal rule does not have a closing tag. It takes attributes such as align and width
Code Output
<hr width="50%" align="center">

Sample html program


<!DOCTYPE html>
<html>
<head>
<title>This is document title
</title>
</head>
<body>
<h1>This is a heading</h1>
<p>Document contentgoeshere.......</p>
</body>
</html>

Web Programming Page


WEB PROGRAMMING

 Type the above program in notepad and save with some file nameeg:sample.html
 Open the file with browser and the webpage looks likethis

Lists:-HTML offers web authors three ways for specifying lists of


information. All lists must contain one or more list elements. Lists are of three
types
1) Un ordered list
2) Ordered List
3)Definitionlist

HTML Unordered Lists:An unordered list is a collection of related items that have no special
order or sequence. This list is created by using HTML <ul> tag. Each item in the list is marked
with a bullet.
Example

<!DOCTYPE html>
<html>
<head>
<title>HTML Unordered List</title>
</head>
<body>
<ul> <li>Beetroot</li>
<li>Ginger</li><li>Potato</li>
<li>Radish</li>
</ul>
</body>
</html>

HTML Ordered Lists:- items are numbered list instead of bulleted, This list is created by using

<!DOCTYPE html>
<html>
<head>
<title>HTML Ordered List</title>
</head>
<body>
<ol>
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ol>
</body>
</html>
Web T

<ol>tag
WEB PROGRAMMING

HTML Definition Lists:- HTML and XHTML supports a list style which is called definition
lists where entries are listed like in a dictionary or encyclopedia. The definition list is the ideal
way to present a glossary, list of terms, or other name/value list. Definition List makes use of
following three tags.
1). <dl> - Defines the start of the list
2). <dt> - A term
3). <dd> - Termdefinition
4). </dl> - Defines the end of thelist

<!DOCTYPE html>
<html>
<head>
<title>HTML Definition List</title>
</head>
<body>
<dl>
<dt><b>HTML</b></dt><dd>This stands for Hyper Text Markup Language</dd>
<dt><b>HTTP</b></dt><dd>This stands for Hyper Text Transfer Protocol</dd>
</dl>
</body>
</html>

HTML tables:
The HTML tables allow web authors to arrange data like text, images, links, other tables, etc.
into rows and columns of cells. The HTML tables are created using the <table>tag inwhich the
<tr>tag is used to create table rows and <td>tag is used to create data cells.

Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML Tables</title>
</head>
<body>
<table border="1">
<tr>
<td>Row 1, Column 1</td><td>Row 1, Column 2</td>
</tr>
<tr><td>Row 2, Column 1</td><td>Row 2, Column 2</td>
</tr>
</table>
</body>
Web Page 10
WEB PROGRAMMING

Table Heading: Table heading can be defined using <th>tag. This tag will be put to replace
<td> tag, which is used to represent actual data cell. Normally you will put your top row as table
heading as shown below, otherwise you can use <th> element in any row.
Tables Backgrounds: set table background using one of the following two ways:
1) bgcolor attribute - You can set background color for whole table or just for one cell.
2) background attribute - You can set background image for whole table or just for one cell.
You can also set border color also using bordercolorattribute.

<!DOCTYPE html>
<html>
<head>
<title>HTML Tables</title></head>
<body>
<table border="1"bordercolor="red" bgcolor="yellow">
<tr><th>Name</th>
<th>Salary</th></tr>
<td>Jayapal </td><td>50,000.00</td>
</tr>
<tr><td>Ravi</td><td>45,000.00</td>
</tr>
</table>
</body>
</html>

Images are very important to beautify as well as to depict many complex concepts in simple
way on your web page.
Insert Image:
insert any image in the web page by using <img>tag.
<img align="left|right|middle|top|bottom">
Attribute Values

Value Description

left Align the image to the left

right Align the image to the right


<img src="Image URL" ... attributes-
middle Align the image in the middle

Web Progamming Page11


WEB PROGRAMMING

top Align the image at the top

bottom Align the image at the bottom


Example

<!DOCTYPE html>
<html>
<head>
<title>Using Image in Webpage</title>
</head>
<body><p>Simple Image Insert</p>
<img src="test.png" alt="Test Image" />
</body>
</html>

HTML FORMS:
HTML Forms are required to collect some data from the site visitor. For example, during
user registration you would like to collect information such as name, email address, credit card,
etc. A form will take input from the site visitor and then will post it to a back-end application
such as CGI, ASP Script or PHP script etc. The back-end application will perform required
processing on the passed data based on defined business logic inside the application. There are
various form elements available like text fields, text area fields, drop-down menus, radio buttons,
checkboxes, etc.

<form action="Script URL" method="GET|POST"> form elements like input, text area etc. </form>

Web Technologies Page 12


WEB PROGRAMMING

<HimTMgsLrcF=o"rImmCaognetrUoRls L:"...
attributes-list/>
There are different types of form controls that you can use to collect data using HTML form:
 Text InputControls
 Checkboxes Controls
 Radio BoxControls
 Select BoxControls
 File Selectboxes
 Hidden Controls
 ClickableButtons
 Submit and ResetButton
Text Input Controls:-
There are three types of text input used on forms:
1) Single-line text input controls - This control is used for items that require only one
line of user input, such as search boxes or names. They are created
usingHTML
<input>tag.

<input type="text">defines a one-line input field for text input:

Example:

<form>
Firstname:<br>
<input type="text"name="firstname"><br>
Lastname:<br>
<input type="text" name="lastname">
</form>

2) Password input controls - This is also a single-line text input but it masks the character
as soon as a user enters it. They are also created using HTML <input>tag.
Input Type Password

<input type="password">defines a password field:

<form>
User name:<br>
<input type="text"
name="username"><br>
User password:<br>
<input type="password"
name="psw">

Web Programming Page 13


WEB PROGRAMMING

3) Multi-line text input controls - This is used when the user is required to give details that may
belongerthanasinglesentence.Multi-lineinputcontrolsarecreatedusing HTML
<textarea> tag.

<!DOCTYPE html>
<html>
<head>
<title>Multiple-Line Input Control</title>
</head>
<body>
<form> Description: <br />
<textarea rows="5" cols="50" name="description"> Enter description here... </textarea>
</form>
</body>
</html>

Checkboxes Controls:-
Checkboxes are used when more than one option is required to be selected. They are also
created using HTML <input> tag but type attribute is set to checkbox.
Here is an example HTML code for a form with two checkboxes:

<!DOCTYPE html>
<html><head><title>Checkbox Control</title></head>
<body>
<form>
<input type="checkbox" name="C++" value="on"> C++
<br>
<input type="checkbox" name="C#" value="on"> C#
<br>
<input type="checkbox" name="JAVA" value="on"> JAVA
</form>
</body></
html>
Radio Button Control:-
Radio buttons are used when out of many options, just one option is required to be selected.
They are also created using HTML <input> tag but type attribute is set toradio.

<!DOCTYPE html>
<html><head><title>Radio Box Control</title></head>
<body><p>Select a Course</p>
<form>
<input type="radio" name="subject" value="C++"> C++
<br>
<input type="radio" name="subject" value="JAVA"> JAVA
<br>
<input type="radio" name="subject" value="HTML"> HTML
</form> </body></html>

Web Programming Page 14


WEB PROGRAMMING

Select Box Controls :- A select box, also called drop down box which provides option to list
down various options in the form of drop down list, from where a user can select one or more
options.

<!DOCTYPE html>
<html>
<head>
<title>Select Box Control</title>
</head>
<body>
<form>
<select name="dropdown">
<option value="C++" selected>C++</option>
<option value="JAVA">JAVA</option>
<option value="HTML">HTML</option>
</select>
</form>
</body>
</html>
File Select boxes:- If you want to allow a user to upload a file to your web site, you will need to
use a file upload box, also known as a file select box. This is also created using the <input>
element but type attribute is set to file.

<!DOCTYPE html>
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<p>File Upload Box</p>
<form>
<input type="file" name="fileupload" accept="image/*" />
</form>
</body>
</html>

Hidden Controls:- Hidden form controls are used to hide data inside the page which later on can
be pushed to the server. This control hides inside the code and does not appear on the actual
page. For example, following hidden form is being used to keep current page number. When a
user will click next page then the value of hidden control will be sent to the web server and there
it will decide which page will be displayed next based on the passed currentpage.

<html><head> <title>File Upload Box</title> </head>


<body>
<form>
<p>This is page 10</p>
<input type="hidden" name="pagename" value="10" />
<input type="submit" name="submit" value="Submit" />
<input type="reset" name="reset" value="Reset" />
</form> </body> </html>

Web Programming Page 15


WEB PROGRAMMING

Button Controls:-
There are various ways in HTML to create clickable buttons. You can also create a clickable
button using <input> tag by setting its type attribute to button. The type attribute can take the
following values:

<!DOCTYPE html>
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<form>
<input type="submit" name="submit" value="Submit" />
<input type="reset" name="reset" value="Reset" />
<input type="button" name="ok" value="OK" />
<input type="image" name="imagebutton" src="test1.png" />
</form>
</body></html>

HTML frames: These are used to divide your browser window into multiple sections where
each section can load a separate HTML document. A collection of frames in the browser window
is known as a frameset. The window is divided into frames in a similar way the tables
areorganized: into rows andcolumns.
To use frames on a page we use <frameset> tag instead of <body> tag. The <frameset>
tag defines, how to divide the window into frames. The rows attribute of <frameset> tag defines

Web Programming Page 16


WEB PROGRAMMING

horizontal frames and cols attribute defines vertical frames. Each frame is indicated by <frame>
tag and it defines which HTML document shall open into the frame.

Note: HTML <frame>Tag. Not Supported in HTML5.

<frameset
cols="25%,50%,25%">
<framesrc="frame_a.ht
m">
<framesrc="frame_b.ht
m">

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<iframe src="sample1.html" height="400"
width="400"frameborder="1">
<h1>This is aHeading</h1>
<p>This is aparagraph.</p>
</iframe>
</body>

CSS stands for Cascading Style Sheets


CSS describes how HTML elements are to be displayed on screen, paper, or in other
media. CSS saves a lot of work. It can control the layout of multiple web pages all at once.
CSS can be added to HTML elements in 3 ways:
 Inline - by using the style attribute in HTMLelements
 Internal - by using a <style> element in the <head>section
 External - by using an external CSSfile
Inline CSS
An inline CSS is used to apply a unique style to a single HTML element.
An inline CSS uses the style attribute of an HTML element.
This example sets the text color of the <h1> element to blue:

<h1 style="color:blue;">This is a Blue


Heading</h1>

<ht <hea <title>Pa


ml d ge
> <h1 style="color:blue;">This is
a Blue Heading</h1>
</body>
</html> Page 17
WEB PROGRAMMING

Internal CSS: An internal CSS is used to define a style for a single HTML page. An internal
CSS is defined in the <head> section of an HTML page, within a <style> element:
An external style sheet is used to define the style for many HTML pages. With an external style
<html>
sheet, you can change the look of an entire web site, by changing one file! To use an external
style sheet, add<head>
a link to it in the <head> section of the HTML page:
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color:red;}
</style>
</head>
<body>
<h1>This is aheading</h1>
<p>This is aparagraph.</p>
</body>
</html>
External
An CSS:-
external style sheet can be written in any text editor. The file must not contain any HTML
code, and must be saved with a .css extension.
Here is how the "styles.css" looks:

<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is aheading</h1>
<p>This is aparagraph.</p>
</body>
</html>

body { background-color: powderblue; }

h1 { color:blue; }

p { color:red; }

Web Programming Page18


WEB PROGRAMMING

CSS Fonts: The CSS color property defines the text color to be used.
The CSS font-family property defines the font to be used.
The CSS font-size property defines the text size to be used.

<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 300%;
}
p{
color: red;
font-family: courier;
font-size: 160%;
}
</style>
</head>
<body>
<h1>This is aheading</h1>
<p>This is aparagraph.</p>
</body>
</html>

CSS Border: The CSS border property defines a border around an HTML element.
CSS Padding: The CSS padding property defines a padding (space) between the text and the
border.
CSS Margin: The CSS margin property defines a margin (space) outside the border.

<html><head>
<style>h
1{
color: blue;
font-family: verdana;
font-size: 300%; }
p{
color: red; font-size: 160%; border: 2px solid powderblue; padding: 30px; margin: 50px; }
</style>
</head>
<body>
<h1>This is aheading</h1>
<p>This is aparagraph.</p>
</body>
</html>

Web Programming Page 19


WEB PROGRAMMING

JavaScript:
What is JavaScript?
Java Script is one popular scripting language over internet. Scripting means a small sneak
(piece). It is always independent on otherlanguages.
JavaScript is most commonly used as a client side scripting language. This means that JavaScript
code is written into an HTML page. When a user requests an HTML page with JavaScript in it,
the script is sent to the browser and it's up to the browser to do something with it.
Difference between JavaScript and Java
JavaScript Java
Cannot live outside a Web page Can build stand-alone applications or live in a
Web page as an applet.
Doesn‘t need a compiler Requires a compiler
Knows all about your page Applets are dimly aware of your Web page.
Untyped Strongly typed
Somewhat object-oriented Object-oriented
There are no relationship between in java & java script. Java Script is a scripting language that
always dependent in HTML language. It used to css commands. It is mainly used to creating
DHTML pages & validating the data. This is called client side validations.
Why we Use JavaScript?
Using HTML we can only design a web page but you can not run any logic on web browser
like addition of two numbers, check any condition, looping statements (for, while), decision
making statement (if-else) at client side. All these are not possible using HTML So for perform
all these task at client side you need to useJavaScript.
Features of JavaScript

JavaScript is a client side technology, it is mainly used for gives client side validation, but
it have lot of features which are given below;

Web Programming Page 20


WEB PROGRAMMING

Java script is object based oriented language.

Inheritance is does not support in JavaScript, so it is called object based oriented


language.
 JavaScript was developed by Netscape (company name) & initially called live script.
Later Microsoft developed & adds some features live script then it is called “Jscript”.
Jscript is nothing but Java script. We cannot create own classes in java script.
Java script is designed to add interactivity to HTML pages. It is usually embedded
directly into html pages.
 Java script is mainly useful to improve designs of WebPages, validate form data at client
side, detects (find) visitor‘s browsers, create and use to cookies, and much more.
 Java script is also called light weight programming language, because Java script is
return with very simple syntax. Java script is containing executable code.
 Java script is also called interpreted language, because script code can be executed
without preliminary compilation.
 It Handling dates, time, onSubmit, onLoad, onClick, onMouseOver & etc.

 JavaScript is case sensitive.

 Most of the javascript control statements syntax is same as syntax of controlstatements


in C language.
 An important part of JavaScript is the ability to create new functions within scripts.

Declare a function in JavaScript using function keyword.

Creating a java script: - html script tag is used to script code inside the html page.

<script> </script>

The script is containing 2 attributes. They are

1) Language attribute:-

It represents name of scripting language such as JavaScript, VbScript.

<script language=―JavaScript‖>

Web Programming Page 21


WEB PROGRAMMING

2) Type attribute: - It indicates MIME (multi purpose internet mail extension) type of
scripting code. It sets to an alpha-numeric MIME type of code.

<script type=―text / JavaScript‖>

Location of script or placing the script: - Script code can be placed in both head & body
section of html page.

Script inhead section Script in body section

<html> <html>
<head> <head>
<script type=―text/JavaScript‖>
</head>Scr
iptcodehere <body>
</script> <script type= ―text /JavaScript‖>
</head> Script codehere
<body> </script>
</body> </body>
</html> </html>
Scripting in both head & body section: - we can create unlimited number of scripts inside the
same page. So we can locate multiple scripts in both head & body section of page.
Ex: - <html>
<head>
<script type=―text / JavaScript‖>
Script code here
</script>
</head>
<body>
<script type=―text /
JavaScript‖> Script code
here
</script>
</body>
</html>
Program: -
<html>
<head>
<script language="JavaScript">
document.write("hai my name is Mamatha")
</script>
</head>
<body text="red">
Web Programming Page 22
WEB PROGRAMMING

<marquee>
<script language="JavaScript">
document.write("hai my name is Srikanth")
</script></marquee>
</body>
</html>
O/P: - hai my name is Mamatha

hai my name is Srikanth

document. write is the proper name of object.

 There are 2 ways of executing script code


1) directexecute
2) to execute script codedynamically
Reacts to events: - JavaScript can be set to execute when something happens. When the page is
finished loading in browser window (or) when the user clicks on html element dynamically.

Ex: -
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional // EN">
<HTML>
<HEAD>
<script language="JavaScript">
function myf( )
{
document.write("Hai Kalpana")
}
</script>
</HEAD>
<BODY>
to execute script code:
<input type="button" value="click me" onclick="myf( )">
To execute script code:
<input type="button" value="touch me" onmouseover="myf( )">
</BODY>
</HTML>
O/P: - to executescriptcode: To execute scriptcode:

Creating external script: - some times you might want to run same script on several pages
without having to write the script on each page. To simplify this, write external script & save .js
extension. To use external script specify .js file in src attribute of script tag.

Note: - external script can not contain script

tag. save: - external.js


document.write("this is external script code 1 "+"<br>");

Web Programming Page 23


WEB PROGRAMMING

document.write("this is external script code 2 "+"<br>");


document.write("this is external script code 3 "+"<br>");
document.write("this is external script code 4 ");

<HTML><BODY>
<script language="JavaScript">
document.write("this is document code 1 "+"<br>");
document.write("this is document code 2 "+"<br>");
</script>
<script src="external.js">
</script>
</BODY>
</HTML>
JavaScript syntax rules: - JavaScript is case sensitive language. In this upper case lower
case letters are differentiated (not same).

Ex:- a=20;
A=20;
Those the variable name „a‟ is different from the variable named „A‟.
Ex: - myf( ) // correct
myF( ) // incorrect
; is optional in general JavaScript.
Ex:- a=20 //valid
b=30 //valid
A=10; b=40; // valid
However it is required when you put multiple statements in the same line.
 JavaScript ignore white space. In java script white space, tag space & empty lines are not
preserved.
 To display special symbols we use \.
Comment lines: - comments lines are not executable.

// single line comment


/* this is multi line comment */

Declaring variable: - variable is a memory location where data can be stored. In java script
variables with any type of data are declared by using the keyword ‗var‘. All keywords are small
letters only.

vara; a=20;
varstr; str= “Sunil”;
varc; c=‟a‟;
vard; d=30.7;
But the keyword is not mandatory when declare of the variable.
c;  not valid. In this solution var keyword must be declared.

Web Programming Page 24


WEB PROGRAMMING

During the script, we can change value of variable as well as type of value of variable.
Ex: -
a=20;
a=30.7;
JavaScript functions: - in java script functions are created with the keyword ‗function‘ as
shownbelow

Syntax: - function funname( )


{
--------
}
Generally we can place script containing function head section of web page. There are 2 ways to
call the function.
1) direct callfunction
2) Events handlers to call the functiondynamically.
1 We can pass data to function as argument but that data will be available inside the
function.

Ex: -

<HTML> </HEAD>
<HEAD> <BODY>
<TITLE> Function direct call</TITLE> <script>
<script language="JavaScript"> var r=add(30,60)
function add(x,y) document.write("addition is :"+r);
{ </script>
z=x+y </BODY>
return z </HTML>
}
</script> O/P: - addition is :90
2 to add dynamical effects, java script provide a list of events that call function
dynamically. Hare each event is one attribute that always specified in html tags.
attrname=”attrval”
eventName=”funname( )”
Ex: -
<HTML> z=x+y
<HEAD> document.write("addition is :"+z);
<TITLE> Function dynamically</TITLE> }
<script language="JavaScript"> </script>
function add( ) </HEAD>
{ x= <BODY> to call function:
20 <input type="button" value="click hare"
y=30 onclick="add( )">

Web Programming Page 25


WEB PROGRAMMING

</script>
</BODY> O/P: - to call function:
addition is :90
</HTML>

EVENTHANDLERS: Events are not casesensitive.


Java script events: -
Attribute The event occurs when…
onclick mouse click an object
ondblclick mouse double clicks
onmouseover a mouse cursor on touch here
onmousedown a mouse button
ispressed
onmousemove the mouse is moved
onmouseout the mouse is moved out
anelement onmouseup a mouse button isreleased
onkeydown a keyboard key ispressed
onkeypress a keyboard key is pressed or held
down onkeyup a keyboard key isreleased
onfocus an elements getfocus
onblur an element losesfocus
onchange the content of a fieldchange
onselect text isselected
onload a page or an image is finishedloading
onunload the user exist thepage
onerror an error occurs when loading a document or
animage onabort loading an image isinterrupted
onresize a window or frame is resized
onreset the reset button is
pressed onsubmit the submit button isclicked
Ex: -
<HTML> </b>
<HEAD> <br>
<TITLE> Mouse Events </TITLE> <b onmouseover="add( )">
<script language="JavaScript"> to call function touch here :
function add() </b>
{ a= <br>
55 <b ondblclick="add( )">
b=45 to call function double click here :
c=a+b </b>
document.write("addition is :"+c) <br>
} <b onmousemove="add( )">
</script> to call function cursor move here :
</HEAD> </b>
<BODY> <br>
<b onclick="add( )"> <b onmouseup="add( )">
to call function click here : to call function cursor up here :
</b>
Web Programming Page 26
WEB PROGRAMMING

<br> to call function click here :


<b onmouseout="add( )"> to call function touch here :
to call function cursor out here : to call function double click here :
</b> addition is :100
</BODY> to call function cursor move here :
</HTML> to call function cursor up here :
to call function cursor out here :
O/P: -
Program: -
<HTML>
<HEAD>
<TITLE> display student name </TITLE>
<script language="JavaScript">
function disp( )
{
// access from data
var name=window.document.student.sname.value
// (or) var name=window.document.getElementById("snameid").value
//checking name if(name=""||!isNaN(name)||!
isNaN(name.charAt(0)))
window.alert("sname you entered isinvalid")
else
document.write("sname you have entered is : "+name);
}
</script>
</HEAD>
<BODY>
<form name="student">
Enter Student name:
<input type="text" name="sname"id="snameid" value="enter" onblur="disp( )">
</form>
</BODY>
</HTML>

O/P: -
1
Enter Studentname:

1
Enter Studentname:
sname you have entered is : true

Popup boxes: - popup (arises) box is a small window that always shown before opening the
page. The purpose of popup box is to write message, accept some thing from user. Java script
provides 3 types of popup boxes. They are 1) alert 2) Confirm. 3) Prompt.

1) alert popup box :-

Web Programming Page 27


WEB PROGRAMMING

Alert box is a very frequently useful to send or write cautionary messages to end use alert
box is created by alert method of window object as shownbelow.
Syntax: - window – alert (“message”);
When alert popup, the user has to click ok before continue browsing.
Ex: -
<html> window.alert("This is for addition of 2
<head> no's")
<title> alert box </title> document.write("Result is: "+c)
<script language="JavaScript"> }
function add( ) </script>
{ a= </head>
20 <body onload="add( )">
b=40 </body>
c=a+b </html>

O/P: -

Result is: 60
2) confirm popupbox:-
This is useful to verify or accept some thing from user. It is created by confirm method of
window object as shown below.
Syntax:- window.confirm(“message?”);
When the confirm box pop‘s up, user must click either ok or cancel buttons to proceed. If user
clicks ok button it returns the boolean valve true. If user clicks cancel button, it returns the
boolean value false.
Ex: - document.write("result is :"+c)
<HTML> }
<HEAD> else
<TITLE> Confirm </TITLE> {
<script> document.write("you clicked cancel button")
function sub( ) }
{ }
a=50 </script>
b=45 </HEAD>
c=a-b <BODY onload="sub( )">
x=window.confirm("Do you want to see to see the o/p in pop up box:
subtraction of numbers") </BODY>
if(x==true) </HTML>
{

O/P: -

WebProgramming Page28
WEB PROGRAMMING

to see the o/p in pop up box:

result is :5

3) Prompt popup box:- It is useful to accept data from keyboard at runtime. Prompt box is
created by prompt method of windowobject.
window.prompt (“message”, “default text”);
When prompt dialog box arises user will have to click either ok button or cancel button after
entering input data to proceed. If user click ok button it will return input value. If user click
cancel button the value ―null‖ will be returned.
Ex: -
<HTML> {
<HEAD> a=a*i
<TITLE> Prompt </TITLE> }
<script> window.alert("factorial value :"+a)
function fact( ) }
{ </script>
var b=window.prompt("enter +ve integer </HEAD>
:","enter here") <BODY onload="fact( )">
var </BODY>
c=parseInt(b) </HTML>
a=1
for(i=c;i>=1;i--) even if JavaScript is turned off in the
browser and it can‘t be easily bypassed by
O/P: - malicious users. On the other hand, users
FORM VALIDATION: will have to fill in the information without
When we create forms, providing form getting a response until they submit the
validation is useful to ensure that your form. This results in a slow response from
customers enter valid and complete data. For theserver.
example, you may want to ensure that
The exception is validation using Ajax. Ajax
someone inserts a valid e-mail address into a
calls to the server can validate as you type
text box, or perhaps you want to ensure that
and provide immediate feedback. Validation
someone fills in certain fields.
in this context refers to validating rules such
We can provide custom validation for your as username availability.
forms in two ways: server-side validation
and client-side validation. Server side validation is performed by a
web server, after input has been sent to the
SERVER-SIDE VALIDATION server.
In the server-side validation, information is
CLIENT-SIDE VALIDATION
being sent to the server and validated using
one of server-side languages. If the Server-side validation is enough to have a
validation fails, the response is then sent successful and secure form validation. For
back to the client, page that contains the web better user experience, however, you might
form is refreshed and a feedback is shown. consider using client-side validation.This
This method is secure because it will work
Web Programming Page
WEB PROGRAMMING

type of validation is done on the client using if( n == "" || (!isNaN(parseInt(n))) || n.length
script languages such as JavaScript. By < 3 || n.length >= 8)
using script languages user‘s input can be {
validated as they type. This means a more alert( "Please enter valid name and
responsive, visually richvalidation. minimum length 3 characters and maximum
ith client-side validation, form never gets length 8 characters !" );
submitted if validation fails. Validation is document.myForm.Name.focus();
being handled in JavaScript methods that return false;
you create (or within frameworks/plugins) }
and users get immediate feedback if
validationfails. var emailID =
document.myForm.EMail.value;
Main drawback of client-side validation is if( emailID == "" )
that it relies on JavaScript. Ifusers turn {
JavaScript off, they can easily bypass the alert( "Please provide your Email!" );
validation. This is why validation should document.myForm.EMail.focus() ;
always be implemented on both the client return false;
and server. By combining server-side and }
client-side methods we can get the best of
the two: fast response, more secure atpos = emailID.indexOf("@");
validation and better userexperience. dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
Client side validation is performed by a {
web browser, before input is sent to a web alert("Please enter correct email ID")
server.
document.myForm.EMail.focus() ;
return false;
Validation can be defined by many different }
methods, and deployed in many different
ways. var z = document.myForm.Zip.value;
if(z == "" ||isNaN(z) || z.length != 6 )
Simple Example: {
<html>
alert( "Please provide a zip in the format
<head>
#####." );
<title>FormValidation</title>
document.myForm.Zip.focus() ;
<scripttype="text/javascript">
return false;
<!-- }
// Form validation code will come here.
function validate() var c = document.myForm.Country.value;
{
if( c == "-1" )
var n = document.myForm.Name.value; {
alert( "Please provide your country!" );

Web Programming Page


WEB PROGRAMMING

return false; </td>


} </tr>
return( true ); <tr>
} <td align="right"></td>
<td><input type="submit" value="Submit"
//--> /></td>
</script> </tr>
</head> </font></table></form></body>
<bodybgcolor="bisque"> </html>
<h1><p align="center"><b>Application Output:
Form Validation Using
JavaScript</b></p></h1>
<form action="reg.html"name="myForm"
onsubmit="return(validate());">
<table cellspacing="5" cellpadding="5"
align="center" border="5" width="438">
<tr>
<td align="right"><b>Name</b></td>
<td><input type="text" name="Name"
size="50" /></td>
</tr>
<tr>
<td align="right"><b>EMail</b></td>
<td><input type="text" name="EMail"
size="50" /></td>
</tr>
<tr>
<td align="right"><b>Zip Code</b></td>
<td><input type="text" name="Zip"
size="50" /></td>
</tr>
<tr>
<td align="right" ><b>Country</b></td>
<td>
<select name="Country">
<option value="-1" selected>[choose
yours]</option>
<option value="1">INDIA</option>
<option value="2">UK</option>
<option value="3">USA</option>
</select>

Web Programming Page


WEB PROGRAMMING

JavaScript is an Object Oriented Programming (OOP) language. A programming language can be called
object-oriented if it provides four basic capabilities to developers −
 Encapsulation − the capability to store related information, whether data or methods, together in an object.
 Aggregation − the capability to store one object inside another object.
 Inheritance − the capability of a class to rely upon another class (or number of classes) for some of its
properties and methods.
 Polymorphism − the capability to write one function or method that works in a variety of different ways.
Objects are composed of attributes. If an attribute contains a function, it is considered to be a method of the
object, otherwise the attribute is considered a property.

Object Properties
Object properties can be any of the three primitive data types, or any of the abstract data types, such as
another object. Object properties are usually variables that are used internally in the object's methods, but
can also be globally visible variables that are used throughout the page.
The syntax for adding a property to an object is −
objectName.objectProperty = propertyValue;
For example − The following code gets the document title using the "title" property of the document object.
var str = document.title;
Object Methods
Methods are the functions that let the object do something or let something be done to it. There is a small
difference between a function and a method – at a function is a standalone unit of statements and a method
is attached to an object and can be referenced by the this keyword.
Methods are useful for everything from displaying the contents of the object to the screen to performing
complex mathematical operations on a group of local properties and parameters.
For example − Following is a simple example to show how to use the write() method of document object to
write any content on the document.
document.write("This is test");
Web Programming Page
WEB PROGRAMMING

User-Defined Objects
All user-defined objects and built-in objects are descendants of an object called Object.

The new Operator


The new operator is used to create an instance of an object. To create an object, the new operator is followed
by the constructor method.
In the following example, the constructor methods are Object(), Array(), and Date(). These constructors are
built-in JavaScript functions.
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");
The Object() Constructor
A constructor is a function that creates and initializes an object. JavaScript provides a special
constructor function called Object() to build the object. The return value of the Object() constructor is
assigned to a variable.
The variable contains a reference to the new object. The properties assigned to the object are not
variables and are not defined with the var keyword.

Example 1
Try the following example; it demonstrates how to create an Object.

Live
<html> Demo
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";
</script>
</head>

<body>
<script type = "text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
Output
Book name is : Perl
Book author is : Mohtashim
Example 2
This example demonstrates how to create an object with a User-Defined Function. Here this keyword is used
to refer to the object that has been passed to a function.

Live
<html> Demo
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
function book(title, author) {
this.title = title;
Web Programming Page
WEB PROGRAMMING
this.author = author;

Web Programming Page


WEB PROGRAMMING

}
</script>
</head>

<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>
Output
Book title is : Perl
Book author is : Mohtashim
Defining Methods for an Object
The previous examples demonstrate how the constructor creates the object and assigns properties. But we
need to complete the definition of an object by assigning methods to it.

Example
Try the following example; it shows how to add a function along with an object.

Live
<html> Demo

<head>
<title>User-defined objects</title>
<script type = "text/javascript">
// Define a function which will work as a method
function addPrice(amount) {
this.price = amount;
}

function book(title, author)


{ this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>

<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);

document.write("Book title is : " + myBook.title + "<br>");


document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
Output
Book title is : Perl
Book author is : Mohtashim
Book price is : 100
The 'with' Keyword
Web Programming Page
WEB PROGRAMMING

The ‘with’ keyword is used as a kind of shorthand for referencing an object's properties or methods.
The object specified as an argument to with becomes the default object for the duration of the block that
follows. The properties and methods for the object can be used without naming the object.

Syntax
The syntax for with object is as follows −
with (object) {
properties used without the object name and dot
}
Example
Try the following example.

Live
<html> Demo
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
// Define a function which will work as a method
function addPrice(amount) {
with(this) {
price = amount;
}
}
function book(title, author)
{ this.title = title;
this.author = author;
this.price = 0;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>

<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);

document.write("Book title is : " + myBook.title + "<br>");


document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
Output
Book title is : Perl
Book author is : Mohtashim
Book price is : 100
JavaScript Native Objects
JavaScript has several built-in or native objects. These objects are accessible anywhere in your program and
will work the same way in any browser running in any operating system.
Here is the list of all important JavaScript Native Objects −
 JavaScript Number Object
 JavaScript Boolean Object
Web Programming Page
WEB PROGRAMMING

 JavaScript String Object


 JavaScript Array Object
 JavaScript Date Object
 JavaScript Math Object
 JavaScript RegExp Object

JavaScript - The Number Object


The Number object represents numerical date, either integers or floating-point numbers. In
general, you do not need to worry about Number objects because the browser
automatically converts number literals to instances of the number class.

Syntax
The syntax for creating a number object is as follows −
var val = new Number(number);
In the place of number, if you provide any non-number argument, then the argument
cannot be converted into a number, it returns NaN (Not-a-Number).

Number Properties
Here is a list of each property and their description.
Sr.No. Property & Description

1 MAX_VALUE

The largest possible value a number in JavaScript can


have 1.7976931348623157E+308

2 MIN_VALUE
The smallest possible value a number in JavaScript can have 5E-324

3 NaN
Equal to a value that is not a number.

4 NEGATIVE_INFINITY
A value that is less than MIN_VALUE.

5 POSITIVE_INFINITY
A value that is greater than MAX_VALUE
Web Programming Page
WEB PROGRAMMING

6 prototype
A static property of the Number object. Use the prototype property to
assign new properties and methods to the Number object in the current
document
7 constructor
Returns the function that created this object's instance. By default
this is the Number object.

In the following sections, we will take a few examples to demonstrate the properties of
Number.

Number Methods
The Number object contains only the default methods that are a part of every object's
definition.
Sr.No. Method & Description

1 toExponential()

Forces a number to display in exponential notation, even if the number is


in the range in which JavaScript normally uses standard notation.

2 toFixed()
Formats a number with a specific number of digits to the right of the
decimal.
3 toLocaleString()
Returns a string value version of the current number in a format that
may vary according to a browser's local settings.

4 toPrecision()
Defines how many total digits (including digits to the left and right of
the decimal) to display of a number.

5 toString()
Returns the string representation of the number's value.

6 valueOf()
Returns the number's value.
WEB PROGRAMMING

Web Programming Page


WEB PROGRAMMING

JavaScript - The Boolean Object


Advertisements

Previous Page
Next Page
The Boolean object represents two values, either "true" or "false". If value parameter is
omitted or is 0,
-0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of
false.

Syntax
Use the following syntax to create a boolean object.
var val = new Boolean(value);
Boolean Properties
Here is a list of the properties of Boolean object −
Sr.No. Property & Description

1 constructor

Returns a reference to the Boolean function that created the object.

2 prototype
The prototype property allows you to add properties and methods to an
object.
In the following sections, we will have a few examples to illustrate the properties of Boolean
object.

Boolean Methods
Here is a list of the methods of Boolean object and their description.
Sr.No. Method & Description

1 toSource()

Returns a string containing the source of the Boolean object; you can
use this string to create an equivalent object.

2 toString()
WEB PROGRAMMING
Web Programming Page
WEB PROGRAMMING

Returns a string of either "true" or "false" depending upon the value of


the object.
3 valueOf()
Returns the primitive value of the Boolean object

JavaScript - The Strings Object


Advertisements

Previous Page
Next Page
The String object lets you work with a series of characters; it wraps Javascript's string
primitive data type with a number of helper methods.
As JavaScript automatically converts between string primitives and String objects, you can
call any of the helper methods of the String object on a string primitive.

Syntax
Use the following syntax to create a String object −
var val = new String(string);
The String parameter is a series of characters that has been properly encoded.

String Properties
Here is a list of the properties of String object and their description.
Sr.No. Property & Description

1 constructor

Returns a reference to the String function that created the object.

2 length
Returns the length of the string.

Web Programming Page


WEB PROGRAMMING

3 prototype
The prototype property allows you to add properties and methods to an
object.
In the following sections, we will have a few examples to demonstrate the usage of String
properties.

String Methods
Here is a list of the methods available in String object along with their description.
Sr.No. Method & Description

1 charAt()

Returns the character at the specified index.

2 charCodeAt()
Returns a number indicating the Unicode value of the character at
the given index.

3 concat()
Combines the text of two strings and returns a new string.

4 indexOf()
Returns the index within the calling String object of the first
occurrence of the specified value, or -1 if not found.

5 lastIndexOf()
Returns the index within the calling String object of the last
occurrence of the specified value, or -1 if not found.

6 localeCompare()
Returns a number indicating whether a reference string comes before
or after or is the same as the given string in sort order.

7 match()
Used to match a regular expression against a string.

8 replace()
Used to find a match between a regular expression and a string, and to
replace
Web Programming Page
WEB PROGRAMMING

the matched substring with a new substring.

9 search()
Executes the search for a match between a regular expression and a
specified string.

10 slice()
Extracts a section of a string and returns a new string.

11 split()
Splits a String object into an array of strings by separating the
string into substrings.

12 substr()
Returns the characters in a string beginning at the specified location
through the specified number of characters.

13 substring()
Returns the characters in a string between two indexes into the string.

14 toLocaleLowerCase()
The characters within a string are converted to lower case while
respecting the current locale.

15 toLocaleUpperCase()
The characters within a string are converted to upper case while
respecting the current locale.

16 toLowerCase()
Returns the calling string value converted to lower case.

17 toString()
Returns a string representing the specified object.

18 toUpperCase()
Returns the calling string value converted to uppercase.

19 valueOf()
Web Programming Page
WEB PROGRAMMING

Returns the primitive value of the specified object.

String HTML Wrappers


Here is a list of the methods that return a copy of the string wrapped inside an appropriate
HTML tag.
Sr.No. Method & Description

1 anchor()

Creates an HTML anchor that is used as a hypertext target.

2 big()
Creates a string to be displayed in a big font as if it were in a <big> tag.

3 blink()
Creates a string to blink as if it were in a <blink> tag.

4 bold()
Creates a string to be displayed as bold as if it were in a <b> tag.

5 fixed()
Causes a string to be displayed in fixed-pitch font as if it were in a <tt>
tag
6 fontcolor()
Causes a string to be displayed in the specified color as if it were in
a <font color="color"> tag.

7 fontsize()
Causes a string to be displayed in the specified font size as if it were
in a <font size="size"> tag.

8 italics()
Causes a string to be italic, as if it were in an <i> tag.

9 link()
Creates an HTML hypertext link that requests another URL.

Web Programming Page


WEB PROGRAMMING

10 small()
Causes a string to be displayed in a small font, as if it were in a <small>
tag.
11 strike()
Causes a string to be displayed as struck-out text, as if it were in a
<strike> tag.
12 sub()
Causes a string to be displayed as a subscript, as if it were in a <sub>
tag
13 sup()
Causes a string to be displayed as a superscript, as if it were in a <sup>
tag

JavaScript - The Arrays Object


Advertisements

Previous
Page Next
Page
The Array object lets you store multiple values in a single variable. It stores a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of
data, but it is often more useful to think of an array as a collection of variables of the same
type.

Syntax
Use the following syntax to create an Array object −
var fruits = new Array( "apple", "orange", "mango" );
The Array parameter is a list of strings or integers. When you specify a single numeric
parameter with the Array constructor, you specify the initial length of the array. The
maximum length allowed for an array is 4,294,967,295.
You can create array by simply assigning values as follows −
var fruits = [ "apple", "orange", "mango" ];
You will use ordinal numbers to access and to set values inside an array as follows.
fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element
Array Properties
WEB PROGRAMMING
Web Programming Page
WEB PROGRAMMING

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.
In the following sections, we will have a few examples to illustrate the usage of Array
properties.

Array Methods
Here is a list of the methods of the Array object along with their description.
Sr.No. Method & Description

1 concat()

Returns a new array comprised of this array joined with other


array(s) and/or value(s).

2 every()
Returns true if every element in this array satisfies the provided testing
function.
3 filter()
Creates a new array with all of the elements of this array for which the
provided filtering function returns true.
Web Programming Page
WEB PROGRAMMING

4 forEach()
Calls a function for each element in the array.

5 indexOf()
Returns the first (least) index of an element within the array equal to the
specified value, or -1 if none is found.

6 join()
Joins all elements of an array into a string.

7 lastIndexOf()
Returns the last (greatest) index of an element within the array equal
to the specified value, or -1 if none is found.

8 map()
Creates a new array with the results of calling a provided function on
every element in this array.

9 pop()
Removes the last element from an array and returns that element.

10 push()
Adds one or more elements to the end of an array and returns the new
length of the array.

11 reduce()
Apply a function simultaneously against two values of the array (from
left-to-right) as to reduce it to a single value.

12 reduceRight()
Apply a function simultaneously against two values of the array (from
right-to-left) as to reduce it to a single value.

13 reverse()
Reverses the order of the elements of an array -- the first becomes the
last, and the last becomes the first.

14 shift()

Web Programming Page


WEB PROGRAMMING

Removes the first element from an array and returns that element.

15 slice()
Extracts a section of an array and returns a new array.

16 some()
Returns true if at least one element in this array satisfies the
provided testing function.

17 toSource()
Represents the source code of an object

18 sort()
Sorts the elements of an array

19 splice()
Adds and/or removes elements from an array.

20 toString()
Returns a string representing the array and its elements.

21 unshift()
Adds one or more elements to the front of an array and returns the new
length of the array.

JavaScript - The Date Object


Advertisements

Previous Page
Next Page
The Date object is a datatype built into the JavaScript language. Date objects are created
with the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most
methods simply allow you to get and set the year, month, day, hour, minute, second, and
millisecond fields of the object, using either local time or UTC (universal, or GMT) time.

Web Programming Page


WEB PROGRAMMING

The ECMAScript standard requires the Date object to be able to represent any date and
time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a
range of plus or minus 273,785 years, so JavaScript can represent date and time till the
year 275755.

Syntax
You can use any of the following syntaxes to create a Date object using Date() constructor.
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
Note − Parameters in the brackets are always
optional. Here is a description of the parameters −
 No Argument − With no arguments, the Date() constructor creates a Date object set
to the current date and time.
 milliseconds − When one numeric argument is passed, it is taken as the internal
numeric representation of the date in milliseconds, as returned by the getTime()
method. For example, passing the argument 5000 creates a date that represents
five seconds past midnight on 1/1/70.
 datestring − When one string argument is passed, it is a string representation of a
date, in the format accepted by the Date.parse() method.
 7 agruments − To use the last form of the constructor shown above. Here is a
description of each argument −
o year − Integer value representing the year. For compatibility (in order to avoid
the Y2K problem), you should always specify the year in full; use 1998, rather
than 98.
o month − Integer value representing the month, beginning with 0 for January
to 11 for December.
o date − Integer value representing the day of the month.
o hour − Integer value representing the hour of the day (24-hour scale).
o minute − Integer value representing the minute segment of a time reading.
o second − Integer value representing the second segment of a time reading.
o millisecond − Integer value representing the millisecond segment of a time
reading.

Date Properties
Here is a list of the properties of the Date object along with their description.
Sr.No. Property & Description

1 constructor
WEB PROGRAMMING
Web Programming Page
WEB PROGRAMMING

Specifies the function that creates an object's prototype.

2 prototype
The prototype property allows you to add properties and methods to an
object
In the following sections, we will have a few examples to demonstrate the usage of
different Date properties.

Date Methods
Here is a list of the methods used with Date and their description.

Sr.No. Method & Description

1 Date()

Returns today's date and time

2 getDate()
Returns the day of the month for the specified date according to local
time.
3 getDay()
Returns the day of the week for the specified date according to local
time.
4 getFullYear()
Returns the year of the specified date according to local time.

5 getHours()
Returns the hour in the specified date according to local time.

6 getMilliseconds()
Returns the milliseconds in the specified date according to local time.

7 getMinutes()
Returns the minutes in the specified date according to local time.

8 getMonth()
Returns the month in the specified date according to local time.

Web Programming Page


WEB PROGRAMMING

9 getSeconds()
Returns the seconds in the specified date according to local time.

10 getTime()
Returns the numeric value of the specified date as the number of
milliseconds since January 1, 1970, 00:00:00 UTC.

11 getTimezoneOffset()
Returns the time-zone offset in minutes for the current locale.

12 getUTCDate()
Returns the day (date) of the month in the specified date according to
universal time.

13 getUTCDay()
Returns the day of the week in the specified date according to universal
time.
14 getUTCFullYear()
Returns the year in the specified date according to universal time.

15 getUTCHours()
Returns the hours in the specified date according to universal time.

16 getUTCMilliseconds()
Returns the milliseconds in the specified date according to universal
time.
17 getUTCMinutes()
Returns the minutes in the specified date according to universal time.

18 getUTCMonth()
Returns the month in the specified date according to universal time.

19 getUTCSeconds()
Returns the seconds in the specified date according to universal time.

20 getYear()
Deprecated - Returns the year in the specified date according to local
time. Use
Web Programming Page
WEB PROGRAMMING

getFullYear instead.

21 setDate()
Sets the day of the month for a specified date according to local time.

22 setFullYear()
Sets the full year for a specified date according to local time.

23 setHours()
Sets the hours for a specified date according to local time.

24 setMilliseconds()
Sets the milliseconds for a specified date according to local time.

25 setMinutes()
Sets the minutes for a specified date according to local time.

26 setMonth()
Sets the month for a specified date according to local time.

27 setSeconds()
Sets the seconds for a specified date according to local time.

28 setTime()
Sets the Date object to the time represented by a number of
milliseconds since January 1, 1970, 00:00:00 UTC.

29 setUTCDate()
Sets the day of the month for a specified date according to universal
time.
30 setUTCFullYear()
Sets the full year for a specified date according to universal time.

31 setUTCHours()
Sets the hour for a specified date according to universal time.

32 setUTCMilliseconds()

Web Programming Page


WEB PROGRAMMING

Sets the milliseconds for a specified date according to universal time.

33 setUTCMinutes()
Sets the minutes for a specified date according to universal time.

34 setUTCMonth()
Sets the month for a specified date according to universal time.

35 setUTCSeconds()
Sets the seconds for a specified date according to universal time.

36 setYear()
Deprecated - Sets the year for a specified date according to local time.
Use setFullYear instead.

37 toDateString()
Returns the "date" portion of the Date as a human-readable string.

38 toGMTString()
Deprecated - Converts a date to a string, using the Internet GMT
conventions. Use toUTCString instead.

39 toLocaleDateString()
Returns the "date" portion of the Date as a string, using the current
locale's conventions.

40 toLocaleFormat()
Converts a date to a string, using a format string.

41 toLocaleString()
Converts a date to a string, using the current locale's conventions.

42 toLocaleTimeString()
Returns the "time" portion of the Date as a string, using the current
locale's conventions.

43 toSource()

Web Programming Page


WEB PROGRAMMING

Returns a string representing the source for an equivalent Date object;


you can use this value to create a new object.

44 toString()
Returns a string representing the specified Date object.

45 toTimeString()
Returns the "time" portion of the Date as a human-readable string.

46 toUTCString()
Converts a date to a string, using the universal time convention.

47 valueOf()
Returns the primitive value of a Date object.

Converts a date to a string, using the universal time convention.

Date Static Methods


In addition to the many instance methods listed previously, the Date object also
defines two static methods. These methods are invoked through the Date() constructor
itself.
Sr.No. Method & Description

1 Date.parse( )

Parses a string representation of a date and time and returns the


internal millisecond representation of that date.

2 Date.UTC( )
Returns the millisecond representation of the specified UTC date and
time.

JavaScript - The Math Object


Advertisements

Web Programming Page


WEB PROGRAMMING

Previous
Page Next
Page
The math object provides you properties and methods for mathematical constants and
functions. Unlike other global objects, Math is not a constructor. All the properties and
methods of Math are static and can be called by using Math as an object without creating
it.
Thus, you refer to the constant pi as Math.PI and you call the sine function as Math.sin(x),
where x is the method's argument.

Syntax
The syntax to call the properties and methods of Math are as follows
var pi_val = Math.PI;
var sine_val = Math.sin(30);
Math Properties
Here is a list of all the properties of Math and their description.
Sr.No. Property & Description

1 E\

Euler's constant and the base of natural logarithms, approximately


2.718.
2 LN2
Natural logarithm of 2, approximately 0.693.

3 LN10
Natural logarithm of 10, approximately 2.302.

4 LOG2E
Base 2 logarithm of E, approximately 1.442.

5 LOG10E
Base 10 logarithm of E, approximately 0.434.

6 PI
Ratio of the circumference of a circle to its diameter, approximately
3.14159.
7 SQRT1_2
Square root of 1/2; equivalently, 1 over the square root of 2,
approximately 0.707.
WEB PROGRAMMING
Web Programming Page
WEB PROGRAMMING

8 SQRT2
Square root of 2, approximately 1.414.

In the following sections, we will have a few examples to demonstrate the usage of Math
properties.

Math Methods
Here is a list of the methods associated with Math object and their description
Sr.No. Method & Description

1 abs()

Returns the absolute value of a number.

2 acos()
Returns the arccosine (in radians) of a number.

3 asin()
Returns the arcsine (in radians) of a number.

4 atan()
Returns the arctangent (in radians) of a number.

5 atan2()
Returns the arctangent of the quotient of its arguments.

6 ceil()
Returns the smallest integer greater than or equal to a number.

7 cos()
Returns the cosine of a number.

8 exp()
Returns EN, where N is the argument, and E is Euler's constant, the base
of the natural logarithm.

9 floor()

Web Programming Page


WEB PROGRAMMING

Returns the largest integer less than or equal to a number.

10 log()
Returns the natural logarithm (base E) of a number.

11 max()
Returns the largest of zero or more numbers.

12 min()
Returns the smallest of zero or more numbers.

13 pow()
Returns base to the exponent power, that is, base exponent.

14 random()
Returns a pseudo-random number between 0 and 1.

15 round()
Returns the value of a number rounded to the nearest integer.

16 sin()
Returns the sine of a number.

17 sqrt()
Returns the square root of a number.

18 tan()
Returns the tangent of a number.

19 toSource()
Returns the string "Math".

NAMES

name' is the property of the window object of the browser. It is a built-in property in JavaScript.

Web Programming Page


WEB PROGRAMMING

JavaScript Literals

JavaScript Literals are constant values that can be assigned to the variables that are called literals or constants.

JavaScript Literals are syntactic representations for different types of data like numeric, string, Boolean, array, etc

data. Literals in JavaScript provide a means of representing particular or some specific values in our program.

Consider an example, var name = “john”, a string variable named name is declared and assigned a string value

“john”. The literal “john” represents, the value john for the variable name. There are different types of literals that

are supported by JavaScript.

What are the Types of JavaScript Literals?


Javascript literals hold different types of values. Examples of JavaScript Literals are given below:

1. Integer Literals
Integer literals are numbers, must have minimum one digit (0-9). No blank or comma is allowed within an integer.

It can store positive numbers or negative numbers. In integers, literals in JavaScript can be supported in three

different bases. The base 10 that is Decimal (Decimal numbers contain digits (0,9) ) examples for Decimal

numbers are 234, -56, 10060. Second is base 8 that is Octal (Octal numbers contains digits (0,7) and leading 0

indicates the number is octal), 0X 073, -089, 02003. Third is base 16 that is Hexadecimal numbers (Hexadecimal

numbers contains (0,9) digits and (A,F) or (a, f) letters and leading 0x or 0X indicates the number is

hexadecimal), examples for hexadecimal numbers are 0X8b, – 0X89, 0X2003.

Let us understand with example code.

Example:

Web Programming Page


WEB PROGRAMMING

<!DOCTYPE html>

<html>

<head>

<meta charset= "utf-8" >

<title> This is an example for numeric literals </title>

</head>

<body>

<h1>JavaScript Numbers </h1>

<p> Number can be written of any base.</p>

Decimal number : <b id="no1"></b><br>

Octal number : <b id="no2"></b><br>

Hexadecimal number : <b id="no3"></b><br>

<script>

document.getElementById("no1").innerHTML = 100.25;

</script>

<script>

document.getElementById("no2").innerHTML = 073;

</script>

<script>

document.getElementById("no3").innerHTML = 0X8b;
Web Programming Page
WEB PROGRAMMING

</script>

</body>

</html>

Output:

2. Floating Number Literals


Floating numbers are decimal numbers or fraction numbers or even can have an exponent part as well. Examples

for hexadecimal numbers are 78.90, -234.90, 78.6e4 etc.

Let us understand with example code.

Example:

<!DOCTYPE html>

<html>

<head>

Web Programming Page


WEB PROGRAMMING

<meta charset= "utf-8" >

<title> This is an example for float literals </title>

</head>

<body>

<h1>JavaScript Float </h1>

<p> Float Examples are : </p>

1. <b id="no1"></b><br>

2. <b id="no2"></b><br>

3. <b id="no3"></b><br>

<script>

document.getElementById("no1").innerHTML = 100.25;

</script>

<script>

document.getElementById("no2").innerHTML = -78.34;

</script>

<script>

document.getElementById("no3").innerHTML = 56e4;

</script>

</body>

</html>
Web Programming Page
WEB PROGRAMMING

3. String Literals
A string literals are a sequence of zero or more characters. A string literals are either enclosed in the single

quotation or double quotation as ( ‘ ) and ( “ ) respectively and to concatenate two or more string we can use +

operator. Examples for string are “hello”, “hello world”, “123”, “hello” + “world” etc.

List of special characters that can be used in JavaScript string are.

 \b: Backspace.

 \n: New Line

 \t: Tab

 \f: Form Feed

 \r: Carriage Return

 \\: Backslash Character (\)

 \’ : Single Quote

 \”: Double Quote

Let us understand with an example code –

Example:

<!DOCTYPE html>

<html>

<head>

<meta charset= "utf-8" >

Web Programming Page


WEB PROGRAMMING

<title> This is an example for float literals </title>

</head>

<body>

<h1>JavaScript String </h1>

<p> String Examples are : </p>

1. <b id="no1"></b><br>

2. <b id="no2"></b><br>

3. <b id="no3"></b><br>

4. <b id="no4"></b><br>

<script>

var str = "This is first string";

document.getElementById("no1").innerHTML = str;

</script>

<script>

var strobj = new String("This is string store as object");

document.getElementById("no2").innerHTML = strobj;

</script>

<script>

var str = "This is first string";

document.getElementById("no3").innerHTML = str.length;
Web Programming Page
WEB PROGRAMMING

</script>

<script>

var str = "This is first string";

document.getElementById("no4").innerHTML = str+" This is second string";

</script>

</body>

</html>

Output:

4. Array Literals
Array literals are a list of expressions or other constant values, each of which expression known as an array

element. An array literal contains a list of element s within square brackets ‘ [ ] ‘ . If no value is a pass when

it creates an empty array with zero length. If elements are passed then its length is set to the number of elements

passed. Examples for string are var color = [ ], var fruits = [“Apple”, “Orange”, “Mango”, “Banana”] (an array of

four elements).

Let us understand with example code.

Example:

<!DOCTYPE html>

<html>

<head>

Web Programming Page


WEB PROGRAMMING

<meta charset= "utf-8" >

<title> This is an example for float literals </title>

</head>

<body>

<h1>JavaScript Array </h1>

<p> Array Examples are : </p>

1. <b id="no1"></b><br>

2. <b id="no2"></b><br>

3. <b id="no3"></b><br>

4. <b id="no4"></b><br>

<script>

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

document.getElementById("no1").innerHTML = fruits;

</script>

<script>

document.getElementById("no2").innerHTML = fruits[0];

</script>

<script>

document.getElementById("no3").innerHTML = fruits[fruits.length - 1];

</script>
Web Programming Page
WEB PROGRAMMING

<script>

document.getElementById("no4").innerHTML = fruits.length;

</script>

</body>

</html>

Output:

5. Boolean Literals
Boolean literals in JavaScript have only two literal values that are true and false.

Let us understand with an example code.

Example:

<!DOCTYPE html>

<html>

<head>

<meta charset= "utf-8" >


Web Programming Page
WEB PROGRAMMING

<title> This is an example for Boolean literals </title>

</head>

<body>

<h1>JavaScript Boolean </h1>

<p> Boolean Examples are : </p>

<script>

document.write('Boolean(12) is ' + Boolean(12));

document.write('<br>');

document.write('Boolean("Hello") is ' + Boolean("Hello"));

document.write('<br>');

document.write('Boolean(2 > 3) is ' + Boolean(2 > 3));

document.write('<br>');

document.write('Boolean(3 > 2) is ' + Boolean(3 > 2));

document.write('<br>');

document.write('Boolean(-12) is ' + Boolean(-12));

document.write('<br>');

document.write("Boolean('true') is " + Boolean('true'));

document.write('<br>');

document.write("Boolean('false') is " + Boolean('false'));

document.write('<br>');
Web Programming Page
WEB PROGRAMMING

document.write('Boolean(0) is ' + Boolean(0));

</script>

</body>

</html>

Output:

6. Object Literals
Object literals are collection zero or more key-value pairs of a comma-separated list, which are enclosed by a pair

of curly braces ‘ { } ‘.Examples for object literal with declaration are var userObject = { }, var student = { f-name :

“John”, l-name : “D”, “rno” : 23, “marks” : 60}

Let understand with an example code –

Example:

<!DOCTYPE html>

<html>

Web Programming Page


WEB PROGRAMMING

<head>

<meta charset= "utf-8" >

<title> This is an example for Object literals </title>

</head>

<body>

<h1>JavaScript Object </h1>

<p> Object Examples are : </p>

<p id= "no1"> </p>

<script>

// Create an object:

var student = {firstName:"John", lastName:"D", "rno" : 23, "marks" : 60 };

// Displaying some data from the object:

document.getElementById("no1").innerHTML =

student.firstName + " got " + student.marks + " marks.";

</script>

</body>

</html>

Expressions and operators

JavaScript has the following types of operators. This section describes the operators and contains information

about operator precedence.


Web Programming Page
WEB PROGRAMMING

 Assignment operators

 Comparison operators

 Arithmetic operators

 Bitwise operators

 Logical operators

 String operators

 Conditional (ternary) operator

 Comma operator

 Unary operators

 Relational operators

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A

binary operator requires two operands, one before the operator and one after the operator:

operand1 operator operand2

Copy to Clipboard

For example, 3+4 or x*y.

A unary operator requires a single operand, either before or after the operator:

operator operand

Copy to Clipboard

or

Web Programming Page


WEB PROGRAMMING

operand operator

Copy to Clipboard

For example, x++ or ++x.

Assignment operators

An assignment operator assigns a value to its left operand based on the value of its right operand. The simple

assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = f() is

an assignment expression that assigns the value of f() to x.

There are also compound assignment operators that are shorthand for the operations listed in the following table:

Name Shorthand operator Me

Assignment x = f() x=

Addition assignment x += f() x=

Subtraction assignment x -= f() x=

Multiplication assignment x *= f() x=

Division assignment x /= f() x=

Remainder assignment x %= f() x=

Web Programming Page


WEB PROGRAMMING

Name Shorthand operator Me

Exponentiation assignment x **= f() x=

Left shift assignment x <<= f() x=

Right shift assignment x >>= f() x=

Unsigned right shift assignment x >>>= f() x=

Bitwise AND assignment x &= f() x=

Bitwise XOR assignment x ^= f() x=

Bitwise OR assignment x |= f() x=

Logical AND assignment x &&= f() x&

Logical OR assignment x ||= f() x ||

Logical nullish assignment x ??= f() x ??

Assigning to properties

If a variable refers to an object, then the left-hand side of an assignment expression may make assignments to

properties of that variable. For example:

let obj = {};

Web Programming Page


WEB PROGRAMMING

obj.x = 3;

console.log(obj.x); // Prints 3.

console.log(obj); // Prints { x: 3 }.

const key = "y";

obj[key] = 5;

console.log(obj[key]); // Prints 5.

console.log(obj); // Prints { x: 3, y: 5 }.

Copy to Clipboard

For more information about objects, read Working with Objects.

Destructuring

For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it

possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object

literals.

var foo = ['one', 'two', 'three'];

Web Programming Page


WEB PROGRAMMING

// without destructuring

var one = foo[0];

var two = foo[1];

var three = foo[2];

// with destructuring

var [one, two, three] = foo;

Copy to Clipboard

Evaluation and nesting

In general, assignments are used within a variable declaration (i.e., with const, let, or var) or as standalone

statements.

// Declares a variable x and initializes it to the result of f().

// The result of the x = f() assignment expression is discarded.

let x = f();

// Declares a variable x and initializes it to the result of f().

Web Programming Page


WEB PROGRAMMING

// The result of the x = g() assignment expression is discarded.

x = g(); Reassigns the variable x to the result of g().

Copy to Clipboard

However, like other expressions, assignment expressions like x = f() evaluate into a result value. Although this

result value is usually not used, it can then be used by another expression.

Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this

reason, some JavaScript style guides discourage chaining or nesting assignments). Nevertheless, assignment

chaining and nesting may occur sometimes, so it is important to be able to understand how they work.

By chaining or nesting an assignment expression, its result can itself be assigned to another variable. It can be

logged, it can be put inside an array literal or function call, and so on.

let x;

const y = (x = f()); // Or equivalently: const y = x = f();

console.log(y); // Logs the return value of the assignment x = f().

console.log(x = f()); // Logs the return value directly.

// An assignment expression can be nested in any place

Web Programming Page


WEB PROGRAMMING

// where expressions are generally allowed,

// such as as array literals’ elements or as function calls’ arguments.

console.log([ 0, x = f(), 0 ]);

console.log(f(0, x = f(), 0));

Copy to Clipboard

The evaluation result matches the expression to the right of the = sign in the “Meaning” column of the table above.

That means that x = f() evaluates into whatever f()’s result is, x += f() evaluates into the resulting sum x + f(), x

**= f() evaluates into the resulting power x ** y, and so on.

In the case of logical assignments, x &&= f(), x ||= f(), and x ??= f(), the return value is that of the logical

operation without the assignment, so x && f(), x || f(), and x ?? f(), respectively.

When chaining these expressions without parentheses or other grouping operators like array literals, the

assignment expressions are grouped right to left (they are right-associative), but they are evaluated left to right.

Note that, for all assignment operators other than = itself, the resulting values are always based on the operands’

values before the operation.

For example, assume that the following functions f and g and the variables x and y have been declared:

function f () {

console.log('F!');

return 2;
Web Programming Page
WEB PROGRAMMING

function g () {

console.log('G!');

return 3;

let x, y;

Copy to Clipboard

Consider these three examples:

y = x = g()

y = [ f(), x = g() ]

x[f()] = g()

Copy to Clipboard

Evaluation example 1

y = x = f() is equivalent to y = (x = f()), because the assignment operator = is right-associative. However, it

evaluates from left to right:

1. The assignment expression y = x = f() starts to evaluate.

1. The y on this assignment’s left-hand side evaluates into a reference to the variable named y.
Web Programming Page
WEB PROGRAMMING

2. The assignment expression x = f() starts to evaluate.

1. The x on this assignment’s left-hand side evaluates into a reference to the variable named y.

2. The function call f() prints "F!" to the console and then evaluates to the number 2.

3. That 2 result from f() is assigned to x.

3. The assignment expression x = f() has now finished evaluating; its result is the new value of x,

which is 2.

4. That 2 result in turn is also assigned to y.

2. The assignment expression y = x = f() has now finished evaluating; its result is the new value of y – which

happens to be 2. x and y are assigned to 2, and the console has printed "F!".

Evaluation example 2

y = [ f(), x = g() ] also evaluates from left to right:

1. The assignment expression y = [ f(), x = g() ] starts to evaluate.

1. The y on this assignment’s left-hand evaluates into a reference to the variable named y.

2. The inner array literal [ f(), x = g() ] starts to evaluate.

3. The function call f() prints "F!" to the console and then evaluates to the number 2.

4. The assignment expression x = g() starts to evaluate.

1. The x on this assignment’s left-hand side evaluates into a reference to the variable named x.

2. The function call g() prints "3!" to the console and then evaluates to the number 3.

3. That 3 result from f() is assigned to x.

5. The assignment expression x = g() has now finished evaluating; its result is the new value of x,

which is 3. That 3 result becomes the next element in the inner array literal (after the 2 from the f()).

Web Programming Page


WEB PROGRAMMING

6. The inner array literal [ f(), x = g() ] has now finished evaluating; its result is an array with

two values: [ 2, 3 ].

7. That [ 2, 3 ] array is now assigned to y.

2. The assignment expression y = [ f(), x = g() ] has now finished evaluating; its result is the new value of y –

which happens to be [ 2, 3 ]. x is now assigned to 3, y is now assigned to [ 2, 3 ], and the console has

printed "F!" then "G!".

Evaluation example 2

x[f()] = g() also evaluates from left to right. (This example assumes that x is already assigned to some object. For

more information about objects, read Working with Objects.)

1. The assignment expression x[f()] = g() starts to evaluate.

1. The x[f()] property access on this assignment’s left-hand starts to evaluate.

1. The x in this property access evaluates into a reference to the variable named x.

2. Then the function call f() prints "F!" to the console and then evaluates to the number 2.

2. The x[f()] property access on this assignment has now finished evaluating; its result is a

variable property reference: x[2].

3. Then the function call g() prints "G!" to the console and then evaluates to the number 3.

4. That 3 is now assigned to x[2]. (This step will succeed only if x is assigned to an object.)

2. The assignment expression x[f()] = g() has now finished evaluating; its result is the new value of x[2] –

which happens to be 3. x[2] is now assigned to 3, and the console has printed "F!" then "G!".

Avoid assignment chains

Web Programming Page


WEB PROGRAMMING

Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this

reason, chaining assignments in the same statement is discouraged).

In particular, putting a variable chain in a const, let, or var statement often does not work. Only the

outermost/leftmost variable would get declared; any other variables within the assignment chain are not declared

by the const/let/var statement. For example:

let z = y = x = f();

Copy to Clipboard

This statement seemingly declares the variables x, y, and z. However, it only actually declares the

variable z. y and x are either invalid references to nonexistent variables (in strict mode) or, worse, would implicitly

create global variables for x and y in sloppy mode.

Comparison operators

A comparison operator compares its operands and returns a logical value based on whether the comparison is true.

The operands can be numerical, string, logical, or object values. Strings are compared based on standard

lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type,

JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in

comparing the operands numerically. The sole exceptions to type conversion within comparisons involve

the === and !== operators, which perform strict equality and inequality comparisons. These operators do not

attempt to convert the operands to compatible types before checking equality. The following table describes the

comparison operators in terms of this sample code:

var var1 = 3;

Web Programming Page


WEB PROGRAMMING

var var2 = 4;

Copy to Clipboard

Comparison operators

Operator Description

Equal (==) Returns true if the operands are equal.

Not equal (!=) Returns true if the operands are not equal.

Returns true if the operands are equal and of the same type. See
Strict equal (===)
also Object.is and sameness in JS.

Strict not equal (!==) Returns true if the operands are of the same type but not equal, or are of different type.

Greater than (>) Returns true if the left operand is greater than the right operand.

Web Programming Page


WEB PROGRAMMING

Comparison operators

Operator Description

Greater than or
Returns true if the left operand is greater than or equal to the right operand.
equal (>=)

Less than (<) Returns true if the left operand is less than the right operand.

Less than or equal (<=) Returns true if the left operand is less than or equal to the right operand.

Note: => is not a comparison operator but rather is the notation for Arrow functions.

Arithmetic operators

An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single

numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division

(/). These operators work as they do in most other programming languages when used with floating point numbers

(in particular, note that division by zero produces Infinity). For example:

1 / 2; // 0.5

1 / 2 == 1.0 / 2.0; // this is true

Copy to Clipboard
Web Programming Page
WEB PROGRAMMING

In addition to the standard arithmetic operations (+, -, *, /), JavaScript provides the arithmetic operators listed in

the following table:

Arithmetic operators

Operator Description Example

Remainder (%) Binary operator. Returns the integer remainder of dividing the two operands. 12 % 5 returns 2

Unary operator. Adds one to its operand. If used as a prefix operator (++x), If x is 3, then ++

Increment (++) returns the value of its operand after adding one; if used as a postfix operator 4, whereas x++ r

(x++), returns the value of its operand before adding one. sets x to 4.

If x is 3, then --x
Unary operator. Subtracts one from its operand. The return value is
Decrement (--) whereas x-- retur
analogous to that for the increment operator.
sets x to 2.

Unary negation Unary operator. Returns the negation of its operand. If x is 3, then -x
(-)

+"3" returns 3.
Unary plus (+) Unary operator. Attempts to convert the operand to a number, if it is

not already.
+true returns 1.

Exponentiation 2 ** 3 returns 8.
Calculates the base to the exponent power, that is, base^exponent
operator (**) 10 ** -1 returns

Bitwise operators

Web Programming Page


WEB PROGRAMMING

A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or

octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators

perform their operations on such binary representations, but they return standard JavaScript numerical values.

The following table summarizes JavaScript's bitwise operators.

Operator Usage Description

Bitwise AND a&b Returns a one in each bit position for which the corresponding bits of both operands

Bitwise OR a|b Returns a zero in each bit position for which the corresponding bits of both operands

Returns a zero in each bit position for which the corresponding bits are the same. [Re
Bitwise XOR a^b
position for which the corresponding bits are different.]

Bitwise NOT ~a Inverts the bits of its operand.

Left shift a << Shifts a in binary representation b bits to the left, shifting in zeros from the right.
b

Sign-propagating
a >> Shifts a in binary representation b bits to the right, discarding bits shifted off.
right shift b

a >>> Shifts a in binary representation b bits to the right, discarding bits shifted off, and shi
Zero-fill right shift
b left.

Bitwise logical operators

Web Programming Page


WEB PROGRAMMING

Conceptually, the bitwise logical operators work as follows:

 The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones).

Numbers with more than 32 bits get their most significant bits discarded. For example, the following

integer with more than 32 bits will be converted to a 32 bit integer:

 Before: 1110 0110 1111 1010 0000 0000 0000 0110 0000 0000 0001

 After: 1010 0000 0000 0000 0110 0000 0000 0001

 Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit,

second bit to second bit, and so on.

 The operator is applied to each pair of bits, and the result is constructed bitwise.

For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when

the bitwise operators are applied to these values, the results are as follows:

Expression Result Binary Description

15 & 9 9 1111 & 1001 = 1001

15 | 9 15 1111 | 1001 = 1111

15 ^ 9 6 1111 ^ 1001 = 0110

~15 -16 ~ 0000 0000 ... 0000 1111 = 1111 1111 ... 1111 0000

~9 -10 ~ 0000 0000 ... 0000 1001 = 1111 1111 ... 1111 0110

Web Programming Page


WEB PROGRAMMING

Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with the most significant (left-

most) bit set to 1 represent negative numbers (two's-complement representation). ~x evaluates to the same value

that -x - 1 evaluates to.

Bitwise shift operators

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the

number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled

by the operator used.

Shift operators convert their operands to thirty-two-bit integers and return a result of either type Number or BigInt:

specifically, if the type of the left operand is BigInt, they return BigInt; otherwise, they return Number.

The shift operators are listed in the following table.

Bitwise shift operators

Operator Description Example

This operator shifts the first operand the specified number


Left shift 9<<2 yields 36, because 1001 shifted
of bits to the left. Excess bits shifted off to the left are
(<<) becomes 100100, which is 36.
discarded. Zero bits are shifted in from the right.

This operator shifts the first operand the specified number 9>>2 yields 2, because 1001 shifted
Sign-propagating
of bits to the right. Excess bits shifted off to the right are becomes 10, which is 2. Likewise, -9
right shift (>>)
discarded. Copies of the leftmost bit are shifted in from the the sign is preserved.

Web Programming Page


WEB PROGRAMMING

Bitwise shift operators

Operator Description Example

left.

19>>>2 yields 4, because 10011 shif


This operator shifts the first operand the specified number
Zero-fill right becomes 100, which is 4. For non-ne
of bits to the right. Excess bits shifted off to the right are
shift (>>>) right shift and sign-propagating right
discarded. Zero bits are shifted in from the left.
result.

Logical operators

Logical operatorsare typically used with Boolean (logical) values; when they are, th ey return a Boolean value.

However, the &&and || operators actually return the value of one of the specified operands, so if these operators

are used with non-Boo lean values, they may return a non-Boolean value. The logi cal operators are described in the

following table.

Logical operators

Operator Us age Description

Logical expr1 && Returns expr1 if it can be converted to false; othe rwise, returns expr2. Thus, when us

AND (&&) expr2 values, && returns true if both operands are true ; otherwise, returns false.

Logical OR (||) expr1 || Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when use

Web Program ming Page


WEB PROGRAMMING

Logical operators

Operator Usage Description

expr2 values, || returns true if either operand is true; if both are false, returns false.

Logical
!expr Returns false if its single operand that can be converted to true; otherwise, returns tru
NOT (!)

Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string

(""), or undefined.

The following code shows examples of the && (logical AND) operator.

var a1 = true && true; // t && t returns true

var a2 = true && false; // t && f returns

false

var a3 = false && true; // f && t returns false

var a4 = false && (3 == 4); // f && f returns false

var a5 = 'Cat' && 'Dog'; // t && t returns Dog

var a6 = false && 'Cat'; // f && t returns false

var a7 = 'Cat' && false; // t && f returns false

Web Programming
Copy to Clipboard Page
WEB PROGRAMMING

The following code shows examples of the || (logical OR) operator.

var o1 = true || true; // t || t returns true

var o2 = false || true; // f || t returns

true

var o3 = true || false; // t || f returns true

var o4 = false || (3 == 4); // f || f returns

false var o5 = 'Cat' || 'Dog'; // t || t

returns Cat

var o6 = false || 'Cat'; // f || t returns Cat

var o7 = 'Cat' || false; // t || f returns Cat

Copy to Clipboard

The following code shows examples of the ! (logical NOT) operator.

var n1 = !true; // !t returns false

var n2 = !false; // !f returns true

var n3 = !'Cat'; // !t returns false

Copy to Clipboard

Short-circuit evaluation
WEB PROGRAMMING

Web Programming Page


WEB PROGRAMMING

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the

following rules:

 false && anything is short-circuit evaluated to false.

 true || anything is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above

expressions is not evaluated, so any side effects of doing so do not take effect.

Note that for the second case, in modern code you can use the new Nullish coalescing operator (??) that works

like ||, but it only returns the second expression, when the first one is "nullish", i.e. null or undefined. It is thus the

better alternative to provide defaults, when values like '' or 0 are valid values for the first expression, too.

String operators

In addition to the comparison operators, which can be used on string values, the concatenation operator (+)

concatenates two string values together, returning another string that is the union of the two operand strings.

For example,

console.log('my ' + 'string'); // console logs the string "my string".

Copy to Clipboard

The shorthand assignment operator += can also be used to concatenate strings.

For example,

var mystring = 'alpha';

Web Programming Page


WEB PROGRAMMING

mystring += 'bet'; // evaluates to "alphabet" and assigns this value to mystring.

Copy to Clipboard

Conditional (ternary) operator

The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of

two values based on a condition. The syntax is:

condition ? val1 : val2

Copy to Clipboard

If condition is true, the operator has the value of val1. Otherwise it has the value of val2. You can use the

conditional operator anywhere you would use a standard operator.

For example,

var status = (age >= 18) ? 'adult' : 'minor';

Copy to Clipboard

This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the

value "minor" to status.

Comma operator

The comma operator (,) evaluates both of its operands and returns the value of the last operand. This operator is

primarily used inside a for loop, to allow multiple variables to be updated each time through the loop. It is regarded

Web Programming Page


WEB PROGRAMMING

bad style to use it elsewhere, when it is not necessary. Often two separate statements can and should be used

instead.

For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator

to update two variables at once. The code prints the values of the diagonal elements in the array:

var x = [0,1,2,3,4,5,6,7,8,9]

var a = [x, x, x, x, x];

for (var i = 0, j = 9; i <= j; i++, j--)

// ^

console.log('a[' + i + '][' + j + ']= ' + a[i][j]);

Copy to Clipboard

Unary operators

A unary operation is an operation with only one operand.

delete

The delete operator deletes an object's property. The syntax is:

delete object.property;

delete object[propertyKey];
Web Programming Page
WEB PROGRAMMING

delete objectName[index];

Copy to Clipboard

where object is the name of an object, property is an existing property, and propertyKey is a string or symbol

referring to an existing property.

If the delete operator succeeds, it removes the property from the object. Trying to access it afterwards will

yield undefined. The delete operator returns true if the operation is possible; it returns false if the operation is not

possible.

delete Math.PI; // returns false (cannot delete non-configurable properties)

const myObj = {h: 4};

delete myobj.h; // returns true (can delete user-defined properties)

Copy to Clipboard

Deleting array elements

Since arrays are just objects, it's technically possible to delete elements from them. This is however regarded as a

bad practice, try to avoid it. When you delete an array property, the array length is not affected and other elements

are not re-indexed. To achieve that behavior, it is much better to just overwrite the element with the

value undefined. To actually manipulate the array, use the various array methods such as splice.

typeof

Web Programming Page


WEB PROGRAMMING

The typeof operator is used in either of the following ways:

typeof operand

typeof (operand)

Copy to Clipboard

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable,

keyword, or object for which the type is to be returned. The parentheses are optional.

Suppose you define the following variables:

var myFun = new Function('5 + 2');

var shape = 'round';

var size = 1;

var foo = ['Apple', 'Mango', 'Orange'];

var today = new Date();

Copy to Clipboard

The typeof operator returns the following results for these

variables: typeof myFun; // returns "function"

typeof shape; // returns "string"

Web Programming Page


WEB PROGRAMMING

typeof size; // returns "number"

typeof foo; // returns "object"

typeof today; // returns "object"

typeof doesntExist; // returns "undefined"

Copy to Clipboard

For the keywords true and null, the typeof operator returns the following results:

typeof true; // returns "boolean"

typeof null; // returns "object"

Copy to Clipboard

For a number or string, the typeof operator returns the following results:

typeof 62; // returns "number"

typeof 'Hello world'; // returns "string"

Copy to Clipboard

For property values, the typeof operator returns the type of value the property contains:

typeof document.lastModified; // returns "string"

typeof window.length; // returns "number"

Web Programming Page


WEB PROGRAMMING

typeof Math.LN2; // returns "number"

Copy to Clipboard

For methods and functions, the typeof operator returns results as follows:

typeof blur; // returns "function"

typeof eval; // returns "function"

typeof parseInt; // returns "function"

typeof shape.split; // returns "function"

Copy to Clipboard

For predefined objects, the typeof operator returns results as follows:

typeof Date; // returns "function"

typeof Function; // returns "function"

typeof Math; // returns "object"

typeof Option; // returns "function"

typeof String; // returns "function"

Copy to Clipboard

void

Web Programming Page


WEB PROGRAMMING

The void operator is used in either of the following ways:

void (expression)

void expression

Copy to Clipboard

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript

expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.

Relational operators

A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.

in

The in operator returns true if the specified property is in the specified object. The syntax is:

propNameOrNumber in objectName

Copy to Clipboard

where propNameOrNumber is a string, numeric, or symbol expression representing a property name or array

index, and objectName is the name of an object.

The following examples show some uses of the in operator.

// Arrays

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];


Web Programming Page
WEB PROGRAMMING

0 in trees; // returns true

3 in trees; // returns true

6 in trees; // returns

false

'bay' in trees; // returns false (you must specify the index number,

// not the value at that index)

'length' in trees; // returns true (length is an Array property)

// built-in objects

'PI' in Math; // returns true

var myString = new String('coral');

'length' in myString; // returns true

// Custom objects

var mycar = { make: 'Honda', model: 'Accord', year: 1998 };

'make' in mycar; // returns true

'model' in mycar; // returns true

Web Programming Page


WEB PROGRAMMING

Copy to Clipboard

instanceof

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:

objectName instanceof objectType

Copy to Clipboard

where objectName is the name of the object to compare to objectType, and objectType is an object type, such

as Date or Array.

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions,

you can branch to different exception-handling code depending on the type of exception thrown.

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is

a Date object, the statements in the if statement execute.

var theDay = new Date(1995, 12, 17);

if (theDay instanceof Date) {

// statements to execute

Copy to Clipboard

Operator precedence

Web Programming Page


WEB PROGRAMMING

The precedence of operators determines the order they are applied when evaluating an expression. You can

override operator precedence by using parentheses.

The following table describes the precedence of operators, from highest to lowest.

Operator type Individual operators

member . []

call / create instance () new

negation/increment ! ~ - + ++ -- typeof void delete

multiply/divide */%

addition/subtraction +-

bitwise shift << >> >>>

relational < <= > >= in instanceof

equality == != === !==

bitwise-and &

bitwise-xor ^

bitwise-or |

Web Programming Page


WEB PROGRAMMING

Operator type Individual operators

logical-and &&

logical-or ||

conditional ?:

assignment = += -= *= /= %= <<= >>= >>>= &= ^= |= &&= ||= ??=

comma ,

A more detailed version of this table, complete with links to additional details about each operator, may be found

in JavaScript Reference.

Expressions

An expression is any valid unit of code that resolves to a value.

Every syntactically valid expression resolves to some value but conceptually, there are two types of expressions:

with side effects (for example: those that assign value to a variable) and those that in some sense evaluate and

therefore resolve to a value.

The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven

to the variable x. The expression itself evaluates to seven.

The code 3 + 4 is an example of the second expression type. This expression uses the + operator to add three and

four together without assigning the result, seven, to a variable.

Web Programming Page


WEB PROGRAMMING

JavaScript has the following expression categories:

 Arithmetic: evaluates to a number, for example 3.14159. (Generally uses arithmetic operators.)

 String: evaluates to a character string, for example, "Fred" or "234". (Generally uses string operators.)

 Logical: evaluates to true or false. (Often involves logical operators.)

 Primary expressions: Basic keywords and general expressions in JavaScript.

 Left-hand-side expressions: Left values are the destination of an assignment.

Primary expressions

Basic keywords and general expressions in JavaScript.

this

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method.

Use this either with the dot or the bracket notation:

this['propertyName']

this.propertyName

Copy to Clipboard

Suppose a function called validate validates an object's value property, given the object and the high and low

values:

function validate(obj, lowval, hival) {

if ((obj.value < lowval) || (obj.value > hival))

Web Programming Page


WEB PROGRAMMING

console.log('Invalid Value!');

Copy to Clipboard

You could call validate in each form element's onChange event handler, using this to pass it to the form element,

as in the following example:

<p>Enter a number between 18 and 99:</p>

<input type="text" name="age" size=3 onChange="validate(this, 18, 99);">

Copy to Clipboard

Grouping operator

The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override

multiplication and division first, then addition and subtraction to evaluate addition first.

var a = 1;

var b = 2;

var c = 3;

// default precedence

a+b*c // 7
Web Programming Page
WEB PROGRAMMING

// evaluated by default like this

a + (b * c) // 7

// now overriding precedence

// addition before multiplication

(a + b) * c // 9

// which is equivalent to

a * c + b * c // 9

Copy to Clipboard

Left-hand-side expressions

Left values are the destination of an assignment.

new

You can use the new operator to create an instance of a user-defined object type or of one of the built-in object

types. Use new as follows:

var objectName = new objectType([param1, param2, ..., paramN]);

Web Programming Page


WEB PROGRAMMING

Copy to Clipboard

super

The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent

constructor, for example.

super([arguments]); // calls the parent constructor.

super.functionOnParent([arguments]);

Statements and declarations


JavaScript applications consist of statements with an appropriate syntax. A single statement may span
multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon.
This isn't a keyword, but a group of keywords.

Statements and declarations by category


For an alphabetical listing see the sidebar on the left.

Control flow
Block

A block statement is used to group zero or more statements. The block is delimited by a pair of
curly brackets.

break
Terminates the current loop, switch, or label statement and transfers program control to the statement
following the terminated statement.

continue
Terminates execution of the statements in the current iteration of the current or labeled loop, and
continues execution of the loop with the next iteration.

Empty
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.

if...else
Executes a statement if a specified condition is true. If the condition is false, another statement can be
Web Programming Page
WEB PROGRAMMING
executed.

Web Programming Page


WEB PROGRAMMING

switch
Evaluates an expression, matching the expression's value to a case clause, and executes statements
associated with that case.

throw
Throws a user-defined exception.

try...catch
Marks a block of statements to try, and specifies a response, should an exception be thrown.

Declarations
var

Declares a variable, optionally initializing it to a value.

let
Declares a block scope local variable, optionally initializing it to a value.

const
Declares a read-only named constant.

Functions and classes


function
Declares a function with the specified parameters.

function*
Generator Functions enable writing iterators more easily.

async function
Declares an async function with the specified parameters.

return
Specifies the value to be returned by a function.

class
Declares a class.

Iterations
do...while
Creates a loop that executes a specified statement until the test condition evaluates to false. The
condition is evaluated after executing the statement, resulting in the specified statement executing at
least once.
Web Programming Page
WEB PROGRAMMING

for
Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by
semicolons, followed by a statement executed in the loop.

for...in
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property,
statements can be executed.

for...of
Iterates over iterable objects (including arrays, array-like objects, iterators and generators), invoking a
custom iteration hook with statements to be executed for the value of each distinct property.

for await...of
Iterates over async iterable objects, array-like objects, iterators and generators, invoking a custom
iteration hook with statements to be executed for the value of each distinct property.

while
Creates a loop that executes a specified statement as long as the test condition evaluates to true. The
condition is evaluated before executing the statement.

Window Object

The window object represents an open window in a browser.

If a document contain frames (<iframe> tags), the browser creates one window object for the HTML document,
and one additional window object for each frame.

Note: There is no public standard that applies to the Window object, but all major browsers support it.

Window Object Properties

Property Description

closed Returns a Boolean value indicating whether a window has been closed or not

console Returns a reference to the Console object, which provides methods for logging to t
information browser's console (See Console object)

Web Programming Page


WEB PROGRAMMING

defaultStatus Sets or returns the default text in the statusbar of a window

document Returns the Document object for the window (See Document object)

frameElement Returns the <iframe> element in which the current window is inserted

frames Returns all <iframe> elements in the current window

history Returns the History object for the window (See History object)

innerHeight Returns the height of the window's content area (viewport) including scrollbars

innerWidth Returns the width of a window's content area (viewport) including scrollbars

length Returns the number of <iframe> elements in the current window

localStorage Allows to save key/value pairs in a web browser. Stores the data with no expiration date

location Returns the Location object for the window (See Location object)

name Sets or returns the name of a window

Web Programming Page


WEB PROGRAMMING

navigator Returns the Navigator object for the window (See Navigator object)

opener Returns a reference to the window that created the window

outerHeight Returns the height of the browser window, including toolbars/scrollbars

outerWidth Returns the width of the browser window, including toolbars/scrollbars

pageXOffset Returns the pixels the current document has been scrolled (horizontally) from the upper left cor
window

pageYOffset Returns the pixels the current document has been scrolled (vertically) from the upper left orne
c window

parent Returns the parent window of the current window

screen Returns the Screen object for the window (See Screen object)

screenLeft Returns the horizontal coordinate of the window relative to the screen

screenTop Returns the vertical coordinate of the window relative to the screen

screenX Returns the horizontal coordinate of the window relative to the screen

Web Programming Page


WEB PROGRAMMING

screenY Returns the vertical coordinate of the window relative to the screen

sessionStorage Allows to save key/value pairs in a web browser. Stores the data for one session

scrollX An alias of pageXOffset

scrollY An alias of pageYOffset

self Returns the current window

status Sets or returns the text in the statusbar of a window

top Returns the topmost browser window

Window Object Methods

Method Description

alert() Displays an alert box with a message and an OK button

atob() Decodes a base-64 encoded string

Web Programming Page


WEB PROGRAMMING

blur() Removes focus from the current window

btoa() Encodes a string in base-64

clearInterval() Clears a timer set with setInterval()

clearTimeout() Clears a timer set with setTimeout()

close() Closes the current window

confirm() Displays a dialog box with a message and an OK and a Cancel button

focus() Sets focus to the current window

getComputedStyle() Gets the current computed CSS styles applied to an element

getSelection() Returns a Selection object representing the range of text selected by the
user

matchMedia() Returns a MediaQueryList object representing the specified CSS media


query string

Web Programming Page


WEB PROGRAMMING

moveBy() Moves a window relative to its current position

moveTo() Moves a window to the specified position

open() Opens a new browser window

print() Prints the content of the current window

prompt() Displays a dialog box that prompts the visitor for input

requestAnimationFrame() Requests the browser to call a function to update an animation before the
next repaint

resizeBy() Resizes the window by the specified pixels

resizeTo() Resizes the window to the specified width and height

scroll() Deprecated. This method has been replaced by the scrollTo() method.

Web Programming Page


WEB PROGRAMMING

scrollBy() Scrolls the document by the specified number of pixels

scrollTo() Scrolls the document to the specified coordinates

setInterval() Calls a function or evaluates an expression at specified intervals (in


milliseconds)

setTimeout() Calls a function or evaluates an expression after a specified number of


milliseconds

stop() Stops the window from loading

The Window object is used to open a window in a browser to display the Web page.

The following figure shows the Window object in the hierarchy of Browsers objects.

The window object has the following three features in JavaScript:

 collection
 properties
 methods

JavaScript Window Object Collection

The window object collection is a set of all the window objects available in an HTML document.

JavaScript Window Object Properties


Web Programming Page
WEB PROGRAMMING

All data and information about any browser is attached to the window object as properties and the frames property
in the window object returns all the frames in the current window. The table given below describes properties of
the window object in JavaScript.

Property Description

closed returns a boolean value that specifies whether a window has been closed or not

defaultStatus specifies the default message that has to be appeared in the statusbar of a window

document specifies a document object in the window

frames specifies an array of all the frames in the current window

history specifies a history object for the window

innerHeight specifies the inner height of a window's content area

innerWidth specifies the inner width of a window's content area

length specifies the number of frames contained in a window

location specifies a location object for the window

name specifies the name of a window

outerHeight specifies the height of the outside boundary of a window in pixels

outerWidth specifies the width of the outside boundary of a window in pixels

parent returns the parent frame or window of the current window

screenLeft specifies the x coordinate of the window relative to a user's monitor screen

screenTop specifies the y coordinate of the window relative to a user's monitor screen

screenX specifies the x coordinate of the window relative to a user's monitor screen

screenY specifies the y coordinate of the window relative to a user's monitor screen

self returns the reference of the current active frame or window

specifies the message that is displayed in the status bar of a window, when an activity is performed o
status
window n the

top specifies the reference of the topmost browser window

Web Programming Page


WEB PROGRAMMING

JavaScript Window Object Properties Example

Here is an example demonstrates window object properties in JavaScript:

<!DOCTYPE HTML>
<html>
<head>
<title>JavaScript Window Object Properties</title>
</head>
<body>

<h3>JavaScript Window Object Properties Example</h3>


<iframe src="http://codescracker.com/java"></iframe>
<iframe src="http://codescracker.com/c"></iframe>
<iframe src="http://codescracker.com/cpp"></iframe>
<script type="text/javascript">
for(var i=0; i<frames.length; i++)
{
frames[i].location = http://codescracker.com"
}
</script>

</body>
</html>

Here is the sample output produced by the above JavaScript Window Object Properties example code:

JavaScript Window Object Methods

The methods of the window object enable you to perform various tasks such as open a url in a new window or to
close a window. The following table describes the methods of the Window object in JavaScript.

Method Description

alert() displays an alert box with a message and an OK button

blur() removes the focus from the current window

clearInterval() clears the timer, which is set by using the setInterval() method

clearTimeout() clears the timer, which is set by using the setTimeout() method

Web Programming Page


WEB PROGRAMMING

close() closes the current window

confirm() displays a dialog box with a message and two buttons, OK and Cancel

createPopup() creates a pop-up window

focus() sets focus on the current window

moveBy() moves a window relative to its current position

moveTo() moves a window to an specified position

open() opens a new browser window

print() sends a print command to print the content of the current window

prompt() prompts for input

resizeBy() resizes a window with the specified pixels

resizeTo() resizes a window with the specified width and height

scrollBy() scrolls the content of a window by the specified number of pixels

scrollTo() scrolls the content of a window up to the specified coordinates

setInterval() evaluates an expression at specified time intervals in milliseconds

setTimeout() evaluates an expression after a specified number of milliseconds

JavaScript Window Object Methods Example

Here is an example uses some window object methods in JavaScript:

<!DOCTYPE HTML>
<html>
<head>
<title>JavaScript Window Object Methods</title>
<script type="text/javascript">
var mywin;
function openMidWin(url)
{
var wid = 500;
var hei = 200;
var winFeat = "width = " + wid + ", height = " + hei + " , status, resizable";
myWin = window.open(url, "subWind", winFeat);
}
function disp_alert()
Web Programming Page
WEB PROGRAMMING

{
alert("Hi, This is an alert box.");
}
function resize_win()
{
window.resizeBy(-100, -100)
}
function close_win()
{
if(window.confirm("Do you really want to close the browser ?"))
window.close();
}
</script>
</head>
<body>

<h3>JavaScript Window Object Methods Example</h3>


<input type="button" value="Open New Window" onclick="openMidWin('WindowObjectMethod.htm')" />
<input type="button" value="Alert" onclick="disp_alert()" />
<input type="button" value="Resize Window" onclick="resize_win()" />
<input type="button" value="Close Window" onclick="close_win()" />

</body>
</html>

Here are some sample output produced by the above Window Object Methods in JavaScript example code. This is
initial output:

This is the output, after clicking on Open New Window button:

This is the output, after clicking on Alert button:

This is the output produced after clicking on Resize Window button:

Web Programming Page


WEB PROGRAMMING

This is the output produced after clicking on Close Window button:

Web Programming Page

You might also like