0% found this document useful (0 votes)
4K views115 pages

HTML and Java Script

Uploaded by

srlohitkriishnaa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
4K views115 pages

HTML and Java Script

Uploaded by

srlohitkriishnaa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 115

PAVAI ARTS AND SCIENCE COLLEGE FOR WOMEN, RASIPURAM.

DEPARTMENT OF COMPUTER SCIENCE

UNIT-I - introduction: html, javascript, and html/javascript documents – accessing html


documents. Html document basics: documents, elements, attributes, and values – html syntax
and style -Using the script element - creating and organizing a web site - selecting and using
colors - using Cascading style sheets.

INTRODUCTION:

HTML is the standard markup language for creating Web pages.

 HTML stands for Hyper Text Markup Language


 HTML describes the structure of Web pages using markup
 HTML elements are the building blocks of HTML pages
 HTML elements are represented by tags
 HTML tags label pieces of content such as "heading", "paragraph", "table", and
so on
 Browsers do not display the HTML tags, but use them to render the content of
the page

A Simple HTML Document


Example
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>
</html>
Example Explained
 The <!DOCTYPE html> declaration defines this document to be HTML
 The <html> element is the root element of an HTML page
 The <head> element contains meta information about the document
 The <title> element specifies a title for the document
 The <body> element contains the visible page content
 The <h1> element defines a large heading
 The <p> element defines a paragraph

HTML Tags

HTML tags are element names surrounded by angle brackets:

<tagname>content goes here...</tagname>

 HTML tags normally come in pairs like <p> and </p>


 The first tag in a pair is the start tag, the second tag is the end tag
 The end tag is written like the start tag, but with a forward slash inserted before
the tag name

ACCESSING HTML DOCUMENTS:

Web Browsers

The purpose of a web browser (Chrome, IE, Firefox, Safari) is to read HTML documents
and display them.

The browser does not display the HTML tags, but uses them to determine how to
display the document:

HTML Page Structure

Below is a visualization of an HTML page structure:


<html>
<head>
<title>Page title</title>

</head>

<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

</body>

</html>
Note: Only the content inside the <body> section (the white area above) is displayed in
a browser.

The <!DOCTYPE> Declaration

The <!DOCTYPE> declaration represents the document type, and helps browsers to
display web pages correctly.

It must only appear once, at the top of the page (before any HTML tags).
The <!DOCTYPE> declaration is not case sensitive.
The <!DOCTYPE> declaration for HTML5 is:

<!DOCTYPE html>

JAVASCRIPT

INTRODUCTION:

JavaScript is a very powerful client-side scripting language. JavaScript is used


mainly for enhancing the interaction of a user with the webpage. In other words, you
can make your webpage more lively and interactive, with the help of JavaScript.
JavaScript is also being used widely in game development and mobile application
development.
History:

JavaScript was developed by Brendan Eich in 1995, which appeared in Netscape, a


popular browser of that time. The language was initially called LiveScript and was later
renamed JavaScript. There are many programmers who think that JavaScript and Java
are the same. In fact, JavaScript and Java are very much unrelated. Java is a very
complex programming language whereas JavaScript is only a scripting language. The
syntax of JavaScript is mostly influenced by the programming language C.

ACCESSING DOCUMENT:

Being a scripting language, JavaScript cannot run on its own. In fact, the browser is
responsible for running JavaScript code. When a user requests an HTML page with
JavaScript in it, the script is sent to the browser and it is up to the browser to execute
it. The main advantage of JavaScript is that all modern web browsers support
JavaScript. So, you do not have to worry about whether your site visitor uses Internet
Explorer, Google Chrome, Firefox or any other browser. JavaScript will be supported.
Also, JavaScript runs on any operating system including Windows, linux or Mac.
Thus, JavaScript overcomes the main disadvantages of VBScript (Now deprecated)
which is limited to just IE and Windows.

Example:

<html>

<head>

<title>My First JavaScript code!!!</title>

<script type="text/javascript">
alert("Hello World!");
</script>

</head>

<body>
</body>

</html>

HTML BASIC:

HTML Documents

All HTML documents must start with a document type declaration: <!DOCTYPE html>.
The HTML document itself begins with <html> and ends with </html>.
The visible part of the HTML document is between <body> and </body>.

Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
HTML Headings

HTML headings are defined with the <h1> to <h6> tags.

<h1> defines the most important heading. <h6> defines the least important heading:

Example
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
HTML Paragraphs

HTML paragraphs are defined with the <p> tag:

Example
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

HTML Links
HTML links are defined with the <a> tag:

Example
<a href="https://www.w3schools.com">This is a link</a>

The link's destination is specified in the href attribute.

Attributes are used to provide additional information about HTML elements.

HTML Images

HTML images are defined with the <img> tag.

The source file (src), alternative text (alt), width, and height are provided as attributes:

Example
<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">
HTML Buttons

HTML buttons are defined with the <button> tag:

Example
<button>Click me</button>
HTML Lists

HTML lists are defined with the <ul> (unordered/bullet list) or


the <ol> (ordered/numbered list) tag, followed by <li> tags (list items):

Example
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
HTML Elements

An HTML element usually consists of a start tag and end tag, with the content inserted
in between:

<tagname>Content goes here...</tagname>


The HTML element is everything from the start tag to the end tag:

<p>My first paragraph</p>

HTML elements with no content are called empty elements. Empty elements do not
have an end tag, such as the <br> element (which indicates a line break).

Nested HTML Elements

HTML elements can be nested (elements can contain


elements). All HTML documents consist of nested HTML
elements.
This example contains four HTML elements:
Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>
</html>

Example Explained

The <html> element defines the whole document.


It has a start tag <html> and an end tag </html>.
The element content is another HTML element (the <body> element).

<html>
<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>
</html>
The <body> element defines the document body.
It has a start tag <body> and an end tag
</body>.
The element content is two other HTML elements (<h1> and <p>).

<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>

The <h1> element defines a heading.

It has a start tag <h1> and an end tag </h1>.

The element content is: My First Heading.

<h1>My First Heading</h1>

The <p> element defines a paragraph.

It has a start tag <p> and an end tag </p>.


The element content is: My first paragraph.
<p>My first paragraph</p>
Do Not Forget the End Tag
Some HTML elements will display correctly, even if you forget the end tag:

Example
<html>
<body>

<p>This is a paragraph
<p>This is a paragraph

</body>
</html>
The example above works in all browsers, because the closing tag is considered
optional.

Never rely on this. It might produce unexpected results and/or errors if you forget
the end tag.

Empty HTML Elements

HTML elements with no content are called empty elements.

<br> is an empty element without a closing tag (the <br> tag defines a line break). Empty elements can
HTML does not require empty elements to be closed. But if you want stricter validation, or if you need to m

Use Lowercase Tags


HTML tags are not case sensitive: <P> means the same as <p>.
The HTML5 standard does not require lowercase tags, but W3C recommends lowercase
in HTML, and demandslowercase for stricter document types like XHTML.

HTML Attributes

 All HTML elements can have attributes


 Attributes provide additional information about an element
 Attributes are always specified in the start tag
 Attributes usually come in name/value pairs like: name="value"
The href Attribute
HTML links are defined with the <a> tag. The link address is specified in
the href attribute:
Example
<a href="https://www.w3schools.com">This is a link</a>
The src Attribute

HTML images are defined with the <img> tag.

The filename of the image source is specified in the src attribute:

Example
<img src="img_girl.jpg">
The width and height Attributes

Images in HTML have a set of size attributes, which specifies the width and height of
the image:

Example
<img src="img_girl.jpg" width="500" height="600">

The image size is specified in pixels: width="500" means 500 pixels wide.

The alt Attribute

The alt attribute specifies an alternative text to be used, when an image cannot be displayed.

The value of the attribute can be read by screen readers. This way, someone "listening"
to the webpage, e.g. a vision impaired person, can "hear" the element.

Example
<img src="img_girl.jpg" alt="Girl with a jacket">

The alt attribute is also useful if the image does not exist.

Example

See what happens if we try to display an image that does not exist:

<img src="img_typo.jpg" alt="Girl with a jacket">

The style Attribute

The style attribute is used to specify the styling of an element, like color, font, size etc.

Example
<p style="color:red">I am a
paragraph</p> The lang Attribute
The language of the document can be declared in the <html> tag.
The language is declared with the lang attribute.
Declaring a language is important for accessibility applications (screen readers) and
search engines:

<!DOCTYPE html>
<html lang="en-US">
<body>
...
</body>
</html>

The first two letters specify the language (en). If there is a dialect, use two more letters
(US).

The title Attribute

Here, a title attribute is added to the <p> element. The value of the title attribute will be
displayed as a tooltip when you mouse over the paragraph:

Example
<p title="I'm a
tooltip"> This is a
paragraph.
</p>

Use Lowercase Attributes

The HTML standard does not require lowercase attribute names.

The title attribute can be written with uppercase or lowercase like title or TITLE.

W3C recommends lowercase in HTML, and demands lowercase for stricter document
types like XHTML.

Quote Attribute Values

The HTML standard does not require quotes around attribute values.
The href attribute, demonstrated above, can be written without quotes:
Bad
<a href=https://www.w3schools.com>

Good
<a href="https://www.w3schools.com">
W3C recommends quotes in HTML, and demands quotes for stricter document types
like XHTML.

Sometimes it is necessary to use quotes. This example will not display the title attribute
correctly, because it contains a space:

Example
<p title=About W3Schools>
Single or Double Quotes?

Double quotes around attribute values are the most common in HTML, but single quotes can also be us

In some situations, when the attribute value itself contains double quotes, it is necessary to use single q

<p title='John "ShotGun" Nelson'>

Or vice versa:

<p title="John 'ShotGun' Nelson">


The HTML Style Attribute
Setting the style of an HTML element, can be done with the style attribute.
The HTML style attribute has the following syntax:
<tagname style="property:value;">

The property is a CSS property. The value is a CSS value.


HTML Background Color
The background-color property defines the background color for an HTML element.
This example sets the background color for a page to powderblue:
Example
<body style="background-color:powderblue;">

<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>

HTML Text Color

The color property defines the text color for an HTML element:

Example
<h1 style="color:blue;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>

HTML Fonts

The font-family property defines the font to be used for an HTML element:

Example
<h1 style="font-family:verdana;">This is a heading</h1>
<p style="font-family:courier;">This is a paragraph.</p>
HTML Text Size

The font-size property defines the text size for an HTML element:

Example
<h1 style="font-size:300%;">This is a heading</h1>
<p style="font-size:160%;">This is a paragraph.</p>

HTML Text Alignment

The text-align property defines the horizontal text alignment for an HTML element:

Example
<h1 style="text-align:center;">Centered Heading</h1>
<p style="text-align:center;">Centered paragraph.</p>

 Use font-size for text sizes


 Use text-align for text alignment

USING SCRIPT ELEMENT:

The HTML <script> Tag

The <script> tag is used to define a client-side script (JavaScript).


The <script> element either contains scripting statements, or it points to an external
script file through the srcattribute.

Common uses for JavaScript are image manipulation, form validation, and dynamic
changes of content.

To select an HTML element, JavaScript very often uses the document.getElementById() method.

This JavaScript example writes "Hello JavaScript!" into an HTML element with id="demo":

Example
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>

A Taste of JavaScript

Here are some examples of what JavaScript can do:

JavaScript can change HTML content


document.getElementById("demo").innerHTML = "Hello JavaScript!";
JavaScript can change HTML styles
document.getElementById("demo").style.fontSize = "25px";
document.getElementById("demo").style.color = "red";
document.getElementById("demo").style.backgroundColor = "yellow";
JavaScript can change HTML attributes
document.getElementById("image").src = "picture.gif";
The HTML <noscript> Tag

The <noscript> tag is used to provide an alternate content for users that have disabled
scripts in their browser or have a browser that doesn't support client-side scripts:
Example
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
<noscript>Sorry, your browser does not support JavaScript!</noscript>

CREATING AND ORGANIZING WEBSITE:

Doctype, Meta Tags, and CSS


The doctype should define the page as an HTML document:

<!DOCTYPE html>

A meta tag should define the character set to be UTF-8:

<meta charset="UTF-8">

A viewport meta tag should make the web site work on all devices and screen resolutions:

<meta name="viewport" content="width=device-width, initial-scale=1">

W3.CSS should take care of all our styling needs and all device and browser differences:

<link rel="stylesheet" href="https://www.w3schools.com/w3css/3/w3.css">


Our first empty web page will look much like this:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/3/w3.css">
<body>
<!-- Content will go here -->
</body>
</html>

CREATING PAGE CONTENT

Inside the <body> element of our web site we will use our "Layout Picture" and create:

 A navigation bar
 A slide show
 A header
 Some sections and articles
 A footer

SEMANTIC ELEMENTS

HTML introduced several new semantic elements. Semantic elements are important to
use because they define the structure of web pages and helps screen readers and
search engines to read the page correctly.

These are some of the most common semantic HTML elements:

The <section> element can be used to define a part of a website with related content. The <article> elem
The <header> element can be used to define a header (in a document, a section, or an article).

The <footer> element can be used to define a footer (in a document, a section, or an
article).

The <nav> element can be used to define a container of navigation links.


In this tutorial we will use semantic elements.
However, it is up to you if you want to use <div> elements instead.

The Navigation Bar

On our "Layout Draft" we have a "Navigation bar".

<!-- Navigation -->


<nav class="w3-bar w3-black">
<a href="#home" class="w3-button w3-bar-item">Home</a>
<a href="#band" class="w3-button w3-bar-item">Band</a>
<a href="#tour" class="w3-button w3-bar-item">Tour</a>
<a href="#contact" class="w3-button w3-bar-item">Contact</a>
</nav>

We can use a <nav> or <div> element as a container for the navigation links.
The w3-bar class is a container for navigation links.
The w3-black class defines the color of the navigation bar.

The w3-bar-item and w3-button class styles the navigation links inside the bar.
Slide Show

On the "Layout Draft" we have a "Slide show".

For the slide show we can use a <section> or <div> element as a picture container:

<!-- Slide Show -->


<section>
<img class="mySlides" src="img_la.jpg" style="width:100%">
<img class="mySlides" src="img_ny.jpg" style="width:100%">
<img class="mySlides" src="img_chicago.jpg" style="width:100%">
</section>

We need to add a little JavaScript to change the images every 3 seconds:

// Automatic Slideshow - change image every 3 seconds


var myIndex = 0;
carousel();

function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex =
1} x[myIndex-1].style.display =
"block"; setTimeout(carousel, 3000);
}
SECTIONS AND ARTICLES

Looking at the "Layout Draft" we can see that the next step is to create articles.
First we will create a <section> or <div> element containing band information:
<section class="w3-container w3-center" style="max-width:600px">
<h2 class="w3-wide">THE BAND</h2>
<p class="w3-opacity"><i>We love music</i></p>
</section>
The w3-container class takes care of standard padding.
The w3-center class centers the content.
The w3-wide class provides a wider heading.
The w3-opacity class provides text transparency.
The max-width style sets a maximum with of the band description
section. Then we will add a paragraph describing the band:
<section class="w3-container w3-content w3-center" style="max-width:600px">
<p class="w3-justify">
We have created a fictional band website. Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua.</p>
</section>

The w3-justify class justifies the text's right and left margins.

Then create a <section> or <div> with an <article> or <div> about each band-member:

<section class="w3-row-padding w3-center w3-light-grey">


<article class="w3-third">
<p>John</p>
<img src="img_bandmember.jpg" alt="Random Name" style="width:100%">
</article>
<article class="w3-third">
<p>Paul</p>
<img src="img_bandmember.jpg" alt="Random Name" style="width:100%">
</article>
<article class="w3-third">
<p>Ringo</p>
<img src="img_bandmember.jpg" alt="Random Name" style="width:100%">
</article>
</section>

Footer

Finally we will use a <footer> or <div> to create footer:


<!-- Footer -->
<footer class="w3-container w3-padding-64 w3-center w3-black w3-xlarge">
<a href="#"><i class="fa fa-facebook-official"></i></a>
<a href="#"><i class="fa fa-pinterest-p"></i></a>
<a href="#"><i class="fa fa-twitter"></i></a>
<a href="#"><i class="fa fa-flickr"></i></a>
<a href="#"><i class="fa fa-linkedin"></i></a>
<p class="w3-medium">
Powered
by <a href="https://www.w3schools.com/w3css/default.asp" target="_blank">w3.css
</a>
</p>
</footer>

The fa fa classes are Font Awesome Icon classes.

To use these classes you must link to a Font Awesome library:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-


awesome/4.6.3/css/font-awesome.min.css">
Selecting and color using css.

SELECTORS USING CSS

CSS Syntax

A CSS rule-set consists of a selector and a declaration block:

The selector points to the HTML element you want to style.

The declaration block contains one or more declarations separated by semicolons.


Each declaration includes a CSS property name and a value, separated by a colon.
A CSS declaration always ends with a semicolon, and declaration blocks are
surrounded by curly braces.
In the following example all <p> elements will be center-aligned, with a red text color:

Example

p{
color: red;
text-align: center;
}

CSS Selectors

CSS selectors are used to "find" (or select) HTML elements based on their element name,
id, class, attribute, and more.

The element Selector

The element selector selects elements based on the element name.

You can select all <p> elements on a page like this (in this case, all <p> elements will
be center-aligned, with a red text color):

Example

p{
text-align: center;
color: red;
}

The id Selector

The id selector uses the id attribute of an HTML element to select a specific element.

The id of an element should be unique within a page, so the id selector is used to select
one unique element!

To select an element with a specific id, write a hash (#) character, followed by the id of
the element.

The style rule below will be applied to the HTML element with id="para1":

Example

#para1 {
text-align: center;
color: red;
}
The class Selector

The class selector selects elements with a specific class attribute.

To select elements with a specific class, write a period (.) character, followed by the
name of the class.

In the example below, all HTML elements with class="center" will be red and center-
aligned:

Example

.center {
text-align: center;
color: red;
}

You can also specify that only specific HTML elements should be affected by a class.
In the example below, only <p> elements with class="center" will be center-aligned:
Example

p.center {
text-align: center;
color: red;
}

HTML elements can also refer to more than one class.

In the example below, the <p> element will be styled according to class="center" and to
class="large":

Example

<p class="center large">This paragraph refers to two classes.</p>

Grouping Selectors
If you have elements with the same style definitions, like this:
h1 {
text-align: center;
color: red;
}
p{
text-align: center; color: red;
}
It will be better to group the selectors, to minimize the code. To group
selectors, separate each selector with a comma.

h2 {
text-align: center;
color: red;
}

In the example below we have grouped the selectors from the code above:

Example

h1, h2, p {
text-align: center;
color: red;
}

SELECTING COLORS USING CSS

Colors are specified using predefined color names, or RGB, HEX, HSL, RGBA, HSLA
values.

Color Names

In HTML, a color can be specified by using a color name:

Background Color

You can set the background color for HTML elements:

Example

<h1 style="background-color:DodgerBlue;">Hello World</h1>


<p style="background-color:Tomato;">Lorem ipsum...</p>

Text Color
You can set the color of text:

Example

<h1 style="color:Tomato;">Hello World</h1>


<p style="color:DodgerBlue;">Lorem ipsum...</p>
<p style="color:MediumSeaGreen;">Ut wisi enim...</p>
Border Color

You can set the color of borders:

Example

<h1 style="border:2px solid Tomato;">Hello World</h1>


<h1 style="border:2px solid DodgerBlue;">Hello World</h1>
<h1 style="border:2px solid Violet;">Hello World</h1>

Color Values

In HTML, colors can also be specified using RGB values, HEX values, HSL values,
RGBA values, and HSLA values:

Same as color name "Tomato":

Example

<h1 style="background-color:rgb(255, 99, 71);">...</h1>


<h1 style="background-color:#ff6347;">...</h1>
<h1 style="background-color:hsl(9, 100%, 64%);">...</h1>

<h1 style="background-color:rgba(255, 99, 71, 0.5);">...</h1>


<h1 style="background-color:hsla(9, 100%, 64%, 0.5);">...</h1>

HINTS
 Use the style attribute for styling HTML elements
 Use background-color for background color
 Use color for text colors
 Use font-family for text fonts
 All HTML elements can have attributes
 The title attribute provides additional "tool-tip" information
 The href attribute provides address information for links
 The width and height attributes provide size information for images
 The alt attribute provides text for screen readers
 we always use lowercase attribute names
 we always quote attribute values with double quotes
 JavaScript is a client-side scripting language developed by Brendan Eich.
 JavaScript can be run on any operating systems and almost all web browsers.
 You need a text editor to write JavaScript code and a browser to display
your web page.
UNIT-II - HTML Tables, Forms, and Lists: The table Element: Basic Table Formatting -
Merging Cells across Rows and Columns. The form Element - Creating Pull-Down Lists
- Combining Tables and Forms - E-Mailing the Contents of Forms - The List Elements.

HTML Tables
Definition
An HTML table is defined with the <table> tag. Each table row is defined with
the <tr> tag. A table header is defined with the <th> tag. By default, table headings are
bold and centered. A table data/cell is defined with the <td> tag.
Example:

<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr> <tr <td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>

Note: The <td> elements are the data containers of the table.
They can contain all sorts of HTML elements; text, images, lists, other tables, etc.

HTML Table - Adding a Border


If you do not specify a border for the table, it will be displayed without
borders. A border is set using the CSS border property:
Example
table, th, td {
border: 1px solid black;
}

Remember to define borders for both the table and the table cells.

HTML Table - Collapsed Borders

If you want the borders to collapse into one border, add the CSS border-
collapse property:
Example
table, th, td
{
border: 1px solid black;
border-collapse: collapse;
}
HTML Table - Adding Cell Padding

Cell padding specifies the space between the cell content and its borders.

If you do not specify a padding, the table cells will be displayed without padding.
To set the padding, use the CSS padding property:
Example
th, td {
padding: 15px;
}
HTML Table - Left-align Headings

By default, table headings are bold and centered.

To left-align the table headings, use the CSS text-align


property: Example
th {
text-align: left;
}
HTML Table - Adding Border Spacing

Border spacing specifies the space between the cells.

To set the border spacing for a table, use the CSS border-spacing property:
Example
table {
border-spacing: 5px;
}

Note: If the table has collapsed borders, border-spacing has no effect.

HTML Table - Cells that Span Many Columns


To make a cell span more than one column, use the colspan attribute:
Example
<table style="width:100%">
<tr>
<th>Name</th>
<th colspan="2">Telephone</th>
</tr>
<tr>
<td>Bill Gates</td>
<td>55577854</td>
<td>55577855</td>
</tr>
</table>
HTML Table - Cells that Span Many Rows
To make a cell span more than one row, use the rowspan attribute:
Example
<table style="width:100%">
<tr>
<th>Name:</th>
<td>Bill Gates</td>
</tr>
<tr>
<th rowspan="2">Telephone:</th>
<td>55577854</td>
</tr>
<tr>
<td>55577855</td>
</tr>
</table>
HTML Table - Adding a Caption
To add a caption to a table, use the <caption>
tag: Example
<table style="width:100%">
<caption>Monthly savings</caption>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$50</td>
</tr>
</table>

Note: The <caption> tag must be inserted immediately after the <table> tag.

A Special Style for One Table


To define a special style for a special table, add an id attribute to the table:
Example
<table id="t01">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Now you can define a special style for this table:
table#t01 {
width: 100%;
background-color: #f1f1c1;
}
And add more styles:
table#t01 tr:nth-child(even)
{ background-color: #eee;
}
table#t01 tr:nth-child(odd) {
background-color: #fff;
}
table#t01 th {
color: white;
background-color: black;
}
HTML Lists

HTML List Example


An Unordered List:
 Item
 Item
 Item
 Item

An Ordered List:

1. First item
2. Second item
3. Third item
4. Fourth item

Unordered HTML List

An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
The list items will be marked with bullets (small black circles) by default:
Example
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Unordered HTML List - Choose List Item Marker
The CSS list-style-type property is used to define the style of the list item marker:
Example - Disc
<ul style="list-style-type:disc">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Example - Circle
<ul style="list-style-type:circle">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Example - Square
<ul style="list-style-type:square">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Example - None
<ul style="list-style-type:none">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Ordered HTML List

An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
The list items will be marked with numbers by default:
Example
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Ordered HTML List - The Type Attribute
The type attribute of the <ol> tag, defines the type of the list item marker:
Numbers:
<ol type="1">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Uppercase Letters:
<ol type="A">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Lowercase Letters:
<ol type="a">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Uppercase Roman Numbers:
<ol type="I">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Lowercase Roman Numbers:
<ol type="i">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
HTML Description Lists

HTML also supports description lists.

A description list is a list of terms, with a description of each term.


The <dl> tag defines the description list, the <dt> tag defines the term (name), and
the <dd> tag describes each term:

Example
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
Nested HTML Lists

List can be nested (lists inside lists):

Example
<ul>
<li>Coffee</li>
<li>Tea
<ul>
<li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ul>

Note: List items can contain new list, and other HTML elements, like images and links,
etc.

Control List Counting

By default, an ordered list will start counting from 1. If you want to start counting
from a specified number, you can use the start attribute:

Example
<ol start="50">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Horizontal List with CSS

HTML lists can be styled in many different ways with CSS.


One popular way is to style a list horizontally, to create a navigation menu:

Example
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333333;
}

li {
float: left;
}

li a {
display: block;
color: white;
text-align: center;
padding: 16px;
text-decoration: none;
}

li a:hover {
background-color: #111111;
}
</style>
</head>
<body>

<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</body>
</html>
HTML FORMS
HTML Form Example
First name:
Mickey

Last name:
Mouse

Submit

The <form> Element

The HTML <form> element defines a form that is used to collect user input:

<form>
.
form elements
.
</form>

An HTML form contains form elements.

Form elements are different types of input elements, like text fields, checkboxes,
radio buttons, submit buttons, and more.

The <input> Element

The <input> element is the most important form element.

The <input> element can be displayed in several ways, depending on the type
attribute. Here are some examples:
Text Input
<input type="text"> defines a one-line input field for text input:
Example
<form>
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname">
</form>

This is how it will look like in a browser:


First name:

Last name:

Note: The form itself is not visible. Also note that the default width of a text field is 20
characters.

Radio Button Input

<input type="radio"> defines a radio button.


Radio buttons let a user select ONE of a limited number of
choices: Example
<form>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>

This is how the HTML code above will be displayed in a browser:

Male
Female
Other
The Submit Button

<input type="submit"> defines a button for submitting the form data to a form-
handler.

The form-handler is typically a server page with a script for processing input data.
The form-handler is specified in the form's action attribute:
Example
<form action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
This is how the HTML code above will be displayed in a browser:
First name:
Last name:
Mouse
Mickey

Submit

The Action Attribute

The action attribute defines the action to be performed when the form is submitted.

Normally, the form data is sent to a web page on the server when the user clicks on the
submit button.

In the example above, the form data is sent to a page on the server called
"/action_page.php". This page contains a server-side script that handles the form data:

<form action="/action_page.php">

If the action attribute is omitted, the action is set to the current page.

The Target Attribute

The target attribute specifies if the submitted result will open in a new browser tab, a
frame, or in the current window.

The default value is "_self" which means the form will be submitted in the current
window.
To make the form result open in a new browser tab, use the value
"_blank": Example
<form action="/action_page.php" target="_blank">

Other legal values are "_parent", "_top", or a name representing the name of an iframe.

The Method Attribute

The method attribute specifies the HTTP method (GET or POST) to be used when
submitting the form data:

Example
<form action="/action_page.php" method="get">
or:

Example
<form action="/action_page.php" method="post">
When to Use GET?
The default method when submitting form data is GET.

However, when GET is used, the submitted form data will be visible in the
page address field:

/action_page.php?firstname=Mickey&lastname=Mouse

Notes on GET:

 Appends form-data into the URL in name/value pairs


 The length of a URL is limited (about 3000 characters)
 Never use GET to send sensitive data! (will be visible in the URL)
 Useful for form submissions where a user wants to bookmark the result
 GET is better for non-secure data, like query strings in Google

Notes on POST:

 POST has no size limitations, and can be used to send large amounts of data.
 Form submissions with POST cannot be bookmarked

The Name Attribute

Each input field must have a name attribute to be submitted.

If the name attribute is omitted, the data of that input field will not be sent at all.
This example will only submit the "Last name" input field:
Example
<form action="/action_page.php">
First name:<br>
<input type="text"
value="Mickey"><br> Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
Grouping Form Data with <fieldset>

The <fieldset> element is used to group related data in a form.


The <legend> element defines a caption for the <fieldset> element.

Example
<form action="/action_page.php">
<fieldset>
<legend>Personal information:</legend>
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</fieldset>
</form>

This is how the HTML code above will be displayed in a browser:


Personal information:First name:
Last name:
Mouse
Mickey

Submit

HTML Form Elements

The <input> Element

The most important form element is the <input> element.


The <input> element can be displayed in several ways, depending on the type attribute.
Example
<input name="firstname" type="text">

If the type attribute is omitted, the input field gets the default type: "text".

The <select> Element

The <select> element defines a drop-down list:


Example
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>

The <option> elements defines an option that can be


selected. By default, the first item in the drop-down list is
selected.
To define a pre-selected option, add the selected attribute to the option:

Example
<option value="fiat"
selected>Fiat</option> Visible Values:
Use the size attribute to specify the number of visible values:

Example
<select name="cars" size="3">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
Allow Multiple Selections:

Use the multiple attribute to allow the user to select more than one value:

Example
<select name="cars" size="4" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
The <textarea> Element

The <textarea> element defines a multi-line input field (a text area):


Example
<textarea name="message" rows="10" cols="30">
The cat was playing in the garden.
</textarea>

The rows attribute specifies the visible number of lines in a text area.
The cols attribute specifies the visible width of a text area.
This is how the HTML code above will be displayed in a browser:

You can also define the size of the text area by using CSS:

Example
<textarea name="message" style="width:200px; height:600px">
The cat was playing in the garden.
</textarea>
The <button> Element

The <button> element defines a clickable button:

Example
<button type="button" onclick="alert('Hello World!')">Click Me!</button>
This is how the HTML code above will be displayed in a browser:
Click Me!

Note: Always specify the type attribute for the button element. Different browsers
may use different default types for the button element
HINTS

 Use the HTML <table> element to define a table


 Use the HTML <tr> element to define a table row
 Use the HTML <td> element to define a table data
 Use the HTML <th> element to define a table heading
 Use the HTML <caption> element to define a table caption
 Use the CSS border property to define a border
 Use the CSS border-collapse property to collapse cell borders
 Use the CSS padding property to add padding to cells
 Use the CSS text-align property to align cell text
 Use the CSS border-spacing property to set the spacing between cells
 Use the colspan attribute to make a cell span many columns
 Use the rowspan attribute to make a cell span many rows
 Use the id attribute to uniquely define one table
UNIT-III - fundamentals of the javascript language: capabilities of javascript -
definitions - structure of Javascript code - data and objects - tokens, operators,
expressions, and statements - the javascriptMath object - comparison operators
and decision-making structures: relational and logicalOperators - the if construct -
the switch construct. Loop structures: count-controlled loops -Conditional loops.
Using javascript to change values in form fields.

JavaScript Statements
Example
var x, y, z; // Statement
1 x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement
4

JavaScript Programs

A computer program is a list of "instructions" to be "executed" by a computer.

In a programming language, these programming instructions are called statements.


JavaScript Statements
JavaScript statements are composed of:

Values, Operators, Expressions, Keywords, and Comments.

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

Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
Most JavaScript programs contain many JavaScript statements.
The statements are executed, one by one, in the same order as they are written.

Semicolons ;

Semicolons separate JavaScript statements.

Add a semicolon at the end of each executable statement:

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


a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c
When separated by semicolons, multiple statements on one line are
allowed: a = 5; b = 6; c = a + b;
JavaScript White Space

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

The following lines are equivalent:

var person =
"Hege"; var
person="Hege";

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


var x = y + z;
JavaScript Line Length and Line Breaks

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

If a JavaScript statement does not fit on one line, the best place to break it is after
an operator:

Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";
JavaScript Code Blocks

JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
The purpose of code blocks is to define statements to be executed together.

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

Example
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}

JavaScript Keywords

JavaScript statements often start with a keyword to identify the JavaScript action to be
performed. JavaScript keywords are reserved words. Reserved words cannot be used as
names for variables.

JavaScript Syntax
JavaScript syntax is the set of rules, how JavaScript programs are
constructed: var x, y; // How to declare variables
x = 5; y = 6; // How to assign values
z = x + y; // How to compute values

JavaScript Values

The JavaScript syntax defines two types of values: Fixed values and variable values.
Fixed values are called literals. Variable values are called variables.
JavaScript Literals

The most important rules for writing fixed values are:

Numbers are written with or without decimals:


10.50
1001

Strings are text, written within double or single quotes:


"John Doe"

'John Doe'

JavaScript Variables

In a programming language, variables are used to store data values.


JavaScript uses the var keyword to declare variables.
An equal sign is used to assign values to variables.

In this example, x is defined as a variable. Then, x is assigned (given) the value 6:


var x;
x = 6;

JavaScript Operators

JavaScript uses arithmetic operators ( + - * / ) to compute values:


(5 + 6) * 10
JavaScript uses an assignment operator ( = ) to assign values to variables:

var x, y;
x = 5;
y = 6;

JavaScript Expressions

An expression is a combination of values, variables, and operators, which computes to


a value.

The computation is called an


evaluation. For example, 5 * 10
evaluates to 50:
5 * 10

Expressions can also contain variable values:

x * 10

The values can be of various types, such as numbers and strings.


For example, "John" + " " + "Doe", evaluates to "John Doe":

"John" + " " + "Doe"


JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.
The var keyword tells the browser to create variables:
var x, y;
x=5+
6;
y = x * 10;

JavaScript Comments

Not all JavaScript statements are "executed".

Code after double slashes // or between /* and */ is treated as a comment.


Comments are ignored, and will not be executed:
var x = 5; // I will be executed

// var x = 6; I will NOT be executed

JavaScript Identifiers

Identifiers are names.

In JavaScript, identifiers are used to name variables (and keywords, and functions, and
labels).

The rules for legal names are much the same in most programming languages.

In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign
($).
Subsequent characters may be letters, digits, underscores, or dollar signs.
Numbers are not allowed as the first character.
This way JavaScript can easily distinguish identifiers from numbers.

JavaScript is Case Sensitive

All JavaScript identifiers are case sensitive.


The variables lastName and lastname, are two different variables.

var lastname,
lastName; lastName =
"Doe"; lastname =
"Peterson";

JavaScript does not interpret VAR or Var as the keyword


var. JavaScript Character Set
JavaScript uses the Unicode character set.

Unicode covers (almost) all the characters, punctuations, and symbols in the world.

.JavaScript Comments

JavaScript comments can be used to explain JavaScript code, and to make it more
readable.

JavaScript comments can also be used to prevent execution, when testing


alternative code.

Single Line Comments

Single line comments start with //.

Any text between // and the end of the line will be ignored by JavaScript (will not be
executed).
This example uses a single-line comment before each code
line: Example
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";

This example uses a single line comment at the end of each line to explain the code:

Example
var x = 5; // Declare x, give it the value of 5
var y = x + 2; // Declare y, give it the value of x + 2

Multi-line Comments
Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored by JavaScript.


This example uses a multi-line comment (a comment block) to explain the code:
Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
Using Comments to Prevent Execution

Using comments to prevent execution of code is suitable for code testing.

Adding // in front of a code line changes the code lines from an executable line to a
comment.
This example uses // to prevent execution of one of the code
lines: Example
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
This example uses a comment block to prevent execution of multiple lines:
Example
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/

JavaScript Variables

JavaScript variables are containers for storing data values.


In this example, x, y, and z, are variables:
Example
var x = 5;
var y = 6;
var z = x + y;

From the example above, you can expect:

 x stores the value 5


 y stores the value 6
 z stores the value 11

JavaScript variables are containers for storing data values.


JavaScript Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

 Names can contain letters, digits, underscores, and dollar signs.


 Names must begin with a letter
 Names can also begin with $ and _ (but we will not use it in this tutorial)
 Names are case sensitive (y and Y are different variables)
 Reserved words (like JavaScript keywords) cannot be used as names

The Assignment Operator

In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.
This is different from algebra. The following does not make sense in algebra:
x=x+5

In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.

(It calculates the value of x + 5 and puts the result into x. The value of x is incremented
by 5.)

The "equal to" operator is written like == in JavaScript.


JavaScript Data Types

JavaScript variables can hold numbers like 100 and text values like "John Doe".
In programming, text values are called text strings.
JavaScript can handle many types of data, but for now, just think of numbers and
strings.

Strings are written inside double or single quotes. Numbers are written without
quotes. If you put a number in quotes, it will be treated as a text string.
Example
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
Declaring (Creating) JavaScript Variables

Creating a variable in JavaScript is called "declaring" a variable.


You declare a JavaScript variable with the var keyword:
var carName;

After the declaration, the variable has no value. (Technically it has the value
of undefined)

To assign a value to the variable, use the equal sign:

carName = "Volvo";

You can also assign a value to the variable when you declare
it: var carName = "Volvo";
In the example below, we create a variable called carName and assign the value
"Volvo" to it.
Then we "output" the value inside an HTML paragraph with id="demo":
Example
<p id="demo"></p>
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>

One Statement, Many Variables

You can declare many variables in one statement.

Start the statement with var and separate the variables by comma:
var person = "John Doe", carName = "Volvo", price = 200;
A declaration can span multiple lines:

var person = "John Doe",


carName = "Volvo",
price = 200;
Value = undefined

In computer programs, variables are often declared without a value. The value can
be something that has to be calculated, or something that will be provided later, like
user input.

A variable declared without a value will have the value undefined.

The variable carName will have the value undefined after the execution of this
statement:

Example
var carName;

Re-Declaring JavaScript Variables

If you re-declare a JavaScript variable, it will not lose its value.

The variable carName will still have the value "Volvo" after the execution of these
statements:

Example
var carName = "Volvo";
var carName;
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like =
and +:

Example
var x = 5 + 2 + 3;

You can also add strings, but strings will be concatenated:

Example
var x = "John" + " " + "Doe";
Also try this:
Example
var x = "5" + 2 + 3;

If you put a number in quotes, the rest of the numbers will be treated as strings,
and concatenated.

Now try this:

Example
var x = 2 + 3 + "5";

JavaScript Operators
Example
Assign values to variables and add them
together: var x = 5; // assign the value 5 to x
var y = 2; // assign the value 2 to y
var z = x + y; // assign the value 7 to z (x + y)

The assignment operator (=) assigns a value to a variable.

Assignment
var x = 10;
The addition operator (+) adds numbers:
Adding
var x = 5;
var y = 2;
var z = x + y;

The multiplication operator (*) multiplies numbers.

Multiplying
var x = 5;
var y = 2;
var z = x * y;
JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic on numbers:

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.

The addition assignment operator (+=) adds a value to a variable.

Assignment
var x = 10;
x += 5;
JavaScript String Operators

The + operator can also be used to add (concatenate) strings.

Example
var txt1 = "John";
var txt2 = "Doe";
var txt3 = txt1 + " " + txt2;
The result of txt3 will be:
John Doe

The += assignment operator can also be used to add (concatenate) strings:


Example
var txt1 = "What a very ";
txt1 += "nice day";

The result of txt1 will be:

What a very nice day

When used on strings, the + operator is called the concatenation operator.

Adding Strings and Numbers

Adding two numbers, will return the sum, but adding a number and a string will return
a string:

Example
var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;

The result of x, y, and z will be:


10
55
Hello5

JavaScript Comparison Operators

Operator Description

== equal to

=== equal value and equal type

!= not equal
!== not equal value or not equal type

> greater than

< less than

>= greater than or equal to

<= less than or equal to

? ternary operator

JavaScript Logical Operators

Operator Description

&& logical and

|| logical or

! logical not
Operator Description Example Same as Result Decimal

& AND 5&1 0101 & 0001 0001 1

| OR 5|1 0101 | 0001 0101 5

~ NOT ~5 ~0101 1010 10

^ XOR 5^1 0101 ^ 0001 0100 4

<< Zero fill left shift 5 << 1 0101 << 1 1010 10

>> Signed right shift 5 >> 1 0101 >> 1 0010 2

>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010 2

JavaScript Type Operators

Operator Description

typeofReturns the type of a variable


instanceof Returns true if an object is an instance of an object type

JavaScript Bitwise Operators

Bit operators work on 32 bits numbers.

Any numeric operand in the operation is converted into a 32 bit number. The result is
converted back to a JavaScript number.
JavaScript Arithmetic Operators

Arithmetic operators perform arithmetic on numbers (literals or variables).

Operator Description

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus (Remainder)

++ Increment
--
Decrement

Arithmetic Operations

A typical arithmetic operation operates on two numbers.


The two numbers can be literals:
Example
var x = 100 + 50;
or variables:
Example
var x = a + b;
or expressions:
Example
var x = (100 + 50) * a;
Operators and Operands
The numbers (in an arithmetic operation) are called operands.

The operation (to be performed between the two operands) is defined by an operator.

Operand Operator Operand

100 + 50

Adding

The addition operator (+) adds numbers:


Example
var x = 5;
var y = 2;
var z = x + y;
Subtracting

The subtraction operator (-) subtracts numbers.

Example
var x = 5;
var y = 2;
var z = x - y;
Multiplying

The multiplication operator (*) multiplies numbers.

Example
var x = 5;
var y = 2;
var z = x * y;
Dividing

The division operator (/) divides numbers.

Example
var x = 5;
var y = 2;
var z = x / y;
Remainder

The modulus operator (%) returns the division remainder.

Example
var x = 5;
var y = 2;
var z = x % y;
In arithmetic, the division of two integers produces a quotient and a remainder.
In mathematics, the result of a modulo operation is the remainder of an arithmetic
division.

Incrementing

The increment operator (++) increments numbers.

Example
var x =
5; x++;
var z = x;
Decrementing
The decrement operator (--) decrements numbers.

Example
var x = 5;
x--;
var z = x;

Operator Precedence

Operator precedence describes the order in which operations are performed in an


arithmetic expression.

Example
var x = 100 + 50 * 3;

Is the result of example above the same as 150 * 3, or is it the same as 100 + 150?
Is the addition or the multiplication done first?
As in traditional school mathematics, the multiplication is done first.

Multiplication (*) and division (/) have higher precedence than addition (+) and
subtraction (-).

And (as in school mathematics) the precedence can be changed by using parentheses:

Example
var x = (100 + 50) * 3;
When using parentheses, the operations inside the parentheses are computed first.

When many operations have the same precedence (like addition and subtraction), they
are computed from left to right:

Example
var x = 100 + 50 - 3;

JavaScript Operator Precedence Values

Pale red entries indicates ECMAScript 2015 (ES6) or higher.

Value Operator Description Example

20 () Expression grouping (3 + 4)

19 . Member person.name

19 [] Member person["name"]

19 () Function call myFunction()

19 new Create new Date()


17 ++ Postfix Increment i++

17 -- Postfix Decrement i--

16 ++ Prefix Increment ++i

16 -- Prefix Decrement --i

16 ! Logical not !(x==y)

16 typeof Type typeof x

15 ** Exponentiation (ES7) 10 ** 2

14 * Multiplication 10 * 5
14 / Division 10 / 5

14 % Division Remainder 10 % 5

13 + Addition 10 + 5

13 - Subtraction 10 - 5

12 << Shift left x << 2

12 >> Shift right x >> 2

12 >>> Shift right (unsigned) x >>> 2

11 < Less than x<y


11 <= Less than or equal x <= y

11 > Greater than x>y

11 >= Greater than or equal x >= y

11 in Property in Object "PI" in Math

11 instanceof Instance of Object instanceof


Array

10 == Equal x == y

10 === Strict equal x === y

10 != Unequal x != y

10 !== Strict unequal x !== y


9 & Bitwise AND x&y

8 ^ Bitwise XOR x^y

7 | Bitwise OR x| y

6 && Logical AND x && y

5 || Logical OR x || y

4 ?: Condition ? "Yes" : "No"

3 += Assignment x += y

3 += Assignment x += y

3 -= Assignment x -= y

3 *= Assignment x *= y
3 %= Assignment x %= y

3 <<= Assignment x <<= y

3 >>= Assignment x >>= y

3 >>>= Assignment x >>>= y

3 &= Assignment x &= y

3 ^= Assignment x ^= y

3 |= Assignment x |= y

2 yield Pause Function yield x

1 , Comma 5,6

Expressions in parentheses are fully computed before the value is used in the rest of the
expression.
JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.

Operator Example Same As

= x=y x=y

+= x += y x=x+y

-= x -= y x=x-y

*= x *= y x=x*y

/= x /= y x=x/y

%= x %= y x=x%y

<<= x <<= y x = x << y

>>= x >>= y x = x >> y

>>>= x >>>= y x = x >>> y


&= x &= y x=x&y

^= x ^= y x=x^y

|= x |= y x=x|y

**= x **= y x = x ** y

Assignment Examples

The = assignment operator assigns a value to a variable.

Assignment
var x = 10;
The += assignment operator adds a value to a variable.

Assignment
var x = 10;
x += 5;

The -= assignment operator subtracts a value from a variable.

Assignment
var x = 10;
x -= 5;

The *= assignment operator multiplies a variable.

Assignment
var x = 10;
x *= 5;

The /= assignment divides a variable.


Assignment
var x =
10; x /=
5;

The %= assignment operator assigns a remainder to a variable.

Assignment
var x = 10;
x %= 5;
JavaScript Data Types
JavaScript variables can hold many data types: numbers, strings, objects and more:
var length = 16; // Number
var lastName = "Johnson"; // String
var x = {firstName:"John", lastName:"Doe"}; // Object
The Concept of Data Types
In programming, data types is an important concept.

To be able to operate on variables, it is important to know something about the type.


Without data types, a computer cannot safely solve this:
var x = 16 + "Volvo";

Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it
produce a result?

JavaScript will treat the example above as:

var x = "16" + "Volvo";

When adding a number and a string, JavaScript will treat the number as a string.

Example
var x = 16 + "Volvo";

Example
var x = "Volvo" + 16;
JavaScript evaluates expressions from left to right. Different sequences can produce
different results:

JavaScript:
var x = 16 + 4 + "Volvo";

Result:
20Volvo

JavaScript:
var x = "Volvo" + 16 + 4;

Result:
Volvo164

In the first example, JavaScript treats 16 and 4 as numbers, until it reaches "Volvo".

In the second example, since the first operand is a string, all operands are treated as
strings.

JavaScript Types are Dynamic

JavaScript has dynamic types. This means that the same variable can be used to
hold different data types:

Example
var x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String

JavaScript Strings

A string (or a text string) is a series of characters like "John Doe".


Strings are written with quotes. You can use single or double quotes:
Example
var carName = "Volvo XC60"; // Using double quotes
var carName = 'Volvo XC60'; // Using single quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding
the string:

Example
var answer = "It's alright"; // Single quote inside double quotes
var answer = "He is called 'Johnny'"; // Single quotes inside double quotes
var answer = 'He is called "Johnny"'; // Double quotes inside single quotes
JavaScript Numbers

JavaScript has only one type of numbers.

Numbers can be written with, or without decimals:

Example
var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals

Extra large or extra small numbers can be written with scientific (exponential) notation:

Example
var y = 123e5; // 12300000
var z = 123e-5; // 0.00123
JavaScript Booleans

Booleans can only have two values: true or false.

Example
var x = 5;
var y =
5; var z =
6;
(x == y) // Returns true
(x == z) // Returns false

Booleans are often used in conditional testing.

You will learn more about conditional testing later in this tutorial.

JavaScript Objects

JavaScript objects are written with curly braces.


Object properties are written as name:value pairs, separated by commas.

Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

The object (person) in the example above has 4 properties: firstName, lastName, age,
and eyeColor.

You will learn more about objects later in this tutorial.


The typeof Operator
You can use the JavaScript typeof operator to find the type of a JavaScript variable.
The typeof operator returns the type of a variable or an expression:
Example
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns
"string"
Example
typeof 0 // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns
"number"
Undefined

In JavaScript, a variable without a value, has the value undefined. The type is
also undefined.

Example
var car; // Value is undefined, type is undefined

Any variable can be emptied, by setting the value to undefined. The type will
also be undefined.

Example
car = undefined; // Value is undefined, type is undefined
Empty Values

An empty value has nothing to do with undefined.


An empty string has both a legal value and a type.
Example
var car = ""; // The value is "", the typeof is
"string" Null
In JavaScript null is "nothing". It is supposed to be something that doesn't exist.
Unfortunately, in JavaScript, the data type of null is an object.
You can consider it a bug in JavaScript that typeof null is an object. It should be null.
You can empty an object by setting it to null:
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = null; // Now value is null, but type is still an object
You can also empty an object by setting it to undefined:

Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = undefined; // Now both value and type is undefined
Difference Between Undefined and Null

Undefined and null are equal in value but different in type:

typeof undefined // undefined


typeof null // object

null === undefined // false


null == undefined // true
Primitive Data

A primitive data value is a single simple data value with no additional properties and
methods.

The typeof operator can return one of these primitive types:


 string
 number
 boolean
 undefined

Example
typeof "John" // Returns "string"
typeof 3.14 // Returns
"number"
typeof true // Returns "boolean"
typeof false // Returns "boolean"
typeof x // Returns "undefined" (if x has no value)

Complex Data

The typeof operator can return one of two complex types:

 function
 object

The typeof operator returns object for both objects, arrays, and null.
The typeof operator does not return object for functions.
Example
typeof {name:'John', age:34} // Returns "object"
typeof [1,2,3,4] // Returns "object" (not "array", see note below)
typeof null // Returns "object"
typeof function myFunc(){} // Returns "function"

The typeof operator returns "object" for arrays because in JavaScript arrays are objects.

JavaScript Objects
Real Life Objects, Properties, and
Methods In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:

All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.
JavaScript Objects

You have already learned that JavaScript variables are containers for data values.
This code assigns a simple value (Fiat) to a variable named car:
var car = "Fiat";

Objects are variables too. But objects can contain many values.

This code assigns many values (Fiat, 500, white) to a variable named car:
var car = {type:"Fiat", model:"500", color:"white"};
The values are written as name:value pairs (name and value separated by a colon).

Object Definition

You define (and create) a JavaScript object with an object literal:

Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Spaces and line breaks are not important. An object definition can span multiple lines:

Example
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};

Object Properties

The name:values pairs in JavaScript objects are called properties:


Property Property Value

firstName John

lastName Doe

age 50

eyeColor blue

Accessing Object Properties

You can access object properties in two ways:

objectName.propertyName

or

objectName["propertyName"]

Example1
person.lastName;
Example2
person["lastName"];
Object Methods

Objects can also have methods.

Methods are actions that can be performed on objects.


Methods are stored in properties as function definitions.
Property Property Value

firstName John

lastName Doe

age 50

eyeColor blue

fullName function() {return this.firstName + " " + this.lastName;}

A method is a function stored as a property.

Example
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
The this Keyword

In a function definition, this refers to the "owner" of the function.

In the example above, this is the person object that "owns" the fullName function.
In other words, this.firstName means the firstName property of this object.
Read more about the this keyword at JS this
Keyword. Accessing Object Methods
You access an object method with the following syntax:

objectName.methodName()

Example
name = person.fullName();

If you access a method without the () parentheses, it will return the function definition:

Example
name = person.fullName;

Do Not Declare Strings, Numbers, and Booleans as Objects!

When a JavaScript variable is declared with the keyword "new", the variable is
created as an object:

var x = new String(); // Declares x as a String object


var y = new Number(); // Declares y as a Number object
var z = new Boolean(); // Declares z as a Boolean object

Avoid String, Number, and Boolean objects. They complicate your code and slow down
execution speed.

JavaScript For Loop

Loops can execute a block of code a number of times.

JavaScript Loops

Loops are handy, if you want to run the same code over and over again, each time with
a different value.
Often this is the case when working with
arrays: Instead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
You can write:
var i;
for (i = 0; i<cars.length; i++) {
text += cars[i] + "<br>";
}

Different Kinds of Loops

JavaScript supports different kinds of loops:

 for - loops through a block of code a number of times


 for/in - loops through the properties of an object
 while - loops through a block of code while a specified condition is true
 do/while - also loops through a block of code while a specified condition is true

The For Loop


The for loop has the following syntax:
for (statement 1; statement 2; statement 3) {
code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

Example
for (i = 0; i< 5; i++) {
text += "The number is " + i + "<br>";
}

From the example above, you can read:

Statement 1 sets a variable before the loop starts (vari = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5).
Statement 3 increases a value (i++) each time the code block in the loop has been
executed.

Statement 1

Normally you will use statement 1 to initialize the variable used in the loop (i = 0).
This is not always the case, JavaScript doesn't care. Statement 1 is optional.
You can initiate many values in statement 1 (separated by comma):

Example
for (i = 0, len = cars.length, text = ""; i<len; i++) {
text += cars[i] + "<br>";
}

And you can omit statement 1 (like when your values are set before the loop starts):
Example
var i = 2;
var len =
cars.length; var text
= "";
for (; i<len; i++) {
text += cars[i] + "<br>";
}

Statement 2

Often statement 2 is used to evaluate the condition of the initial variable.

This is not always the case, JavaScript doesn't care. Statement 2 is also optional.

If statement 2 returns true, the loop will start over again, if it returns false, the loop will
end.

Statement 3

Often statement 3 increments the value of the initial variable.

This is not always the case, JavaScript doesn't care, and statement 3 is optional.

Statement 3 can do anything like negative increment (i--), positive increment (i = i + 15),
or anything else.
Statement 3 can also be omitted (like when you increment your values inside the loop):
Example
var i = 0;
var len = cars.length;
for (; i<len; ) {
text += cars[i] + "<br>";
i++;
}

The For/In Loop

The JavaScript for/in statement loops through the properties of an object:

Example
var person = {fname:"John", lname:"Doe", age:25};

var text = "";


var x;
for (x in person) {
text += person[x];
}

The While Loop


JavaScript While Loop
The while loop loops through a block of code as long as a specified condition is true.

Syntax
while (condition) {
code block to be executed
}

Example

In the following example, the code in the loop will run, over and over again, as long as a
variable (i) is less than 10:
Example
while (i< 10) {
text += "The number is " + i;
i++;
}

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop as
long as the condition is true.
Syntax
do {
code block to be executed
}
while (condition);
Example
The example below uses a do/while loop. The loop will always be executed at least
once, even if the condition is false, because the code block is executed before the
condition is tested:
Example
do {
text += "The number is " + i;
i++;
}
while (i< 10);

Do not forget to increase the variable used in the condition, otherwise the loop will
never end!

Comparing For and While

If you have read the previous chapter, about the for loop, you will discover that a while
loop is much the same as a for loop, with statement 1 and statement 3 omitted.

The loop in this example uses a for loop to collect the car names from the cars array:

Example
var cars = ["BMW", "Volvo", "Saab",
"Ford"]; var i = 0;
var text = "";
for (;cars[i];) {
text += cars[i] + "<br>";
i++;
}

The loop in this example uses a while loop to collect the car names from the cars array:

Example
var cars = ["BMW", "Volvo", "Saab",
"Ford"]; var i = 0;
var text = "";

while (cars[i]) {
text += cars[i] + "<br>";
i++;
}

JavaScript Switch Statement

The switch statement is used to perform different actions based on different


conditions. Use the switch statement to select one of many code blocks to be executed.
Syntax
switch(expression) {
case x:
code block
break;
case y:
code block
break;
default:
code block
}

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.

Example
The getDay() method returns the weekday as a number between 0 and
6. (Sunday=0, Monday=1, Tuesday=2 ..)
This example uses the weekday number to calculate the weekday name:

switch (new Date().getDay()) {


case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day =
"Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day =
"Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}

The result of day will be:

Tuesday

The break Keyword

When JavaScript reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for
more testing.
A break can save a lot of execution time because it "ignores" the execution of all the
rest of the code in the switch block.

It is not necessary to break the last case in a switch block. The block breaks (ends) there
anyway.

The default Keyword

The default keyword specifies the code to run if there is no case match:
Example
The getDay() method returns the weekday as a number between 0 and 6.
If today is neither Saturday (6) nor Sunday (0), write a default message:
switch (new Date().getDay()) {
case 6:
text = "Today is
Saturday"; break;
case 0:
text = "Today is
Sunday"; break;
default:
text = "Looking forward to the Weekend";
}

The result of text will be:

Looking forward to the Weekend

The default case does not have to be the last case in a switch block:

Example
switch (new Date().getDay()) {
default:
text = "Looking forward to the Weekend";
break;
case 6:
text = "Today is
Saturday"; break;
case 0:
text = "Today is Sunday";
}
Common Code Blocks

Sometimes you will want different switch cases to use the same code.

In this example case 4 and 5 share the same code block, and 0 and 6 share another code
block:

Example
switch (new Date().getDay()) {
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
break;
default:
text = "Looking forward to the Weekend";
}

Switching Details

If multiple cases matches a case value, the first case is selected.

If no matching cases are found, the program continues to the default label.

If no default label is found, the program continues to the statement(s) after the switch.
Strict Comparison
Switch cases use strict comparison (===).

The values must be of the same type to match.

A strict comparison can only be true if the operands are of the same
type. In this example there will be no match for x:
Example
var x = "0";
switch (x) {
case 0:
text = "Off";
break;
case 1:
text = "On";
break;
default:
text = "No value found";
}

The if Statement

Use the if statement to specify a block of JavaScript code to be executed if a condition is


true.

Syntax

if (condition) {
block of code to be executed if the condition is true
}

Example
Make a "Good day" greeting if the hour is less than 18:00:
if (hour < 18) {
greeting = "Good day";
}

The result of greeting will be:

Good day

The else Statement


Use the else statement to specify a block of code to be executed if the condition is false.
if (condition) {
block of code to be executed if the condition is true
} else {
block of code to be executed if the condition is false
}
Example
If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening":
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}

The result of greeting will be:

Good day

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax

if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}

Example

If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than
20:00, create a "Good day" greeting, otherwise a "Good evening":

if (time < 10) {


greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
} The result of greeting will be: Good day
UNIT-IV - Using Arrays in HTML /JavaScript: Basic Array Properties - Operations
on Arrays - Creating Two Dimensional Arrays - Using Arrays to Access the
Contents of Forms - Hiding the Contents of a JavaScript Script.

Array

An array is an indexed collection. An array can be used to store a list of items (elements) under
a single name with an integral index. You can reference individual element via the integral
index in the form of anArrayName[anIndexNumber]. Furthermore, you can conveniently
process all
the elements of an array collectively via a loop.

Creating an Array via Array Initializer


You can create an array by assigning an array literal to a variable, known as Array Initializer, in
the form of [value1, value2, ...]. For examples,
// Create an array by declaring a variable and assign an array literal
var weekdays = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];

// You can print out an array


document.writeln(weekdays); // sun,mon,tue,wed,thu,fri,sat
console.log(weekdays); // ["sun", "mon", "tue", "wed", "thu", "fri",
"sat"]
// A JavaScript Array is actually an
object console.log(typeof weekdays);
// object

// You can get the length of the array via .length


property console.log(weekdays.length); // 7

// A JavaScript array can contain mixed types (number, string, boolean)


varsomethings = [1, 2.3, "abc", false];
console.log(somethings); // [1, 2.3, "abc", false]
console.log(somethings.length); // 4

// A JavaScript array is dynamically allocated


var fruits = []; // begins with an emtpy
array console.log(fruits); // []
console.log(fruits.length); // 0
// Dynamically add an item
fruits[0] = "apple";
console.log(fruits); // ["apple"]
console.log(fruits.length); // 1

// Add an item, skipping some indexes


fruits[3] = "orange";
document.writeln(fruits); // apple,,,orange
console.log(fruits); // ["apple", 3:
"orange"] console.log(fruits.length); // 4

// Push an item at the end of the array


fruits.push('banana');
document.writeln(fruits); // apple,,,orange,banana
console.log(fruits); // ["apple", 3: "orange", 4:
"banana"] console.log(fruits.length); // 5

// Traversing an array via for-loop with


index for (vari = 0; i<fruits.length; ++i) {
console.log(i + ": " + fruits[i]);
}
// 0: apple
// 1: undefined
// 2: undefined
// 3: orange
// 4: banana

// Using the JavaScript's "for-index-in" loop


for (vari in fruits) {
console.log(i + ": " + fruits[i]);
}
// 0: apple
// 3: orange
// 4: banana
// (The undefined indexes were skipped)

// Using the JavaScript's "for-item-of" loop


for (var item of fruits) {
console.log(item);
}
// apple
// undefined
// undefined
// orange
// banana
// (The undefined items were not skipped)
Take note that JavaScript's array literal is enclosed in square bracket [...], instead of {...} in
Java/C/C++.JavaScript uses {...} for object literal (to be discussed later).
You can also use an Array Initializer to create an array with missing indexes. For example,
var fruits = ['apple', , , 'orange'];
console.log(fruits); // ["apple", 3: "orange"]
// fruits[1] and fruits[2] are undefined

Accessing an Item
You can access individual element of an array via an integral index, in the form
of anArrayName[anIndexNumber]. The index of the array begins at 0, and shall be a non-
negative integer.
Array's length
The length of the array is maintained in a variable called length, which can be accessed
via anArrayName.length. In fact, the property .length returns the last integral index plus 1, as
JavaScript's array index is 0-based. Nonetheless, you are allow to manipulate the .length. For
example,
a = ['11', '22', '33'];
console.log(a); // ["11", "22", "33"]
console.log(a.length); // 3

a.length = 10;
console.log(a); // ["11", "22", "33"]
console.log(a.length); // 10
Clearly, setting the .length does not affect the array elements.

Dynamic Array
Unlike Java/C/C++, the JavaScript array is dynamically allocated. You can add more elements to
an array. You can also remove the content of an element using keyword delete. For examples,
var days = ["sun", "mon", "tue"];
console.log(days.length); // 3
console.log(days); // ["sun", "mon",
"tue"]

// Dynamically add an item


days[5] = "fri";
console.log(days.length); // 6
console.log(days); // ["sun", "mon", "tue", 5: "fri"] (items in between are undefined)

// Remove an item. Set to undefined.


delete days[1];
console.log(days.length); // 6
console.log(days); // ["sun", 2: "tue", 5: "fri"]

// Push an item at the end


days.push("sat");
console.log(days.length); // 7
console.log(days); // ["sun", 2: "tue", 5: "fri", 6: "sat"]

// Remove the last item


console.log(days.pop()); // sat
console.log(days.length); // 6
console.log(days); // ["sun", 2: "tue", 5: "fri"]

// Add an item in front, shifting the


indexes days.unshift("hi");
console.log(days.length); // 7
console.log(days); // ["hi", "sun", 3: "tue", 6: "fri"]

// Remove an item in front, shifting the


indexes console.log(days.shift()); // hi
console.log(days.length); // 6
console.log(days); // ["sun", 2: "tue", 5: "fri"]

// Negative index?
days[-9] = 'hello';
console.log(days.length); // 6
console.log(days); // ["sun", 2: "tue", 5: "fri", -9: "hello"]
// The index -9 is considered as an object property,
// outside the numerical indexes (to be discussed later)

Accessing All Items using for-loop with index


Array is usually processed collectively using a loop, e.g.,
var days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
for (vari = 1; i<days.length; ++i) {
console.log(i + ": " + days[i]);
}
// 1: mon
// 2: tue
// 3: wed
// 4: thu
// 5: fri
// 6: sat
The JavaScript's for-index-in loop
JavaScript provides a special for-index-in loop to process all the elements in an array. The syntax
is as follows, where index takes on the each of the index number of element which are
not undefined.
for (varindexinarrayName){ ... }
For example,
var months = ["jan", "feb"]; // index 0 and 1
months[11] = "dec"; // indexes 2 to 10
undefined for (vari in months) {
console.log(i + ": " + months[i]);
}
// 0: jan
// 1: feb
// 11: dec
The JavaScript's for-item-of loop
JavaScript provides a special for-item-of loop to process all the elements in an array. The syntax
is as follows, where item takes on the each of the element including the undefined.
for (varitemofarrayName){ ... }

Add/Remove item(s)
You can:
 Use array.length to add one item to the end of an array.
 Use delete to remove a particular index (set it to undefined).
 Use push() to add one or more items to the end of an array. push() returns the resultant
length of the array.
 Use unshift() to add one or more items to the beginning of an array. unshift() returns the
resultant length of the array.
 Use pop() to remove and return the last item of an array.
 Use shift() to remove and return the first item of an array.

ARRAY'S PROPERTIES AND OPERATIONS


The Array object has these commonly-used properties:
 .length: the number of items including undefineds. In fact, .length is set to the last index
plus 1.
It has these commonly-used methods:
 .join([separator]): join the elements of an array together into a single string, separated by
the separator (defaulted to ','). For example,
 var fruits = ["apple", "orange", "banana"];
 console.log(fruits.join()); // apple,orange,banana (string)
console.log(fruits.join("|")); // apple|orange|banana (string)
 aString.split([separator, limit]): Reverse of join(). Take a string and split into an array
based on the separator. For example,
 varstr = 'apple, orange, banana';
 var fruits = str.split();
 console.log(fruits); // ["apple, orange, banana"] (3 items)

 str = 'apple|*|orange|*|banana';
 fruits = str.split();
 console.log(fruits); // ["apple|*|orange|*|banana"] (one item)

 fruits = str.split('|*|');
 console.log(fruits); // ["apple", "orange", "banana"] (3 items)

 fruits = str.split('*');
console.log(fruits); // ["apple|", "|orange|", "|banana"] (3 items)
 .concat(value1, value2, ..., valueN): returns a new array composing of this array and the
given arrays or values. For example,
 var fruits = ['apple', 'orange'];
 moreFruits = fruits.concat('banana', 'watermelon');
 console.log(moreFruits); // ["apple", "orange", "banana", "watermelon"]
console.log(fruits); // ["apple", "orange"] (No change!)
 .reverse(): reverses the order of elements in the array, the first becomes last. For example,
 var a = ["1", "2", "3", "4", "5"];
 a.reverse();
console.log(a); // ["5", "4", "3", "2", "1"]
 .sort(): sorts the elements in the array. For example,
 var a = ["8", "10", "a", "b"];
 a.sort();
 console.log(a); // ["10", "8", "a", "b"]
 // Strings are sorted based on ASCII (Unicode) order.
 // Hence, "10" is before "8", as '1' is before '8'

 a = [8, 20, 5, 100];
 a.sort();
 console.log(a); // [100, 20, 5, 8]
// numbers are also sorted based on ASCII (Unicode) order!!!
Take note take, by default, number are also sorted based on ASCII (Unicode) order. To sort
numbers numerically, you can supply a callback comparison function. The function shall
take 2 arguments, say a and b, and return a negative number if a < b; a positive number if a
> b; and 0 if a == b. For
example, var a = [8, 20, 5, 100];
a.sort( function(a, b) { return a - b; } );
console.log(a); // [5, 8, 20, 100]
 .slice(beginIndex, endIndex): extracts and returns a section of an array
from beginIndex (inclusive) to endIndex (exclusive). For example,
 var a = ["a", "b", "c", "d", "e"];
 console.log(a.slice(1, 4)); // ["b", "c", "d"]
 // include start index but exclude end index
console.log(a); // ["a", "b", "c", "d", "e"] (No Change)
 .splice(startIndex, countToRemove, insertItem1, insertItem2, ...): removes elements from an
array, and insert elements at its place. For example,
 var a = ["1", "2", "3", "4", "5"];
 a.splice(2, 2, "a", "b", "c", "d");
 console.log(a); // ["1", "2", "a", "b", "c", "d", "5"]
 // 2 elements starting at index 2 (i.e., indexes 2 and 3) were removed
 // and the given elements inserted at its place (index 2).
 // Renumber the indexes.
console.log(a.length); // 7
 .indexOf(searchItem[, startIndex]) and .lastIndexOf(searchItem[, startIndex]): search for the
index of the item forward or backward. It returns -1 if item cannot be found. For example,
 var a = ['a', 'b', 'c', 'a', 'b', 'c'];
 varsearchItem = 'b';
 varidx = a.indexOf(searchItem)
 console.log(idx); // 1

 // Search again from the last found index
 idx = a.indexOf(searchItem, idx + 1)
 console.log(idx); // 4

 idx = a.indexOf(searchItem, idx + 1)
 console.log(idx); // -1 (not found)

 // Search backwards
 console.log(a.lastIndexOf('a')); // 3
console.log(a.lastIndexOf('a', 2)); // 0
 .push(): adds one or more elements to the end of an array and returns the resultant length of
the array.
 .pop(): removes and return the last element from an array.
 .shift(): removes and returns the first element from an array.
 .unshift(): adds one or more elements to the front of an array and returns the resultant length
of the array.
Arrays also support these iterative methods that iterate through each item of the array:
 .forEach(callback): takes a function with an argument which iterates through all the items in
the array.
 var fruits = ['apple', 'orange', 'banana'];
 fruits.forEach( function(item) {
 console.log('processing item: ' + item);
 });
 // processing item: apple
 // processing item: orange
// processing item: banana
NOTE: Using for-index-in or for-item-of or simple for loop is probably more conventional.
 .map(callback): return a new array, which contains all the return value from
executing callback on each item. For example,
 var fruits = ['apple', 'orange', 'banana'];
 var results = fruits.map( function(item) {
 console.log('processing item: ' + item);
 return item.toUpperCase();
 });
 console.log(results);
 // processing item: apple
 // processing item: orange
 // processing item: banana
// ["APPLE", "ORANGE", "BANANA"]
 .filter(callback): return a new array, containing the items for which callback returned true.
For example,
 var fruits = ['apple', 'orange', 'banana'];
 var result = fruits.filter( function(item) {
 console.log('processing item: ' + item);
 return /.*e$/.test(item); // ends with 'e'?
 });
 console.log(result);
 // processing item: apple
 // processing item: orange
 // processing item: banana
// ["apple", "orange"]
 .every(callback): return true if callback returns true for ALL items.
 .some(callback): return true if callback returns true for at least one item in the array.
For detailed specification and examples about a built-in object, check "Core JavaScript
References".

Associative Array
An associative array is an array of key-value pair. Instead of using numbers 0, 1, 2,... as keys as
in the regular array, you can use anything (such as string) as key in an associative array.
Associative arrays are used extensively in JavaScript and jQuery.
JavaScript does not support native associative array (it actually does not support native array
too). In JavaScript, associative arrays (and arrays) are implemented as objects (to be elaborate
later).
You can create an associative array via the Object Initializer. For example,
// Create an associative array of key-value
pairs varaStudent = {
name: 'peter', // string
id: 8888, // number
isMarried: false // boolean
};

// Add a new property via "index" operator, like an array


aStudent['age'] = 24;

// Use for..in loop to access all items


for (key in aStudent) {
console.log(key + ": " + aStudent[key]);
}
// name: peter
// id: 8888
// isMarried: false
// age: 24

// An associative array is actually an


object console.log(typeofaStudent); //
object
// You can also access a property via "dot" operator, like an object
aStudent.height = 190;
console.log(aStudent.height); // 190
Take note that Array initializer uses square brackets [ ... ]; while object initializer (for associative
array) uses curly brackets { ... }.

CREATING TWO DIMENSIONAL ARRAYS


Arrays can be nested, meaning that an array can contain another array as an element. Using this
characteristic of JavaScript arrays, multi-dimensional arrays can be created.
The following code creates a two-dimensional
array. var a =new Array(4);
for(i =0; i<4; i++){
a[i]=new Array(4);
for(j =0; j <4; j++){
a[i][j]='['+ i +', '+ j
+']';
}
}
This example creates an array with the following rows:

Row 0: [0, 0] [0, 1] [0, 2] [0, 3]


Row 1: [1, 0] [1, 1] [1, 2] [1, 3]
Row 2: [2, 0] [2, 1] [2, 2] [2, 3]
Row 3: [3, 0] [3, 1] [3, 2] [3, 3]

ACCESS THE CONTENTS OF FORM USING ARRAY

The elements collection returns a collection of all elements in a form.

Note: The elements in the collection are sorted as they appear in the source code.

Note: The elements collection returns all elements inside the <form> element, not all <form>
elements in the document. To get all <form> elements in the document, use
the document.forms collection instead.
Syntax

formObject.elements

Properties
P r o p e r t yDescription

L e n g t hReturns the number of elements in the <form> element.

Not e: T his pr o pert y is r ead - o nly

Methods

MethodD e s c r i p t i o n

[index]Returns the element in <form> with the specified index (starts at 0).

Note: Returns null if the index number is out of range

i t e m ( i n d e x )Returns the element in <form> with the specified index (starts at 0).

Note: Returns null if the index number is out of range

n a m e d I t e m ( i d )Returns the element in <form> with the specified id .

Note: Returns null if the id does not exist

Example

Find out how many elements there are in a specified <form> element:
var x = document.getElementById("myForm").elements.length;
The result of x will be:

Example

[index]

Get the value of the first element (index 0) in a form:

var x = document.getElementById("myForm").elements[0].value;
The result of x will be:
Donald

Example

item(index)

Get the value of the first element (index 0) in a form:

var x = document.getElementById("myForm").elements.item(0).value;
The result of x will be:
Donald

Example

namedItem(id)

Get the value of the element with name="fname" in a form:

var x = document.getElementById("myForm").elements.namedItem("fname").value;
The result of x will be:
Donald

Example

Loop through all elements in a form and output the value of each element:
var x = document.getElementById("myForm");
var txt = "";
var i;
for (i = 0; i<x.length; i++) {
txt = txt + x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = txt;
The result of txt will be:
Donald
Duck
Submit
HIDING THE CONTENT OF JAVASCRIPT

Style display property is used to hide and show the content of HTML DOM by accessing the
DOM element using JavaScript/jQuery.
To hide an element, set the style display property to “none”.
document.getElementById("element").style.display = "none";
To show an element, set the style display property to “block”.
document.getElementById("element").style.display = "block";
Steps to show the working of style display property:
1. Create some div and assign them an id or class and then add styling to it.
<div class=”circle” id=”circle”></div>
<div class=”rounded” id=”rounded”></div>
<div class=”square” id=”square”></div>

2. Width and height will set the width and height of the content, border-radius 0% will make a
square border, 50% will make a circle and 25% will make a rounded shape and float will
make the divs get positioned, margin-right will make them separated with a space at right.
<style type=”text/css”>
circle
{
width:130px; height:130px;
border-radius:50%; float: left; margin-right;50px;
}
rounded
{
width:130px; height:130px;
border-radius:25%; float: left; margin-right;50px;
}
square
{
width:130px; height:130px;
border-radius:25%; float: left; margin-right;50px;
}

3. Background-color will set the background color of the div.


#circle
{
background-color:#196F3D;
}
#rounded
{
background-color:#5DADE2;
}
#square
{
background-color:#58D68D;
}

4. The document.getElementById will select the div with given id.


<script type=”text/Javascript”>
document.getElementById(“circle”).onclick=function()
The style.display = "none" will make it disappear when clicked on div.
style.display=”none”;

Implementation of style.display property:


<html>
<head>
<title> Javascript </title>
<style type=”text/CSS”>. circle
{
width:130px;
height:130px;
boder-radius:50%
float:left;
margin-right:50px;
}
rounded
{
width:130px; height:130px;
border-radius:25%; float: left; margin-right;50px;
}
square
{
width:130px; height:130px;
border-radius:25%; float: left; margin-right;50px;
}

l >
.

UNIT V - JavaScript Functions: The Purpose of Functions in Programming - Defining JavaScript


Functions - Using JavaScript Functions with HTML Forms - Global Methods and Event Handlers -
Recursive Functions - Passing Values from One Document to Another - Revisiting the JavaScript
sort() Method

JAVASCRIPT FUNCTIONS

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

Example
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
}

JAVASCRIPT FUNCTION SYNTAX

A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {


code to be executed
}

Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.
A Function is much the same as a Procedure or a Subroutine, in other programming languages.

Functions

Functions are useful:


 when you have to use the same codes several times.
 as the JavaScript event handler.
 make your program easier to read and understood.
A function accepts zero or more arguments from the caller, performs the operations defined in the
body, and returns zero or a single result to the caller.
The syntax for user-defined function is:
functionfunctionName(argument1, argument2, ...) {
statements;
......
returnaValue;
}
 Functions are declared using the keyword function. You do not have to specify the return-type
and the types of the arguments because JavaScript is loosely typed. You can use
a return statement to return a single piece of result to the caller anywhere inside the function
body. If no return statement is used (or a return with no value), JavaScript returns undefined.
Functions are generally defined in the HEADsection, so that it is always loaded before being
invoked.
To invoke a function:
functionName(argument1, argument2, ...)
Example:
<!DOCTYPE html>
<!--"JSFunDemo.html" -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Function Demo</title>
<script>
function add(item1, item2) { // Take two numbers or strings
return Number(item1) + Number(item2); // Simply item1 + item2 concatenate strings
}
</script>
</head>
<body>
<script>
var number1 = prompt('Enter the first integer:'); // returns a string
var number2 = prompt('Enter the second integer:'); // returns a string
alert('The sum is ' + add(number1, number2));
</script>
</body>
</html>
Function's arguments
Function has access to an additional variable called arguments inside its body, which is an array
containing all the arguments. For example,
<!DOCTYPE html>
<!--"JSFunArguments.html" -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Function Demo - Using the "arguments" variable</title>
<script>
function add() {
var sum = 0;
for (vari = 0; i<arguments.length; i++) {
sum += Number(arguments[i]);
}
return sum;
}
</script>
</head>
<body>
<script>
document.write(add(1, 2, 3, 4, 5) + "<br>");
document.write(add(1, 2) + "<br>");
document.write(add(1.1, "2.2") + "<br>");
</script>
</body>
</html>

PASS BY VALUE VS. PASS BY REFERENCE


In JavaScript, primitive arguments are passed by value. That is, a copy of the variable is made and
passed into the function. On the other hand, objects are passed by references. That is, if you modify
the content of an object inside the function, the "copy" outside the function is also affected.
Functions are objects in JavaScript (to be discussed later).

The Default Function Arguments


JavaScript lets you invoke a function omitting some trailing arguments. It sets the omitted arguments
to the value undefined. For example,
// Define a function with 3 parameters
function f1(a1, a2, a3) {
console.log('a1: type is ' + typeof a1 + ', value is ' + a1);
console.log('a2: type is ' + typeof a2 + ', value is ' + a2);
console.log('a3: type is ' + typeof a3 + ', value is ' +
a3);
}

// Invoke the function with varying number of arguments


f1('hello');
// a1: type is string, value is hello
// a2: type is undefined, value is undefined
// a3: type is undefined, value is undefined

f1(1, 2);
// a1: type is number, value is 1
// a2: type is number, value is 2
// a3: type is undefined, value is undefined

f1('hello', 1, 2);
// a1: type is string, value is hello
// a2: type is number, value is 1
// a3: type is number, value is 2
You can use this feature to provide default value to function argument, for example,
// Define a function with default arguments
function f2(a1, a2, a3) {
// Set default for a2, if a2 is missing or null in function call
if (a2 === undefined || a2 === null) a2 = 88;

// Set default to a3
// a3 evaluates to false for undefined, null, '', 0, NaN,
false a3 = a3 || 'myDefault'; // more concise

console.log('a2: type is ' + typeof a2 + ', value is ' + a2);


console.log('a3: type is ' + typeof a3 + ', value is ' + a3);
}

// Invoke function with all the arguments


f2('hello', 1, 2);
// a2: type is number, value is 1
// a3: type is number, value is 2

// Invoke function with omitted trailing


arguments f2('hello');
// a2: type is number, value is 88
// a3: type is string, value is myDefault

f2('hello', null, null);


// a2: type is number, value is 88
// a3: type is string, value is myDefault
In the above example, we allow caller to omit the trailing arguments (a2, a3) or pass a null value (which
is a special literal for unallocated object).
The common idiom in practice today is to use the short-circuited OR expression (as in a3) to provide
default value if no value (undefined or null) is passed, provided the valid inputs cannot be false, 0, '',
and NaN that evaluate to false.

Anonymous (Inline) Functions


In JavaScript, you can define an anonymous function (without a function name) using the following
syntax:
function(parameters) { }
Anonymous function is often used in event handlers and others.

Function Variables
In JavaScript, a variable can hold a primitive (number, string, boolean). It can also hold a function
object. For example,
// Define a named function f1()
function f1(a1) {
return'run f1()';
}
console.log(f1); // function f1(a1)
console.log(f1('hello')); // run f1()

// Declare a variable f2 and assign it an anonymous function


// Same as above!
var f2 = function(a2) {
return'run f2()';
}
console.log(f2); // function f2(a2)
console.log(f2('hello')); // f2(a2)

// Define a variable f3 and assign it a named function


var f3 = f1;
console.log(f3); // function f1(a1)
console.log(f3('hello')); // run f1()

Two Ways in defining a function


As seen in the above example, there are two ways to define a function:
1. Use a function declaration statement in the form of:
FunctionfuncationName(parameters) {........}
2. Use a function expression by assigning an anonymous function to a variable:
VarfunctionVarName= function (parameters) {........}

Function as Argument
Recall that a function takes zero or more arguments from the caller. In JavaScript, the argument can be
of any types: primitive, object or even function. That is, a function may take another function as its
argument.
For example, the following function take a function and an array as its arguments, and apply the
function to the array.
// Define a function, which takes a function and an array as its arguments,
// and apply the function to each item of the array.
functionprocessArray (inFun, inArray) {
varresultArray = [];
for (vari in inArray) {
// apply function to each item of the inArray
resultArray[i] = inFun(inArray[i]);
}
returnresultArray;
}

// Passing an anonymous function


// Square each item of an array
console.log(processArray( function(x) { return x*x; }, [1, 2, 3, 4, 5] ));
// [1, 4, 9, 16, 25]

// Cubic each item of an array


console.log(processArray( function(x) { return x*x*x; }, [1, 2, 3, 4, 5] ));
// [1, 8, 27, 64, 125]

// Passing a named function


function cube(x) { return x*x*x; }
console.log(processArray( cube, [1, 2, 3, 4, 5] ));
// [1, 8, 27, 64, 125]

Nested Function
In JavaScript, you can define a function inside a function. For example,
function f1(msg1) {
console.log('in f1() with message:' + msg1);
// Define a function inside a function
function f2(msg2) {
console.log('in f2() with message:' + msg2);
return'f2:' + msg2;
}
// Invoke the nested function
return'f1:' + f2(msg1);
}

// Invoke the main function


console.log(f1('hello'));
// in f1() with message:hello
// in f2() with message:hello
// f1:f2:hello

Function as the return value


You can return a function from a function. For example,
function main(op) {
var add = function(a1, a2) {
console.log('in add');
return a1 + a2;
};

if (op === 'add') {


returnadd; // return a named nested function
} else if (op === 'mul') {
returnfunction(a1, a2) {
console.log('in mul');
return a1 * a2
}; // return a function anonymously defined
} else {
return"error: invalid argument";
}
}

// Invoke the main function


console.log(main('add')(1, 2));
// in add
// 3

console.log(main('mul')(3, 4));
// in mul
// 12

Scope of a Variable: Global vs. Function-Local

When you declare a variable outside of any function, it is called a global variable, and available to all
codes in the current document. When you declare a variable within a function, it is called a local
variable, and available only within that function. For example,
// global variable
vargvar = 8;

functionsayHello() {
// local variable
varlvar = 'hello';
console.log(gvar); // can access global variable
console.log(lvar);
returnlvar;
}
sayHello();

console.log(gvar); // can access global variable


//console.log(lvar); // error: lvar is not defined
// cannot access local variable outside the function
JavaScript does not have a block scope. A variable defined inside a block is either a local variable to
the enclosing function, or global. For example,
// global variable
for (vari = 0; i< 5; ++i)
{ varmsg = 'hello';
console.log(i);
}
console.log(i); // 5 (i is global, not block-scope)
console.log(msg); // hello (msg is also global, not block-scope)
NOTE: ECMAScript 6 introduces the let variable declaration, which is block-scope. You use
the let keyword (instead of var) to define a variable. However, ECMAScript 6 is still experimental and
not widely supported.
Interacting with Users
JavaScript provides these built-in top-level functions for interacting with the user:
 alert(string): Pop-up a box to alert user for important information. The user will have to click
"OK" to proceed. The alert() returns nothing (or undefined).
 prompt(string, defaultValue): Pop-up a box to prompt user for input, with an
optional defaultValue. The prompt() returns the user's input as a string. For example,
 var number1 = prompt('Enter the first integer:');
 var number2 = prompt('Enter the second integer:');
 alert('The sum is ' + number1 + number2); // Concatenate two strings
alert('The sum is ' + (Number(number1) + Number(number2))); // Add two numbers
 confirm(string): Pop-up a box and ask user to confirm some information. The user will have to
click on "OK" or "Cancel" to proceed. The confirm() which returns a boolean value. For example,
 varisFriday = confirm("Is it Friday?"); // Returns a boolean
 if (isFriday) {
 alert("Thank God, it's Friday!");
 } else {
 alert('Not a Friday');
}
 document.write(string), document.writeln(string): Write the specified string to the current
document. The writeln() (write-line) writes a newline after the string, while write() does not. Take
note that browsers ignores extra white spaces (blanks, tabs, newlines) in an HTML document, and
treat multiple white spaces as a single blank character. You need to write a <br> or <p>...</p> tag
to ask the browser to display a line break.
 console.log(value): write to the JavaScript console, used mainly for debugging.

Other Top-level Built-in Functions

JavaScript also pre-defines the following top-level global functions.


 parseInt(string), parseFloat(string): parses the given string and returns the numeric value
or NaN (Not-A-Number). The parseInt(str, radix) accepts an optional radix (or base). For
example,
 var a = parseInt("88");
 console.log('type: ' + typeof a + ', value: ' + a); // type: number, value: 88

 a = parseInt("88.99");
 console.log('type: ' + typeof a + ', value: ' + a); // type: number, value: 88

 a = parseInt("14px");
 console.log('type: ' + typeof a + ', value: ' + a); // type: number, value: 14

 a = parseInt("Hello");
 console.log('type: ' + typeof a + ', value: ' + a); // type: number, value: NaN

 a = parseFloat("88.99");
 console.log('type: ' + typeof a + ', value: ' + a); // type: number, value: 88.99

 a = parseFloat("0.5%");
 console.log('type: ' + typeof a + ', value: ' + a); // type: number, value: 0.5

 a = parseFloat('Hi');
console.log('type: ' + typeof a + ', value: ' + a); // type: number, value: NaN
 Number(object): returns the number representation of the object. It works for String object, as
well as many objects such as Date.
 isFinite(number): returns true if number is not NaN, Infinity or -Infinity.
 isNaN(number): returns true if number is NaN. Useful for checking the output
of parseInt() and parseFloat().
 eval(codes): evaluate the given JavaScript codes, which could be an expression or a sequence of
statements.
 encodeURI(), decodeURI(), encodeURIComponent(), decodeURIComponent(): encode or decode
name-value pairs for the HTTP request, by replacing special characters with %xx.
RECURSIVE FUNCTIONS

Recursion is a programming pattern that is useful in situations when a task can be naturally split into
several tasks of the same kind, but simpler. Or when a task can be simplified into an easy action plus a
simpler variant of the same task.
There are two ways to implement it.
 Iterative thinking: the for loop:
 function pow(x, n) {
 let result = 1;

 // multiply result by x n times in the loop
 for (let i = 0; i< n; i++) {
 result *= x;
 }

 return result;
 }

 alert( pow(2, 3) ); // 8
 Recursive thinking: simplify the task and call self:
 function pow(x, n) {
 if (n == 1) {
 return x;
 } else {
 return x * pow(x, n - 1);
 }
 }

alert(pow(2, 3) ); // 8
Please note how the recursive variant is fundamentally different.
When pow(x, n) is called, the execution splits into two branches:
if n==1 = x
/
pow(x, n) =
\
else = x * pow(x, n - 1)
 If n == 1, then everything is trivial. It is called the base of recursion, because it immediately
produces the obvious result: pow(x, 1) equals x.
 Otherwise, we can represent pow(x, n) as x * pow(x, n - 1). In maths, one would write xn = x *
xn-1. This is called a recursive step: we transform the task into a simpler action (multiplication
by x) and a simpler call of the same task (powwith lower n). Next steps simplify it further and
further until n reaches 1.
 We can also say that pow recursively calls itself till n == 1.

For example, to calculate pow(2, 4) the recursive variant does these steps:
 pow(2, 4) = 2 * pow(2, 3)
 pow(2, 3) = 2 * pow(2, 2)
 pow(2, 2) = 2 * pow(2, 1)
 pow(2, 1) = 2
So, the recursion reduces a function call to a simpler one, and then – to even more simpler, and so on,
until the result becomes obvious.

INTRODUCTION TO EVENTS

JavaScript are often event-driven. That is, a piece of program (called event handler) fires in response
to a certain user's or browser's action that generates an event.
The commonly-used events are:
 click: generated when the user clicks on an HTML element.
 mouseover, mouseout: generated when the user positions the mouse pointer inside/away from the
HTML element.
 load, unload: generated after the browser loaded a document, and before the next document is
loaded, respectively.
The event handler, called oneventname (such as onclick, onmousemove, onload), is the codes that responses
to an event. The event handler is typically attached to the target HTML tag, e.g.,
<!DOCTYPE html>
<!--"JSEventDemo.html" -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Event Demo</title>
<script>
function say(message) {
alert(message);
}
</script>
</head>
<body>
<h2 onmouseover="this.style.color='red'"
onmouseout="this.style.color=''">Hello</h2>
<input type="button" value="click me to say Hello"onclick="say('Hello')">
<p onclick="say('Hi')">This paragraph can say Hi...</p>
</body>
</html>

Attach Event Handler to an HTML tag

You can attach event handler (e.g., onclick, onmouseover) to a specific HTML tag as the tag's attribute, as
follows:
<tagNameeventHandler="JavaScript statement(s)"otherAttributes>contents</tagName>
The event handler can be a single JavaScript statement, a series of JavaScript statements (separated by
semicolon), or most often, a function call. For example,
<!-- Event handler calls built-in functions -->
<body onload="alert('welcome')"onunload="alert('bye')">

<!-- Event handler calls a user-defined function -->


<script>
functionmyHandler(event) {
alert(event);
}
</script>
<input type="button" value="click me"onclick="myHandler()">

<!-- Event handler composes of JavaScript statement(s) -->


<h1 onmouseover="this.style.color='red'; this.style.backgroundColor='black'"
onmouseout="this.style.color=''; this.style.backgroundColor=''">>Hello</h1>
You can also define an event handler in script by assigning a Function object (without parentheses) to
an event handler. For example,
<!-- Event handler assigned via DOM object instead of inside HTML tag -->
<p id="magic">Welcome</p>
<script>
document.getElementById("magic").onclick = myHandler;// function name without the parentheses
</script>

Built-in Events and Event Handlers


JavaScript supports many types of events, as tabulated below. Certain events such as click are
applicable to all the HTML elements; certain event such as load and unload are applicable to a selected
group of tags.
Event Name Event Handler D e s c r i p t i o n H T M L E l e m e n t

c l i c k o n c l i c k User clicks on the component.

su b m i t onsubmit User clicks the "submit" button. <form>, <input type="submit">


r e s e t o n r e s e t User clicks the "reset" button. <form>, <input type="reset" >
s e l e c t onselect User selects text in a text box or text area. <textarea>, <input type="text">
keypress onkeypres User holds down a ke document, image, link, textarea
s y.
keydown o n k e yd o w n User presses/releases a key.
key up onke yu p

mousedown onmousedown User presses/releases a mouse button. button, document, link


mouseup onmouseup
mousemove onmousemov e User moves the mouse pointer
l o a d on l o a d When the page is loaded into the window. < b o d y> , < f r a m e s e t > , < i m
g>
un l o a d onunload When another page is about to be loaded. <body>, <frameset >
m o v e o n m o v e User moves/resizes the window w i n d o w , f r a m e
resize onresize
< i m g >
The Event object
The event handlers are passed one argument, an Event object, which described the event and its current
states. You can use it to determine where an event originated from and where it currently is in the
event flow.
The following properties are available to all the Event object:
 type: A string indicating the type of event, e.g., "click", "mouseover".
 eventPhase: integer 1 for captured, 2 for at the target, and 3 for bubbling phase.

Mouse-Related Events
Including click, mouseup, mousedown, mouseover, mouseout, mousemove. For mouse-related events,
the Event object provides these additional properties:
1. button: integer 1 for left button, 2 for middle, and 3 for right
2. clientX, clientY: mouse location relative to the client area.
3. screenX, screenY: mouse location relative to the screen.
4. altKey, ctrlKey, metaKey, shiftKey: boolean value indicating where these key was pressed when
the mouse event is fired.

Key-Related Events
Including keyup, keydown and keypress. For key-related events, the Event object provides these additional
properties:
 keyCode: ASCII code of the key pressed.
 altKey, ctrlKey, metaKey, shiftKey: boolean flag indicating whether these key was also pressed.
 clientX, clientY: mouse location relative to the client area.
 screenX, screenY: mouse location relative to the screen.

REVISITING JAVASCRIPT SORT ( ) METHOD


Definition and Usage

The sort() method sorts the items of an array.

The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down).
By default, the sort() method sorts the values as strings in alphabetical and ascending order.
This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as
strings, "25" is bigger than "100", because "2" is bigger than "1".

Because of this, the sort() method will produce an incorrect result when sorting numbers.
You can fix this by providing a "compare function" (See "Parameter Values" below).
Syntax
array.sort(compareFunction)
Description
Optional.A function that defines an alternative sort order. The function should return a negative, zero,
or positive value, depending on the arguments, like:
 function(a, b){return a-b}

When the sort() method compares two values, it sends the values to the compare function, and sorts
the values according to the returned (negative, zero, positive) value.

Example:

When comparing 40 and 100, the sort() method calls the compare function(40,100).

The function calculates 40-100, and returns -60 (a negative value).

The sort function will sort 40 as a value lower than 100.

Example
Sort numbers in an array in ascending order:

var points = [40, 100, 1, 5, 25, 10];


points.sort(function(a, b){return a-b});

Example
Sort numbers in an array in descending order:

var points = [40, 100, 1, 5, 25, 10];


points.sort(function(a, b){return b-a});
Example
Sort an array alphabetically, and then reverse the order of the sorted items (descending):

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


fruits.sort();
fruits.reverse();

You might also like