MODULE 1 (3)
MODULE 1 (3)
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.
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.
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
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:
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.
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
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 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
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>
<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.
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">
Type the above program in notepad and save with some file nameeg:sample.html
Open the file with browser and the webpage looks likethis
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
<!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>
<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.
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
<form>
User name:<br>
<input type="text"
name="username"><br>
User password:<br>
<input type="password"
name="psw">
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>
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.
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
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.
<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>
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>
h1 { color:blue; }
p { color:red; }
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>
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;
Creating a java script: - html script tag is used to script code inside the html page.
<script> </script>
1) Language attribute:-
<script language=―JavaScript‖>
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.
Location of script or placing the script: - Script code can be placed in both head & body
section of html page.
<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
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.
<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.
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.
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
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( )">
</script>
</BODY> O/P: - to call function:
addition is :90
</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.
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
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!" );
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.
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;
}
</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;
}
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
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);
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
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()
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
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
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
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
2 length
Returns the length of the string.
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()
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
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
1 anchor()
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.
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
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
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()
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()
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.
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.
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
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.
1 Date()
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.
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()
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()
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.
1 Date.parse( )
2 Date.UTC( )
Returns the millisecond representation of the specified UTC date and
time.
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\
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()
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()
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.
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
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
Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<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:
Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
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.
\b: Backspace.
\t: Tab
\’ : Single Quote
Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
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>
document.getElementById("no1").innerHTML = str;
</script>
<script>
document.getElementById("no2").innerHTML = strobj;
</script>
<script>
document.getElementById("no3").innerHTML = str.length;
Web Programming Page
WEB PROGRAMMING
</script>
<script>
</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).
Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
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>
document.getElementById("no1").innerHTML = fruits;
</script>
<script>
document.getElementById("no2").innerHTML = fruits[0];
</script>
<script>
</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.
Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
document.write('<br>');
document.write('<br>');
document.write('<br>');
document.write('<br>');
document.write('<br>');
document.write('<br>');
document.write('<br>');
Web Programming Page
WEB PROGRAMMING
</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 :
Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
// Create an object:
document.getElementById("no1").innerHTML =
</script>
</body>
</html>
JavaScript has the following types of operators. This section describes the operators and contains information
Assignment operators
Comparison operators
Arithmetic operators
Bitwise operators
Logical operators
String operators
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:
Copy to Clipboard
A unary operator requires a single operand, either before or after the operator:
operator operand
Copy to Clipboard
or
operand operator
Copy to Clipboard
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
There are also compound assignment operators that are shorthand for the operations listed in the following table:
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
obj.x = 3;
console.log(obj.x); // Prints 3.
console.log(obj); // Prints { x: 3 }.
obj[key] = 5;
console.log(obj[key]); // Prints 5.
console.log(obj); // Prints { x: 3, y: 5 }.
Copy to Clipboard
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.
// without destructuring
// with destructuring
Copy to Clipboard
In general, assignments are used within a variable declaration (i.e., with const, let, or var) or as standalone
statements.
let x = f();
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;
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
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’
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
y = x = g()
y = [ f(), x = g() ]
x[f()] = g()
Copy to Clipboard
Evaluation example 1
1. The y on this assignment’s left-hand side evaluates into a reference to the variable named y.
Web Programming Page
WEB PROGRAMMING
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. The assignment expression x = f() has now finished evaluating; its result is the new value of x,
which is 2.
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
1. The y on this assignment’s left-hand evaluates into a reference to the variable named y.
3. The function call f() prints "F!" to the console and then evaluates to the number 2.
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.
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()).
6. The inner array literal [ f(), x = g() ] has now finished evaluating; its result is an array with
two values: [ 2, 3 ].
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
Evaluation example 2
x[f()] = g() also evaluates from left to right. (This example assumes that x is already assigned to some object. For
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
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!".
Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this
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
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
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
var var1 = 3;
var var2 = 4;
Copy to Clipboard
Comparison operators
Operator Description
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.
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
Copy to Clipboard
Web Programming Page
WEB PROGRAMMING
In addition to the standard arithmetic operations (+, -, *, /), JavaScript provides the arithmetic operators listed in
Arithmetic operators
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
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.
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.]
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.
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
Before: 1110 0110 1111 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,
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:
~15 -16 ~ 0000 0000 ... 0000 1111 = 1111 1111 ... 1111 0000
~9 -10 ~ 0000 0000 ... 0000 1001 = 1111 1111 ... 1111 0110
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
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
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.
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.
left.
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
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
Logical operators
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.
false
Web Programming
Copy to Clipboard Page
WEB PROGRAMMING
true
returns Cat
Copy to Clipboard
Copy to Clipboard
Short-circuit evaluation
WEB PROGRAMMING
As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the
following rules:
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,
Copy to Clipboard
For example,
Copy to Clipboard
The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of
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
For example,
Copy to Clipboard
This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the
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
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]
// ^
Copy to Clipboard
Unary operators
delete
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
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.
Copy to Clipboard
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
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.
var size = 1;
Copy to Clipboard
Copy to Clipboard
For the keywords true and null, the typeof operator returns the following results:
Copy to Clipboard
For a number or string, the typeof operator returns the following results:
Copy to Clipboard
For property values, the typeof operator returns the type of value the property contains:
Copy to Clipboard
For methods and functions, the typeof operator returns results as follows:
Copy to Clipboard
Copy to Clipboard
void
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
// Arrays
6 in trees; // returns
false
'bay' in trees; // returns false (you must specify the index number,
// built-in objects
// Custom objects
Copy to Clipboard
instanceof
The instanceof operator returns true if the specified object is of the specified object type. The syntax is:
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
// statements to execute
Copy to Clipboard
Operator precedence
The precedence of operators determines the order they are applied when evaluating an expression. You can
The following table describes the precedence of operators, from highest to lowest.
member . []
multiply/divide */%
addition/subtraction +-
bitwise-and &
bitwise-xor ^
bitwise-or |
logical-and &&
logical-or ||
conditional ?:
comma ,
A more detailed version of this table, complete with links to additional details about each operator, may be found
in JavaScript Reference.
Expressions
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
The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven
The code 3 + 4 is an example of the second expression type. This expression uses the + operator to add three and
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.)
Primary expressions
this
Use the this keyword to refer to the current object. In general, this refers to the calling object in a method.
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:
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,
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
a + (b * c) // 7
(a + b) * c // 9
// which is equivalent to
a * c + b * c // 9
Copy to Clipboard
Left-hand-side expressions
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
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
super.functionOnParent([arguments]);
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.
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
let
Declares a block scope local variable, optionally initializing it to a value.
const
Declares a read-only named constant.
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
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.
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)
document Returns the Document object for the window (See Document object)
frameElement Returns the <iframe> element in which the current window is inserted
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
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)
navigator Returns the Navigator object for the window (See Navigator object)
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
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
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
Method Description
confirm() Displays a dialog box with a message and an OK and a Cancel button
getSelection() Returns a Selection object representing the range of text selected by the
user
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
scroll() Deprecated. This method has been replaced by the scrollTo() method.
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.
collection
properties
methods
The window object collection is a set of all the window objects available in an HTML document.
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
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
specifies the message that is displayed in the status bar of a window, when an activity is performed o
status
window n the
<!DOCTYPE HTML>
<html>
<head>
<title>JavaScript Window Object Properties</title>
</head>
<body>
</body>
</html>
Here is the sample output produced by the above JavaScript Window Object Properties example code:
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
clearInterval() clears the timer, which is set by using the setInterval() method
clearTimeout() clears the timer, which is set by using the setTimeout() method
confirm() displays a dialog box with a message and two buttons, OK and Cancel
print() sends a print command to print the content of the current window
<!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>
</body>
</html>
Here are some sample output produced by the above Window Object Methods in JavaScript example code. This is
initial output: