WAD Notes

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

Introduction

○ HTML stands for HyperText Markup Language.


○ HTML is used to create web pages and web applications.
○ HTML is widely used language on the web.
○ We can create a static website by HTML only.
○ Technically, HTML is a Markup language rather than a programming language.

Why CSS and JAvascript:

HTML is used for define layout of a wbepage


CSS is used to add styling to that page.
Javascript is used to program logic for page layout eg: what happens when user clicks on
button.

Example analogy:
HTML -> car body(only metal)
CSS -> Car paint , decoration etc.
Javascript -> car engine + internal working
Creating our first website:
We start building a website by creating a file named index.html
HTML programs should be always saved with .html extension

A Basic HTML page structure:

<!DOCTYPE html> → specifies this is a html5 document

<head> → contains page metadata


<title>Web page title</title> → contains title of webpage
</head>
<body> → The main body of page(rendered by browser)
<h1>Write Your First Heading</h1> → heading tag
<p>Write Your First Paragraph.</p> → paragraph tag
</body> → closing body tag
</html>

A tag is like container for either content or other HTML elements.

● Head and body are children of HTML tag.


● HTML is parent of Head and body tag.
● Most of HTML elements have opening and closing tags , with content in between opening
and closing tags.
● Some HTML tags have no content. These are called empty tags eg. <br>
● We can either use .htm or .html extension.
● You can use “inspect “ or “view page source “ option from chrome to look into websites
HTML code.

HTML element = Open tag + content + close tag

Comments in HTML

Comments in HTML should be used to mark text which should not be parsed
<!-- HTML comment - ->

Case sensitivity

HTML is not case sensitive language <H1> and <h1> are both same

Basic HTML tags

We can add elements inside body tag to define the page layout.
<body> → opening tag
Content (text, image, audio,video etc)
</body> → closing tag
HTML attributes:
Used to add more information corresponding to an HTML tag.
Eg: <h1 align=”left” > THis is heading </h1>
We can either use single or double quotes for attribute value.

HTML Heading

A HTML heading or HTML h tag can be defined as a title or a subtitle which you want to display on
the webpage. When you place the text within the heading tags <h1>.........</h1>, it is displayed on the
browser in the bold format and size of the text depends on the number of heading.

There are six different HTML headings which are defined with the <h1> to <h6> tags, from highest
level h1 (main heading) to the least level h6 (least important heading).

Example: Output:

<h1>Heading no. 1</h1> Heading no. 1


<h2>Heading no. 2</h2> Heading no. 2
<h3>Heading no. 3</h3> Heading no. 3

<h4>Heading no. 4</h4> Heading no. 4


<h5>Heading no. 5</h5> Heading no. 5
<h6>Heading no. 6</h6> Heading no. 6

HTML Paragraph <p> </p> tag


HTML paragraph or HTML p tag is used to define a paragraph in a webpage.

An HTML <p> tag indicates starting of new paragraph.

Note: If we are using various <p> tags in one HTML file then browser automatically adds a single blank
line between the two paragraphs.

See this example:

<p>This is first paragraph.</p>

<p>This is second paragraph.</p>


<p>This is third paragraph.</p>

HTML <br> tag


The <br> tag in HTML document is used to create a line break in a text. If you place the <br> tag in
the HTML code, then it works the same as pressing the enter key in a word processor.

Example:

<body>

<p>If you want to break a line <br> in a paragraph, <br> use the BR element in <br> your HTML
document. </p>

</body>

Output:
HTML <hr> tag
HTML <hr> tag is used to specify a paragraph-level thematic break in HTML document. It draw a
horizontal line between them. It is also called a Horizontal Rule in HTML.

Example:

<h2>HTML</h2>
<p>HTML is a language for describing web pages.</p>
<hr>
<h2>HR Tag </h2>

HTML Anchor <a> </a>


The HTML anchor tag defines a hyperlink that links one page to another page. It can create hyperlink
to other web page as well as files, location, or any URL. The "href" attribute is the most important
attribute of the HTML a tag. and which links to destination page or URL.

href attribute of HTML anchor tag


The href attribute is used to define the address of the file to be linked. In other words, it points out
the destination page.

The syntax of HTML anchor tag is given below.

<a href = "..........."> Link Text </a>

Let's see an example of HTML anchor tag.

<a href="second.html">Click for Second Page</a>

Appearance of HTML anchor tag


An unvisited link is displayed underlined and blue.

A visited link displayed underlined and purple.

An active link is underlined and red.

HTML Image <img>


HTML img tag is used to display image on the web page. HTML img tag is an empty tag that
contains attributes only, closing tags are not used in HTML image element.

Let's see an example of HTML image.

<h2>HTML Image Example</h2>


<img src="good_morning.jpg" alt="Good Morning Friends"/>

Attributes of HTML img tag

The src and alt are important attributes of HTML img tag. All attributes of HTML image tag are given
below.

1) src
It is a necessary attribute that describes the source or path of the image. It instructs the browser
where to look for the image on the server.The location of image may be on the same directory or
another server.

2) alt
The alt attribute defines an alternate text for the image, if it can't be displayed. The value of the alt
attribute describe the image in words.
3) width
It is an optional attribute which is used to specify the width to display the image.

4) height
It h3 the height of the image.

Example:

<img src="animal.jpg" height="180" width="300" alt="animal image">

HTML text formatting tags


HTML Formatting is a process of formatting text for better look and feel. hese tags are used to
make text bold, italicized, or underlined. There are almost 14 options available that how text appears
in HTML.

Element name Description Use Output


<b> used to bold the text written <b> Bold text </b> Bold text
between it.

<i> used to make text italic. <i> italic text </i> italic text

<mark> This tag is used to highlight <mark> marked text marked text
text. </mark>

<u> This tag is used to underline <u> underline text underline text
text written between it. </u>

<sup> It displays the content 10 <sup> 3 </sup> O


slightly above the normal
line.

<sub> It displays the content H <sup> 2 </sup> O


slightly below the normal
line.

<del> This tag is used to display <del> deleted text


the deleted content. </del>

<ins> This tag displays the <ins> inserted text inserted text
content which is added </ins>

<big> This tag is used to increase <big> Big</big> Text Big Text
the font size by one
conventional unit.
<small> This tag is used to decrease <small> small small Text
</small> Text
the font size by one unit

from base font size.

HTML Lists
HTML Lists are used to specify lists of information. All lists may contain one or more list elements.
There are three different types of HTML lists:

1. Ordered List or Numbered List (ol)


2. Unordered List or Bulleted List (ul)
3. Description List or Definition List (dl)

Note: We can create a list inside another list, which will be termed as nested List.

1)HTML Ordered List or Numbered List <ol> </ol>


HTML Ordered List or Numbered List displays elements in numbered format. The HTML ol tag is
used for ordered list.There can be different types of numbered list:

● Numeric Number (1, 2, 3)

● Capital Roman Number (I II III)


● Small Romal Number (i ii iii)
● Capital Alphabet (A B C)
● Small Alphabet (a b c)

example:

<ol>
<li>HTML</li>
<li>Java</li>
<li>JavaScript</li>
<li>SQL</li>
</ol>

start attribute
The start attribute is used with ol tag to specify from where to start the list items.

<ol type="1" start="5"> : It will show numeric values starting with "5".

<ol type="A" start="5"> : It will show capital alphabets starting with "E".

<ol type="a" start="5"> : It will show lower case alphabets starting with "e".

<ol type="I" start="5"> : It will show Roman upper case value starting with "V".

Example:

<ol type="i" start="5">


<li>HTML</li>
<li>Java</li>
<li>JavaScript</li>
<li>SQL</li>
</ol>

Output:

5. HTML

6. Java
7. JavaScript
8. SQL

reversed Attribute:

This is a Boolean attribute of HTML <ol> tag, and it is new in HTML5 version. If you use the reversed
attribute with tag then it will numbered the list in descending order (7, 6, 5, 4......1).

2) HTML Unordered List <ul> </ul>

HTML Unordered List or Bulleted List displays elements in bulleted format . We can use unordered
list where we do not need to display items in any particular order.

● Disc
○ circle
Square

None
Example
<ul>
<li>HTML</li>
<li>Java</li>
<li>JavaScript</li>
<li>SQL</li>
</ul>

Output:

○ HTML
○ Java
○ JavaScript
○ SQL

3) HTML Definition List <dl> </dl>

HTML Description List or Definition List displays elements in definition form like in dictionary. The
<dl>, <dt> and <dd> tags are used to define description list.

The 3 HTML description list tags are given below:

1. <dl> tag defines the description list.

2. <dt> tag defines data term.

3. <dd> tag defines data definition (description).

Example:

<dl>
<dt>HTML</dt>
<dd>is a markup language</dd>
<dt>Java</dt>
<dd>is a programming language and platform</dd>
<dt>JavaScript</dt>
<dd>is a scripting language</dd>
<dt>SQL</dt>
<dd>is a query language</dd>
</dl>

Output:
HTML
is a markup language
Java
is a programming language and platform
JavaScript
is a scripting language
SQL
is a query language

HTML Table <table> </table>


● HTML table tag is used to display data in tabular form (row * column). There can be many
columns in a row.A table cell can contain all sorts of HTML elements: text, images,
lists, links, other tables, etc.
● We can create a table to display data in tabular form, using <table> element, with the help of
<tr> , <td>, and <th> elements.
● Each table cell is defined by a <td> and a </td> tag.td stands for table data.
Everything between <td> and </td> are the content of the table cell.
● Each table row starts with a <tr> and ends with a </tr> tag. tr stands for table
row.
● Sometimes you want your cells to be table header cells. In those cases use the <th>
tag instead of the <td> tag. th stands for table header.

Example
A simple HTML table:

<table>

<tr>

<th>Company</th>

<th>Contact</th>

<th>Country</th>

</tr>

<tr>

<td>Alfreds</td>

<td>Maria</td>

<td>Germany</td>
</tr>

</table>

Output:

Company Contact Country

Alfreds Maria Germany

HTML Table Tags

Tag Description

<table> Defines a table

<th> Defines a header cell in a table

<tr> Defines a row in a table

<td> Defines a cell in a table

<caption> Defines a table caption

HTML Table Padding & Spacing


HTML tables can adjust the padding inside the cells, and also the space between the
cells.

HTML Table - Cell Padding


Cell padding is the space between the cell edges and the cell content.

By default the padding is set to 0.


To add padding on table cells, use the CSS padding property:

Example : th, td { padding: 15px; }

HTML Table - Cell Spacing


Cell spacing is the space between each cell.

By default the space is set to 2 pixels.

To change the space between table cells, use the CSS border-spacing property on the
table element:

Example : table { border-spacing: 30px; }

HTML Table Colspan & Rowspan


HTML Table - Colspan
To make a cell span over multiple columns, use the colspan attribute:

Example
<table>
<tr>
<th colspan="2">Name</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
</tr>
</table>

Output:

Note: The value of the colspan attribute represents the number of columns to span.
HTML Table - Rowspan
To make a cell span over multiple rows, use the rowspan attribute:

Example
<table>
<tr>
<th>Name</th>
<td>Jill</td>
</tr>
<tr>
<th rowspan="2">Phone</th>
<td>555-1234</td>
</tr>
<tr>
<td>555-8745</td>
</tr>
</table>

Output:

The value of the rowspan attribute represents the number of rows to span.

HTML Block and Inline Elements

Every HTML element has a default display value, depending on what type of element it is.
The two most common display values are block and inline.

Block-level Elements

A block-level element always starts on a new line, and the browsers automatically add some
space (a margin) before and after the element. A block-level element always takes up the full
width available (stretches out to the left and right as far as it can).

Two commonly used block elements are: <p> and <div>.


Inline Elements
An inline element does not start on a new line.

An inline element only takes up as much width as necessary.

Note: An inline element cannot contain a block-level element!

HTML Forms
An HTML form is used to collect user input. The user input is most often sent to a
server for processing.

Example :
The <form> Element
The HTML <form> element is used to create an HTML form for user input:

<form>
.
form elements
.
</form>

The <form> element is a container for different types of input elements, such as: text
fields, checkboxes, radio buttons, submit buttons, etc.

The <input> Element


The HTML <input> element is the most used form element.
An <input> element can be displayed in many ways, depending on the type
attribute.
Here are some examples:

● <input type="url">
● <input type="week">

Type values explanation output


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

<input type="submit"> defines a button for


submitting form data to a
form-handler.
The form-handler is
typically a server page
with a script for processing
input data

<input type="reset"> defines a reset button that


will reset all form values to
their default values
<input type="radio"> defines a radio button.
Radio buttons let a user
select ONLY ONE of a
limited number of choices

<input type="checkbox"> defines a checkbox.


Checkboxes let a user
select ZERO or MORE
options of a limited
number of choices.

<input type="button" defines a simple button


value="Click Me!">

<input type="color"> is used for input fields that


should contain a color.

<input type="date"> s used for input fields that


should contain a date.

specifies a date and time


<input input field, with no time
type="datetime-local"> zone

is used for input fields that


<input type="email"> should contain an e-mail
address.

<input type="image"
src="img_submit.gif" defines an image as a
alt="Submit" width="48" submit button.The path to
height="48"> the image is specified in
the src attribute.

defines a file-select field


<input and a "Browse" button for
type="file"> file uploads.

<input type="hidden"> defines a hidden input


field (not visible to a
user).A hidden field lets
web developers include
data that cannot be seen
or modified by users when
a form is submitted.

<input type="month"> allows the user to select a


month and year.
<input type="number" defines a numeric input
min="1" max="5"> field.You can also set
restrictions on what
numbers are accepted.

<input type="range" defines a control for


min="0" max="50"> entering a number whose
exact value is not
important (like a slider
control). Default range is 0
to 100.

<input type="search"> s used for search fields (a


search field behaves like a
regular text field).

<input type="tel" is used for input fields that


pattern="[0-9]{3}-[0-9]{2} should contain a telephone
-[0-9]{3}"> number

<input type="time"> allows the user to select a


time

<input type="url"> is used for input fields that


should contain a URL
address

<input type="week"> allows the user to select a


week and year

Input Restrictions
Here is a list of some common input restrictions:

Attribute Description

checked Specifies that an input field should be pre-selected when the page
loads (for type="checkbox" or type="radio")

disabled Specifies that an input field should be disabled

max Specifies the maximum value for an input field

maxlength Specifies the maximum number of character for an input field

min Specifies the minimum value for an input field

pattern Specifies a regular expression to check the input value against

readonly Specifies that an input field is read only (cannot be changed)

required Specifies that an input field is required (must be filled out)


size Specifies the width (in characters) of an input field

step Specifies the legal number intervals for an input field

value Specifies the default value for an input field

HTML <video> </video>


The HTML <video> element is used to show a video on a web page.

Example
<video width="320" height="240" controls autoplay muted >
<source src="movie.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>

How it Works
The controls attribute adds video controls, like play, pause, and volume.

It is a good idea to always include width and height attributes. If height and width are
not set, the page might flicker while the video loads.

The <source> element allows you to specify alternative video files which the browser may
choose from. The browser will use the first recognized format.

The text between the <video> and </video> tags will only be displayed in browsers that
do not support the <video> element.

Attributes of <video>

controls - adds video controls, like play, pause, and volume.

width - sets width to video

height - sets height to video

Autoplay - starts video automatically

Muted - video is muted when page is loaded

poster - sets an image to video before playing

Loop - video is played continuously in loop


HTML <audio> </audio>
The HTML <audio> element is used to play an audio file on a web page.

Example
<audio controls>
<source src="horse.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>

How it Works
The controls attribute adds audio controls, like play, pause, and volume.

The <source> element allows you to specify alternative audio files which the browser may
choose from. The browser will use the first recognized format.

The text between the <audio> and </audio> tags will only be displayed in browsers that
do not support the <audio> element.

Attributes of <audio>

controls - adds audio controls, like play, pause, and volume.

Autoplay - starts audio automatically

Muted - audio is muted when page is loaded

Loop - video is played continuously in loop

HTML Image Maps


With HTML image maps, you can create clickable areas on an image.

Image Maps
The HTML <map> tag defines an image map. An image map is an image with clickable
areas. The areas are defined with one or more <area> tags.

Example
<img src="workplace.jpg" alt="Workplace" usemap="#workmap">

<map name="workmap">
<area shape="rect" coords="34,44,270,350" alt="Computer"
href="computer.htm">
<area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.htm">
<area shape="circle" coords="337,300,44" alt="Coffee" href="coffee.htm">
</map>

How Does it Work


To create an image map you need an image, and some HTML code that describes the
clickable areas.

The image is inserted using the <img> tag. The only difference from other images is that
you must add a usemap attribute

The usemap value starts with a hash tag # followed by the name of the image map, and is
used to create a relationship between the image and the image map.

Create Image Map


Then, add a <map> element.

The <map> element is used to create an image map, and is linked to the image by using
the required name attribute

Then, add the clickable areas.

A clickable area is defined using an <area> element.

Shape
You must define the shape of the clickable area, and you can choose one of these values:

● rect - defines a rectangular region


● circle - defines a circular region
● poly - defines a polygonal region
● default - defines the entire region

You must also define some coordinates to be able to place the clickable area onto the
image.

What is CSS?
● CSS stands for Cascading Style Sheets
● CSS describes how HTML elements are to be displayed on screen, paper, or in other
media
● CSS saves a lot of work. It can control the layout of multiple web pages all at once
● External stylesheets are stored in CSS files
CSS Syntax
A CSS rule 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.

Multiple CSS declarations are separated with semicolons, and declaration blocks are
surrounded by curly braces.

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

CSS Selectors
CSS selectors are used to "find" (or select) the HTML elements you want to style.

● The CSS id Selector


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

The id of an element is 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.

<!DOCTYPE html>
<head>
<style>
#para1 {
text-align: center;
color: red;
}
</style>
</head>
<body>
<p id="para1">Hello World!</p>
</body>
</html>

The CSS class Selector


The class selector selects HTML elements with a specific class attribute.

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

<!DOCTYPE html>
<head>
<style>
.center {
text-align: center;
color: red;
}
</style>
</head>
<body>
<h1 class="center">Red and center-aligned heading</h1>
<p class="center">Red and center-aligned paragraph.</p>
</body>
</html>

Types of CSS
There are three ways of inserting a style sheet:

● External CSS
● Internal CSS
● Inline CSS

External CSS
The external style sheet is generally used when you want to make changes on multiple pages. It is
ideal for this condition because it facilitates you to change the look of the entire web site by
changing just one file.

It uses the <link> tag on every pages and the <link> tag should be put inside the head section.

Example:

<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
The external style sheet may be written in any text editor but must be saved with a .css extension.
This file should not contain HTML elements.

Internal CSS
The internal style sheet is used to add a unique style for a single document. It is defined in <head>
section of the HTML page inside the <style> tag.

Example:

<!DOCTYPE html>
<head>
<style>
body {
background-color: linen;
}
h1 {
color: red;
margin-left: 80px;
}
</style>
</head>
<body>
<h1>The internal style sheet is applied on this heading.</h1>
<p>This paragraph will not be affected.</p>
</body>
</html>

Inline CSS
We can apply CSS in a single element by inline CSS technique.

The inline CSS is also a method to insert style sheets in HTML document. This method mitigates
some advantages of style sheets so it is advised to use this method sparingly.

If you want to use inline CSS, you should use the style attribute to the relevant tag.

Example

<h2 style="color:red;margin-left:40px;">Inline CSS is applied on this heading.</h2>

CSS Basic Properties


Text Properties

Property Description Values


color Sets the color of a text RGB, hex, keyword
line-height Sets the distance between lines normal, number, length, %
letter-spacing Increase or decrease the space normal, length
between characters
text-align Aligns the text in an element left, right, center, justify
text-decoration Adds decoration to text none, underline, overline, line-through

text-indent Indents the first line of text in an length, %


element
text-transform Controls the letters in an element none, capitalize, uppercase, lowercase

Border Properties

Property Description Values


border Sets all the border properties border-width, border-style, border-color
in one declaration

border-bottom Sets all the bottom border border-bottom-width, border-bottom-style,


properties in one declaration border-bottom-color

border-bottom-color Sets the color of the bottom border-color


border
border-bottom-style Sets the style of the bottom border-style
border
border-bottom-width Sets the width of the bottom border-width
border
border-color Sets the color of the four color_name, hex_number, rgb_number,
borders transparent, inherit
border-left Sets all the left border border-left-width, border-left-style,
properties in one declaration border-left-color

border-left-color Sets the color of the left border-color


border
border-left-style Sets the style of the left border-style
border
border-left-width Sets the width of the left border-width
border
border-right Sets all the right border border-right-width, border-right-style,
properties in one declaration border-right-color

border-right-color Sets the color of the right border-color


border
border-right-style Sets the style of the right border-style
border
border-right-width Sets the width of the right border-width
border
border-style Sets the style of the four none, hidden, dotted, dashed, solid, double,
borders groove, ridge, inset, outset, inherit

border-top Sets all the top border border-top-width, border-top-style,


properties in one declaration border-top-color

border-top-color Sets the color of the top border-color


border
border-top-style Sets the style of the top border-style
border
border-top-width Sets the width of the top border-width
border
border-width Sets the width of the four thin, medium, thick, length, inherit
borders

Font Properties

Property Description Values


font Sets all the font properties in font-style, font-variant, font-weight,
one declaration font-size/line-height, font-family, caption, icon,
menu, message-box, small-caption, status-bar,
inherit
font-family Specifies the font family for text family-name, generic-family, inherit

font-size Specifies the font size of text xx-small, x-small, small, medium, large, x-large,
xx-large, smaller, larger, length, %, inherit

font-style Specifies the font style for text normal, italic, oblique, inherit

font-variant Specifies whether or not a text normal, small-caps, inherit


should be displayed in a
small-caps font
font-weight Specifies the weight of a font normal, bold, bolder, lighter,
100, 200, 300, 400, 500, 600, 700, 800, 900, inherit
Careful, many of these are not supported!

Javascript
JavaScript (js) is a light-weight object-oriented programming language which is used by several
websites for scripting the webpages. It is an interpreted, full-fledged programming language that
enables dynamic interactivity on websites when applied to an HTML document.

Features of JavaScript
There are following features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in execution environments.

2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a
structured programming language.

3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending on
the operation).

4. JavaScript is an object-oriented programming language that uses prototypes rather than


using classes for inheritance.

5. It is a light-weighted and interpreted language.

6. It is a case-sensitive language.

7. JavaScript is supportable in several operating systems including, Windows, macOS, etc.

8. It provides good control to the users over the web browsers.

JavaScript Example
<script type="text/javascript">
document.write("Hello JavaScript by JavaScript");
</script>

JavaScript provides 3 places to put the JavaScript code: within body tag, within head tag and
external JavaScript file
Link external javascript file : <script type="text/javascript" src="message.js"></script>

The script tag specifies that we are using JavaScript.

The text/javascript is the content type that provides information to the browser about the data.

JavaScript Comment
The JavaScript comments are meaningful way to deliver message. It is used to add information
about the code, warnings or suggestions so that end user can easily interpret the code.

The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.

Types of JavaScript Comments


There are two types of comments in JavaScript.

1. Single-line Comment

It is represented by double forward slashes (//). It can be used before and after the
statement.
<script>
// It is single line comment
document.write("hello javascript");
</script>

2. Multi-line Comment

It can be used to add single as well as multi line comments. So, it is more convenient.
It is represented by forward slash with asterisk then asterisk with forward slash. For example:

<script>

/* It is multi line comment.


It will not be displayed */
document.write("example of javascript multiline comment");
</script>

JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types of variables
in JavaScript : local variable and global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).

1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.


2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.
4. Javascript keywords cannot be used as variable names.
5. We cannot use space in variable name

Javascript Data Types


JavaScript provides different data types to hold different types of values. There are two types of
data types in JavaScript.

1. Primitive data type


2. Non-primitive (reference) data type

JavaScript is a dynamic type language, means you don't need to specify type of the variable
because it is dynamically used by JavaScript engine. You need to use var here to specify the data
type. It can hold any type of values such as numbers, strings etc. For example:

var a=40;//holding number


var b="Rahul";//holding string

JavaScript primitive data types


There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value


Null represents null i.e. no value at all

JavaScript non-primitive data types


The non-primitive data types are as follows

Data Type Description

Object represents instance through which we can access members

Array represents group of similar values

RegExp represents regular expression

JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands.
There are following types of operators in JavaScript.
1. Arithmetic Operators

2. Comparison (Relational) Operators


3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on the operands.

Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2
% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9

JavaScript Comparison Operators


The JavaScript comparison operator compares the two operands. The comparison operators are as
follows:

Operator Description Example

== Is equal to 10==20 = false

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

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false

JavaScript Bitwise Operators


The bitwise operators perform bitwise operations on operands. The bitwise operators are as
follows:

Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false


~ Bitwise NOT (~10) = -10

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

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

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

JavaScript Logical Operators


The following operators are known as JavaScript logical operators.

Operator Description Example

&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true

JavaScript Assignment Operators


The following operators are known as JavaScript assignment operators.

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is true or false.
There are three forms of if statement in JavaScript.

1. If Statement
2. If else statement
3. if else if statement

JavaScript If statement
It evaluates the content only if expression is true. The syntax of JavaScript if statement is given
below.

if(condition){

//content to be evaluated

Example:
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>

JavaScript If...else Statement


It evaluates the content whether condition is true of false. The syntax of JavaScript if-else
statement is given below.

if(condition){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}

Example:

<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>

JavaScript If...else if statement


It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is given below.

Example:
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>

JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions. It is just
like else if statement. But it is convenient than if..else..if because it can be used with numbers,
characters etc.

The syntax of JavaScript switch statement is given below.

switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......

default:
code to be executed if above values are not matched;
}

Let’s see the simple example of switch statement in javascript.

<script>
var grade='B';
switch(grade)
{
case 'A':
document.write(“A Grade”);
break;
case 'B':
document.write(“B Grade");
break;
case 'C':
document.write("C Grade");
break;
default:
document.write("No Grade");
}
</script>

JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It
makes the code compact. It is mostly used in array.

There are four types of loops in JavaScript.

1. for loop

2. while loop

3. do-while loop

1) JavaScript For loop


The JavaScript for loop iterates the elements for the fixed number of times. It should be used if
number of iteration is known. The syntax of for loop is given below.

for (initialization; condition; increment)


{
code to be executed
}

Example:
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>

Output:

2) JavaScript while loop


The JavaScript while loop iterates the elements for the infinite number of times. It should be used if
number of iteration is not known. The syntax of while loop is given below.

while (condition)
{
code to be executed
}

Let’s see the simple example of while loop in javascript.

<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
3) JavaScript do while loop
The JavaScript do while loop iterates the elements for the infinite number of times like while loop.
But, code is executed at least once whether condition is true or false. The syntax of do while loop is
given below.

do{

code to be executed

}while (condition);

Let’s see the simple example of do while loop in javascript.

<script>
var i=21;
do {
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>

JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many times to
reuse the code.

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it save coding.


2. Less coding: It makes our program compact. We don’t need to write many lines of code each
time to perform a common task.

JavaScript Function Syntax


The syntax of declaring function is given below.

function functionName([arg1, arg2, ...argN]){


//code to be executed
}

JavaScript Functions can have 0 or more arguments.

Let’s see the simple example of function in JavaScript that does not has arguments.

<script>
function msg()
{
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>

JavaScript Function Arguments


We can call function by passing arguments. Let’s see the example of function that has one
argument.

<script>
function getcube(number)
{
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>

Function with Return Value


We can call function that returns a value and use it in our program. Let’s see the example of function
that returns value.

<script>
function getInfo()
{
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
JavaScript Objects
Javascript objects can be created of two types: 1) User defined objects 2) Native objects

A javaScript object is an entity having state and behavior (properties and method). For example: car,
pen, bike, chair, glass, keyboard, monitor etc.

We already know that JavaScript variables are containers for data values.

Example: let 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:

const car = {type:"Fiat", model:"500", color:"white"};

1) User defined objects


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

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

The name:values pairs in JavaScript objects are called properties example: age: 50

You can access object properties in two ways:

person.lastName; OR person["lastName"];

Output: Doe

Object Methods
Objects can also have methods.

Methods are actions that can be performed on objects.

Methods are stored in properties as function definitions.


Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
In the example above, this refers to the person object:
this.firstName means the firstName property of person.
this.lastName means the lastName property of person.

Accessing Object Methods


name = person.fullName();

Example:

Output:

2) Native objects
Array Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for
arrays.

Arrays use numbers to access its "elements". In this example, person[0] returns John:

const person = ["John", "Doe", 46];

Objects use names to access its "members". In this example, person.firstName returns
John:

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

example of creating and using array in JavaScript

<script>

var emp=["Sonoo","Vimal","Ratan"];

</script>

The syntax of creating array directly is given below:

var arrayname=new Array();

Here, new keyword is used to create instance of array.

<script>
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
</script>

Accessing array all array elements one by one . Example:

var fruits= ["Mango", "banaba","apple"];


document.write(fruits[0] + "<br>");
document.write(fruits[1] + "<br>");
document.write(fruits[2] + "<br>");

Accessing array all array elements using loop . Example:

var fruits= ["Mango", "banaba","apple"];


for(i=0; i< fruits.length ; i++)
{
document.write(fruits[i] + "<br>");
}

Array object properties and methods

description const fruits = ["Banana", Output


"Orange", "Apple", "Mango"];

length The length property 4


returns the length (size) let size = fruits.length;
of an array

toString() toString() converts an fruits.toString(); Banana,Ora


array to a string of nge,Apple,
(comma separated) array Mango
values.

at() To get specific let fruit = fruits.at(2); Apple


element

pop() removes the last element fruits.pop(); Mango


from an array

push() adds a new element to let length = Banana,Ora


an array (at the end) fruits.push("Kiwi"); nge,Apple,
Mango,Kiwi

concat() It returns a new array object array1.concat(array2)


that contains two or more
merged arrays

indexOf() It searches the specified fruits.indexOf("Mango") 3


element in the given array
and returns the index of the
first match.

reverse() It reverses the elements of fruits.reverse() Banana,Ora


given array. nge,Apple,
Mango

sort() It returns the element of the fruits.sort() Apple,Bana


given array in a sorted order. na,Mango,O
range

JavaScript String
String Properties
The following table lists the standard properties of the String object.

Property Description
length Returns the length of a string.

String Methods
The following table lists the standard methods of the String object.

Method Description var str = "Hello


world";

charAt() Returns the character at the specified index. str.charAt(4) o

concat() Joins two or more strings, and returns a str.concat(str2)


new string.

endsWith() Checks whether a string ends with a str.endsWith("d") true


specified substring.

includes() Checks whether a string contains the str.includes("wor") true


specified substring.

indexOf() Returns the index of the first occurrence of str.indexOf("w") 6


the specified value in a string.

lastIndexO Returns the index of the last occurrence of str.lastIndexOf("l") 9


f() the specified value in a string.

replace() Replaces the occurrences of a string or str.replace("Hello" hii world


pattern inside a string with another string, , "hii")
and return a new string without modifying
the original string.

slice() Extracts a portion of a string and returns it str.slice(2,6) llo


as a new string.

substr() Extracts the part of a string between the str.substr(1,5) ello


start index and a number of characters after
it.

toLowerCas Converts a string to lowercase letters. str.toLowerCase() hello world


e()

toUpperCas Converts a string to uppercase letters. str.toUpperCase() HELLO


e() WORLD

trim() Removes whitespace from both ends of a str.trim() hello world


string.

Example:
var str = "Hello world";
var str2 = " this is string";

document.write(str + " -Simple string <br>");


document.write(str.length + " -length property <br>");
document.write(str.charAt(4) + " -chatAt method <br>");
document.write(str.concat(str2) + " -concat method <br>");
document.write(str.endsWith("d") + " -endswith method <br>");
document.write(str.includes("wor") + " - includes method <br>");
document.write(str.indexOf("w") + " -indexOf method <br>");
document.write(str.replace("Hello" , "hii") + " -replace method <br>");
document.write(str.slice(2,6) + " - slice method <br>");
document.write(str.substr(1,5) + " - substr method <br>");
document.write(str.toLowerCase() + " -toLowerCase method <br>");
document.write(str.toUpperCase() + " -toUpperCase method <br>");
document.write(str.trim() + " - trim method <br>");

JavaScript Date Object


The JavaScript date object can be used to get year, month and day. You can display a timer on the
webpage by the help of JavaScript date object.

You can use different Date constructors to create date object. It provides methods to get and set
day, month, year, hour, minute and seconds.

You can use 4 variant of Date constructor to create date object.

1. Date()

let d = new Date();


document.write(d);

2. Date(milliseconds)
let d = new Date(1517356800000);
document.write(d);

3. Date(dateString)
let d = new Date("31 January 2018");
document.write(d);

4. Date(year, month, day, hours, minutes, seconds, milliseconds)


let d = new Date(2018,0,31,14,35,20,50);
document.write(d);

JavaScript Date Methods


Methods Description

getDate() It returns the integer value between 1 and 31 that represents the day for the

specified date on the basis of local time.

getDay() It returns the integer value between 0 and 6 that represents the day of the

week on the basis of local time.

getFullYears() It returns the integer value that represents the year on the basis of local

time.

getHours() It returns the integer value between 0 and 23 that represents the hours on

the basis of local time.

getMilliseconds() It returns the integer value between 0 and 999 that represents the

milliseconds on the basis of local time.

getMinutes() It returns the integer value between 0 and 59 that represents the minutes

on the basis of local time.

getMonth() It returns the integer value between 0 and 11 that represents the month on

the basis of local time.

getSeconds() It returns the integer value between 0 and 60 that represents the seconds

on the basis of local time.

setDate() It sets the day value for the specified date on the basis of local time.

setDay() It sets the particular day of the week on the basis of local time.

setFullYears() It sets the year value for the specified date on the basis of local time.

setHours() It sets the hour value for the specified date on the basis of local time.
setMilliseconds() It sets the millisecond value for the specified date on the basis of local

time.

setMinutes() It sets the minute value for the specified date on the basis of local time.

setMonth() It sets the month value for the specified date on the basis of local time.

setSeconds() It sets the second value for the specified date on the basis of local time.

toString() It returns the date in the form of string.

Example: getting date and time

let d = new Date();


alert(d.getDate()); // Display the day of the month
alert(d.getDay()); // Display the number of days into the week (0-6)
alert(d.getMonth()); // Display the number of months into the year (0-11)
alert(d.getFullYear()); // Display the full year (four digits)
alert(d.getHours()); // Display the number of hours into the day (0-23)
alert(d.getMinutes()); // Display the number of minutes into the hour
(0-59)
alert(d.getSeconds()); // Display the seconds into the minute (0-59)
alert(d.getMilliseconds()); // Display the number of milliseconds into
second (0-999)
alert(d.getTime()); // Display the number of milliseconds since 1/1/1970
alert(d.getTimezoneOffset()); // Display the time-zone offset

Example: setting date and time

let d = new Date(2018, 5, 24); // June 24, 2018


d.setMonth(12); // Sets month to 12, new date will be January 24, 2019
document.write(d);

let d = new Date(2018, 5, 24); // June 24, 2018 00:00:00


d.setHours(8);
d.setMinutes(30);
d.setSeconds(45);
d.setMilliseconds(600);
document.write(d);

JavaScript Math
The JavaScript math object provides several constants and methods to perform mathematical
operation

Methods Description

cbrt() It returns the cube root of the given number.

ceil() It returns a smallest integer value, greater than or equal to the given number.

exp() It returns the exponential form of the given number.

floor() It returns largest integer value, lower than or equal to the given number.

hypot() It returns square root of sum of the squares of given numbers.

log() It returns natural logarithm of a number.

max() It returns maximum value of the given numbers.

min() It returns minimum value of the given numbers.

pow() It returns value of base to the power of exponent.

random() It returns random number between 0 (inclusive) and 1 (exclusive).

round() It returns closest integer value of the given number.

sqrt() It returns the square root of the given number

trunc() It returns an integer part of the given number.

. Example:

document.write(Math.cbrt(9) + "<br>");
document.write(Math.ceil(15.453) + "<br>");
document.write(Math.exp(9) + "<br>");
document.write(Math.floor(2.456) + "<br>");
document.write(Math.hypot(45,23) + "<br>");
document.write(Math.log(9) + "<br>");
document.write(Math.max(9,8,10,5) + "<br>");
document.write(Math.min(9,8,10,5) + "<br>");
document.write(Math.pow(2,3) + "<br>");
document.write(Math.random() + "<br>");
document.write(Math.round(14.25) + "<br>");
document.write(Math.sqrt(25) + "<br>");
document.write(Math.trunc(12.563) + "<br>");

JavaScript Number Object


The JavaScript number object enables you to represent a numeric value. It may be integer or
floating-point. JavaScript number object follows IEEE standard to represent the floating-point
numbers.

By the help of Number() constructor, you can create number object in JavaScript. For example:

var n=new Number(value);

If value can't be converted to number, it returns NaN(Not a Number) that can be checked by isNaN()
method.

JavaScript Number Methods


Let's see the list of JavaScript number methods with their description.

Methods Description

isFinite() It determines whether the given value is a finite number.

isInteger() It determines whether the given value is an integer.

parseFloat() It converts the given string into a floating point number.

parseInt() It converts the given string into an integer number.

toExponential() It returns the string that represents exponential notation of the given number.

toFixed() It returns the string that represents a number with exact digits after a decimal

point.
toPrecision() It returns the string representing a number of specified precision.

toString() It returns the given number in the form of string.

Example:

var no =1022;
document.write(Number.isFinite(453) + "<br>");
document.write(Number.isInteger(45.5) + "<br>");
document.write(no.toExponential() + "<br>");
document.write(no.toFixed(2) + "<br>");
document.write(no.toPrecision() + "<br>");

Document Object Model


The document object represents the whole html document.

When html document is loaded in the browser, it becomes a document object. It is the root element
that represents the html document. It has properties and methods. By the help of document object,
we can add dynamic content to our web page.

Properties of document object


Let's see the properties of document object that can be accessed and modified by the document
object.
Document object has following properties and methods

Properties –
cookie - Returns all name/value pairs of cookies in the document
document - Mode Returns the mode used by the browser to render the
document
domain - Returns the domain name of the server that loaded the
document
lastModified - Returns the date and time the document was last
modified
readyState - Returns the (loading) status of the document
referrer Returns the URL of the document that loaded the current
document
title - Sets or returns the title of the document
URL - Returns the full URL of the document

Example:
document.writeln (document.cookie);
document.writeln(document.documentMode);
document.writeln(document.domain);
document.writeln(document.lastModified);
document.writeln(document.readystate);
document.writeln(document.referrer);
document.writeln(document.title);
document.writeln(document.URL);

Methods of document object


We can access and change the contents of document by its methods.

The important methods of document object are as follows:

Method Description

write("string") writes the given string on the doucment.

writeln("string") writes the given string on the doucment with newline character at
the end.

getElementById() returns the element having the given id value.


getElementsByName() returns all the elements having the given name value.

getElementsByTagName() returns all the elements having the given tag name.

getElementsByClassName() returns all the elements having the given class name.

close() Closes the output stream previously opened with document.

open() Opens an output stream to collect the output from document.

Accessing field value by document object


In this example, we are going to get the value of input text by user. Here, we are using
document.form1.name.value to get the value of name field.

Here, document is the root element that represents the html document.

form1 is the name of the form.


name is the attribute name of the input text.
value is the property, that returns the value of the input text.

Let's see the simple example of document object that prints name with welcome message.

<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>

<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>

Javascript - innerHTML
The innerHTML property can be used to write the dynamic html on the html document.

It is used mostly in the web pages to generate the dynamic html such as registration form,
comment form, links etc.

Example of innerHTML property


In this example, we are going to create the html form when user clicks on the button.
<html>
<body>
<script type="text/javascript" >
function showcommentform() {
var data="Name:<br><input type='text' name='name'><br>Comment:<br><textarea rows='5'
cols='50'></textarea><br><input type='submit' value='comment'>";

document.getElementById('mylocation').innerHTML=data;
}

</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
</body>
</html>

You might also like