HTML Unit1
HTML Unit1
HTML (Hypertext Markup Language) is a markup language which is used to create web pages
HTML stands for HyperText Markup Language. It is the standard language used to create and
structure content on the web. It tells the web browser how to display text, links, images, and other
forms of multimedia on a webpage.
Versions of HTML
Original intent of HTML: General layout of documents that could be displayed by a wide variety of
computers.
HTML 1.0
HTML 2.0
• HTML 2.0 was the standard for website design until January 1997
• A cleanup of 4.0,
HTML Element
An HTML element is a basic building block to create a webpage, and It is created by a start tag,
content, and end tag
Example:
Note: Some HTML elements have no content (like the <br> element). These elements are called
empty elements. Empty elements do not have an end tag!
HTML Attributes
Attributes contain additional pieces of information. Attributes take the form of an opening tag and
additional info is placed inside.
In this instance, the image source(src) and the alt text (alt) are the attributes of <img> tags.
HTML page structure (or, HTML basic structure) consists of the essential elements that are required
to create an HTML document that can be displayed on the browser.
1. <!DOCTYPE html>:
2. <html> </html> :
The html element includes an attribute lang .Which specifies the language in which the document is
written.
<html lang=“en>
title element
meta element.
The content of the title element is displayed by the browser in the browser window’s title bar.
The meta tag specifies the character set used to write the document.
3. Body
It defines the body of the webpage, all elements that are used to display content on the browser
placed inside the body tag.
Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML Tutorial</title>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
Paragraph Tag
The tag offers a way to structure your text into different paragraphs.
Each paragraph of text should go in between an opening <p> and a closing </p> tag as shown
below in the example
Line Break Tag
Whenever you use the <br /> element, anything following it starts from the next line. This tag is an
example of an empty element, where you do not need opening and closing tags, as there is nothing
to go in between them.
Horizontal Lines
Image
The HTML <img> tag is used to embed an image in web pages by linking them. It creates a
placeholder for the image, defined by attributes like src, width, height, and alt, and does not
require a closing tag.
Insert Image
Syntax
<html>
<head>
</head>
<body>
</body>
</html>
You can set image width and height based on your requirement using width and height attributes.
You can specify width and height of the image in terms of either pixels or percentage of its actual
size.
Eg:
You can use the style attributes to specify the width and height of image
By default, image will have a border around it, you can specify border thickness in terms of pixels
using border attribute. A thickness of 0 means, no border around the picture.
Eg:
By default, image will align at the left side of the page, but you can use align attribute to set it in the
center or right.
<img src="C:\Users\s\Desktop\53.jpg" alt="Sleepy cat" border="3” align=“right”/>
We can also link an image with other page or we can use an image as a link. To do this, put <img>
tag inside the <a> tag.
Eg:
<a href=https://livelongandpawspurr.com/blog/20-cat-quotes-for-cat-lovers">
Image Formats:
It has 24-bit color representation (16 million different colors). Both use compression, but JPEG
compression is better.
Lists
HTML offers web authors three ways for specifying lists of information. All lists must contain one
or more list elements. Lists may contain −
<ul> − An unordered list. This will list items using plain bullets.
<ol> − An ordered list. This will use different schemes of numbers to list your items.
<dl> − A definition list. This arranges your items in the same way as they are arranged in a
dictionary.
An unordered list is a collection of related items that have no special order or sequence. This list is
created by using HTML <ul> tag. Each item in the list is marked with a bullet.
<html>
<body>
<ul>
<li>Aries</li>
<li>Bingo</li>
<li>Leo</li>
<li>Oracle</li>
</ul>
</body>
</html>
You can use type attribute for <ul> tag to specify the type of bullet you like. By default, it is a disc.
Following are the possible options
Eg:
<ul type="circle">
<li>Aries</li>
<li>Bingo</li>
<li>Leo</li>
<li>Oracle</li>
</ul>
HTML Table
HTML table tag is used to display data in tabular form (row * column). There can be many columns
in a row.
We can create a table to display data in tabular form, using <table> element, with the help of <tr> ,
<td>, and <th> elements.
In Each table, table row is defined by <tr> tag,
table header is defined by <th>,
and table data is defined by <td> tags.
HTML tables are used to manage the layout of the page e.g. header section, navigation bar, body
content, footer section etc..
Table Cell
Each table cell is defined by <td> and </td>
Everything between <td>and </td>is the content of the table cell
Here, the border is an attribute of <table> tag and it is used to put a border across all the cells. If
you do not need a border, then you can use border = "0".
Table Heading
Table heading can be defined using <th> tag
Headings, which are defined in <th> tag are centered and bold by default.
Tables Backgrounds
You can set table background using one of the following two ways −
bgcolor attribute − You can set background color for whole table or just for one cell.
background attribute − You can set background image for whole table or just for one cell.
You can also set border color also using bordercolor attribute.
Table Caption
The caption tag will serve as a title or explanation for the table and it shows up at the top of
the table.
Table Header, Body, and Footer
Tables can be divided into three portions − a header, a body, and a foot. The head and foot are
rather similar to headers and footers in a word-processed document that remain the same for
every page, while the body is the main content holder of the table.
The three elements for separating the head, body, and foot of a table are −
<thead> − to create a separate table header.
<tbody> − to indicate the main body of the table.
<tfoot> − to create a separate table footer.
HTML – Forms
An HTML form is a webpage section usually used for collecting data from the users and then
sent to a server for further processing.
HTML forms allow users to input data into a website or app, which can then be processed by
a server. Forms are a fundamental part of web development and are used for many tasks,
including:
Collecting user information: Such as contact details, login credentials, or search terms
Updating the interface: Such as adding items to a list or showing or hiding a feature
<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
An <input> element can be displayed in many ways, depending on the type attributes
Attributes
Following is the list of attributes for <input> tag for creating text field.
Multiple-Line Text Input Controls
This is used when the user is required to give details that may be longer than a single
sentence. Multi-line input controls are created using HTML <textarea> tag.
Password input controls
This is also a single-line text input but it masks the character as soon as a user enters it.
They are also created using HTML <input>tag but type attribute is set to password.
Example
Here is a basic example of a single-line password input used to take user password −
Checkbox Control
Checkboxes are used when more than one option is required to be selected. They are
also created using HTML <input> tag but type attribute is set to checkbox..
Example
Here is an example HTML code for a form with two checkboxes −
Radio buttons are used when out of many options, just one option is required to be selected.
They are also created using HTML <input> tag but type attribute is set to radio.
Select Box Control
A select box, also called drop down box which provides option to list down various options in
the form of drop down list, from where a user can select one or more options.
Example
Here is example HTML code for a form with one drop down box
File Upload Box
If you want to allow a user to upload a file to your web site, you will need to use a file
upload box, also known as a file select box. This is also created using the <input>
element but type attribute is set to file.
Example
Here is example HTML code for a form with one file upload box –
Attributes
Button Controls
There are various ways in HTML to create clickable buttons. You can also create a
clickable button using <input>tag by setting its type attribute to button. The type
attribute can take the following values –
Form attributes
auto-completion of text,
The action attribute of <form>element transmits the user's input to a backend script for
processing.
The method attribute determines which HTTP method should be used by the browser while
uploading the form information. The most commonly used methods are as follows:
1.GET: It is the default method for form submission, which means if we don't specify the
method name explicitly, the form will use the GET method to send data.
2. POST: It is used to send form data inside HTTP request body. It is safer than GET method.
The target attributes determines the target window or frame where the result of the script
will be displayed after submitting the form.
src
This attribute is used to give the file name that should be loaded in the frame. Its value
can be any URL. For example, src="/html/top_frame.htm" will load an HTML file
available in html directory.
name
frameborder
This attribute specifies whether or not the borders of that frame are shown; it
overrides the value given in the frameborder attribute on the <frameset> tag if one is
given, and this can take values either 1 (yes) or 0 (no).
marginwidth
This attribute allows you to specify the width of the space between the left and right of
the frame's borders and the frame's content. The value is given in pixels. For example
marginwidth="10".
marginheight
This attribute allows you to specify the height of the space between the top and
bottom of the frame's borders and its contents. The value is given in pixels. For
example marginheight="10".
scrolling
This attribute controls the appearance of the scrollbars that appear on the frame. This
takes values either "yes", "no" or "auto". For example scrolling="no" means it should
not have scroll bars.
Syntax
The target attributes attribute can have one of the following values:
HTML Features
It has introduced new multimedia features which supports both audio and video
controls by using<audio>and<video>tags.
There are new graphics elements including vector graphics and tags.
Drag and Drop- The user can grab an object and drag it further dropping it to a new
location.
Web storage facility which provides web application methods to store data on the
web browser.
CSS
Introduction
Cascading Style Sheets, commonly referred to as CSS, is a simple design language intended to
simplify the process of making web pages presentable.
• CSS handles the look and feel part of a web page.
• Using CSS, we can control the
• Color of the text.
• The style of fonts.
• The spacing between paragraphs.
• Columns are sized and laid out.
• Background images.
• Variety of other effects.
Applications of CSS
• CSS saves time - You can write CSS once and then reuse same sheet in multiple HTML
pages. You can define a style for each HTML element and apply it to as many Web pages
as you want.
• Pages load faster - If you are using CSS, you do not need to write HTML tag attributes
every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag.
So less code means faster download times.
• Easy maintenance - To make a global change, simply change the style, and all elements
in all the web pages will be updated automatically.
• Superior styles to HTML - CSS has a much wider array of attributes than HTML, so you
can give a far better look to your HTML page in comparison to HTML attributes.
• Multiple Device Compatibility - Style sheets allow content to be optimized for more
than one type of device. By using the same HTML document, different versions of a
website can be presented for handheld devices such as PDAs and cell phones or for
printing.
• Global web standards - Now HTML attributes are being deprecated and it is being
recommended to use CSS. So its a good idea to start using CSS in all the HTML pages to
make them compatible to future browsers.
CSS Versions
• Cascading Style Sheets level 1 (CSS1) came out of W3C as a recommendation in
December 1996. This version describes the CSS language as well as a simple visual
formatting model for all the HTML tags.
• CSS2 became a W3C recommendation in May 1998 and builds on CSS1. This version adds
support for media-specific style sheets e.g. printers and aural devices, downloadable
fonts, element positioning and tables.
• Inline: Style sheet appears as the values of the style attribute of a tag
An inline CSS is used to apply a unique style to a single HTML element.
General form:
property_2: value_2;
property_n: value_n;"
font-size:50px;
font-style:italic;
text-align:center;">
Inline CSS
</p>
3. External CSS
External CSS contains separate CSS files that contain only style properties with the help of
tag attributes (For example class, id, heading, ... etc). CSS property is written in a separate
file with a .css extension and should be linked to the HTML document using a link tag.
Ex:
Selector Forms
The element selector selects HTML elements based on the element name.
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.
3.Generic Selectors
• A generic class can be defined if you want a style to apply to more than one kind of tag. A
generic class must be named, and the name must begin with a period Example
4. 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.
5.Contexual selectors
• Selectors can also specify that the style should apply only to elements in certain positions in
the document .This is done by listing the element hierarchy in the selector.
Eg: body b em {font-size: 24pt ;}
• In the eg, selector applies its style to the content of emphasis elements that are descendants
of bold elements in the body of the document. It is also called as descendant selectors. It will
not apply to emphasis element not descendant of bold face element.
6.Universal Selectors
• The universal selector denoted by an asterisk(*). It applies its style to all elements in the
document
For Eg: * {color : red}
Makes all elements in the document red
6. Pseudo Classes
• Pseudo classes are styles that apply when something happens, rather than because the target
element(tag) simply exists. Names begin with colons
The style of hover pseudo classes apply when the mouse cursor is over the element.The style
of focus pseudo classes apply when an element has focus (mouse cursor over the element and
click the left mouse button)
CSS Pseudo-elements
What are Pseudo-Elements?
The following example selects all <a> elements with a target attribute:
Property Value
CSS includes 60 different properties in seven categories
• Fonts
• Lists
• Alignment of text
• Margins
• Colors
• Backgrounds
• Borders
Font Properties
We can set the following font properties of an element:
• The font-family property is used to change the face of a font.
• The font-style property is used to make a font italic or oblique.
• The font-variant property is used to create a small-caps effect.
• The font-weight property is used to increase or decrease how bold or light a font appears.
• The font-size property is used to increase or decrease the size of a font.
• The font property is used as shorthand to specify a number of other font properties.
Font Families
• The font-family property is used to specify a list of font names.
• The browser uses the first font in the list that it supports.
• Ex: font-family: Arial, Helvetica, Futura
• Above style tells the browser to use Arial if it supports that font
• If not, it will use Helvetica if it supports it. If the browser supports neither Arial nor Helvetica,
it will use Futura if it can.
• If the browser does not support any of the specified fonts, it will use an alternative of its
choosing.
• A generic font can be specified as a font-family value. The possible generic fonts and
examples of each are shown in below table.
• Each browser has a font defined for each of these generic names.
• A good approach to specifying fonts is to use a generic font as the last font in the value of a
font-family property
Font Sizes
• The font-size property does what its name implies.
Ex: • The following property specification sets the font size for text to 10 points:
• font-size: 10pt
• Many relative font-size values are defined, including xx-small, x-small, small, medium, large,
x-large, and xx-large.
• In addition, smaller or larger can be specified.
• Furthermore, the value can be a percentage relative to the current font size.
• Using the relative font sizes has the disadvantage of failing to provide strict font size control.
Different browsers can use different values for them.
• For example, small might mean 10 points on one browser and 8 points on another.
• On the other hand, using a specific font size has the risk that some browsers may not support
that particular size, causing the document to appear different on different browsers.
Font Variants
• The default value of the font-variant property is normal, which specifies the usual character
font.
• This property can be set to small-caps to specify small capital characters.
• These characters are all uppercase, but the letters that are normally uppercase are
somewhat larger than those that are normally lowercase.
Font Styles
• The font-style property is most commonly used to specify italic, as in font-style: italic
• An alternative to italic is oblique, but when displayed, the two are nearly identical, so oblique
is not a terribly useful font style. In fact, some browsers do not support it, so they display all
oblique fonts in italic.
Font Weights
• The font-weight property is used to specify the degree of boldness, as in
• font-weight: bold
• Besides bold, the values normal (the default), bolder, and lighter can be specified.
• The bolder and lighter values are taken as relative to the current level of boldness.
• Specific numbers also can be given in multiples of 100 from 100 to 900, where 400 is the
same as normal and 700 is the same as bold.
Font Shorthands
• If more than one font property must be specified, the values can be stated in a list as the
value of the font property.
• The browser then has the responsibility for determining which properties to assign from the
forms of the values.
List properties
• Two presentation details of lists can be specified in XHTML documents
• The shape of the bullets that precede the items in an unordered list and the sequencing
values
• That precedes the items in an ordered list.
• The list-style-type property is used to specify both of these.
• The list-style-type property of an unordered list can be set to below values.
• Disc (Small filled circle)
• Circle (A circle is an unfilled circle)
• Square (A square is a filled square)
• None
Ex:
Colour
• CSS uses color values to specify a color.
• Typically, these are used to set a color either for the foreground of an element (i.e., its text) or
for the background of the element.
• They can also be used to affect the color of borders and other decorative effects.
• You can specify your color values in various formats.
• Following table lists all the possible formats.
Hex Codes
• A hexadecimal is a 6 digit representation of a color.
• The first two digits (RR) represent a red value, the next two are a green value (GG), and the
last are the blue value (BB).
• A hexadecimal value can be taken from any graphics software like Adobe Photoshop,
• Jasc Paintshop Pro, or even using Advanced Paint Brush.
• Each hexadecimal code will be preceded by a pound or hash sign ‘#’.
• Following are the examples to use Hexadecimal notation. Ex: #000000, #FF0000, #00FF00
RGB Values
• This color value is specified using the rgb( ) property.
• This property takes three values, one each for red, green, and blue.
• The value can be an integer between 0 and 255 or a percentage.
Alignment of text
• The text-indent property can be used to indent the first line of a paragraph.
• This property takes either a length or a percentage value.
• The text-align property, for which the possible keyword values are • Left • Center • Right •
Justify
• The float property is used to specify that text should flow around some element, often an
image or a table.
• The possible values for float are left, right, and none, which is the default.
The Div is the most usable tag in web development because it helps us to separate out data in
the web page and we can create a particular section for particular data or function in the web
pages.
• Div tag is Block level tag
• It is a generic container tag
• It is used to the group of various tags of HTML so that sections can be created and style can
be applied to them.
• As we know Div tag is block-level tag in this example div tag contain entire width. It will be
displayed div tag each time on a new line, not on the same line.
• CSS3 stands for Cascading Style Sheet level 3, which is the advanced version of CSS. It is used for
structuring, styling, and formatting web pages.
• Several new features have been added to CSS3 and it is supported by all modern web browsers.
The most important feature of CSS3 is the splitting of CSS standards into separate modules that are
simpler to learn and use.
JavaScript
is a lightweight, interpreted programming language. It is designed for creating network-
centric applications. It is complimentary to and integrated with Java. JavaScript is very easy to
implement because it is integrated with HTML. It is open and cross-platform.
What is JavaScript?
• JavaScript is the programming language of HTML and the Web
. • JavaScript is a loosely typed language.
• JavaScript is client-side scripting language.
• JavaScript executes in the user's browser.
• JavaScript interact with html elements (DOM elements).
Why JavaScript
• JavaScript eliminates server-side processing.
• JavaScript executes on any OS.
• JavaScript can be used with any type of web page e.g. PHP, ASP.NET, Perl etc.
• JavaScript increases the performance of web page due to client-side execution
• Many JavaScript based application frameworks are available in the market to create Single
page web applications e.g. ExtJS, AngularJS, KnockoutJS etc.
Advantages of JavaScript
• An interpreted language
• Embedded within HTML
• Minimal Syntax and easy to learn.
• Quick Development.
• Designed for simple and small programs.
• High Performance.
• Procedural capabilities.
• Event driven.
• Easy debugging and testing.
• Platform independent and Architectural neutral.
Uses of JavaScript
• The JavaScript was initially introduced to provide programming capability at both the server
and client ends of web connection.
• JavaScript therefore is implemented at 2 ends:
• Client end • Server end
• The client side JavaScript is embedded in XHTML documents and is interpreted by the
browser
• It also provides some means of computation, which serves as an alternative for some tasks
done at the server side
• Interactions with users through form elements, such as buttons and menus, can be
conveniently described in JavaScript. Because button clicks and mouse movements are easily
detected with JavaScript, they can be used to trigger computations and provide feedback to the
user.
• For example, when a user moves the mouse cursor from a text box, JavaScript can detect that
movement and check the appropriateness of the text box’s value (which presumably was just
filled by the user).
• Even without forms, user interactions are both possible and simple to program in
JavaScript. These interactions, which take place in dialog windows, include getting input
from the user and allowing the user to make choices through buttons. It is also easy to
generate new content in the browser display dynamically.
• This transfer of task ensures that the server is not overloaded and performs only required
task
• But client side JavaScript cannot replace serves side JavaScript; because serrver side software
supports file operations, database access, security, networking etc
JavaScript is also used as an alternative to java applets.
• Programming in JavaScript is much simpler than compared to java
• JavaScript support DOM [Document Object Model] which enables JavaScript to access and
modify CSS properties and content of any element of a displayed XHTML document
• Identifier form: begin with a letter or underscore, or dollar sign ($) followed by any
number of letters, underscores, and digits
• Case sensitive
• 25 reserved words, plus future reserved words Eg: Break, continue, switch, case, if ,else,
while, for…
• Comments: both // and /* … */
• Scripts are usually hidden from browsers that do not support JavaScript interpreters by
putting them in special comments.
Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords, variables,
function names, and any other identifiers must always be typed with a consistent capitalization
of letters. So the identifiers Time and TIME will convey different meanings in JavaScript.
Comments in JavaScript
JavaScript supports both C-style and C++-style comments. Thus: · Any text between a // and
the end of a line is treated as a comment and is ignored by JavaScript. · Any text between the
characters /* and */ is treated as a comment. This may span multiple lines.
Primitives, Operations, & Expressions
1.Primitive Types
Five primitive types: Number, String, Boolean, Undefined, or Null.
Javascript includes predefined objects that are closely related to primitive types named
Number ,string and Boolean.
These objects are called wrapper objects. Because each objects contains a property that stores
a value of the corresponding primitive type.
The purpose of Wrapper objects are used to provide properties and methods that are
convenient to use with the values of primitive types
The methods of Number and String objects can be used on variables of the corresponding
primitive types.
The difference between primitives and objects Suppose that prim is a primitive variable with
the value 17 and obj is a Number object with property value 17.
prim and obj are stored differently
4.Declaring variables
Like many other programming languages, JavaScript has variables. Variables can be thought of
as named containers. You can place data into these containers and then refer to the data simply
by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared
with the var keyword as follows.
3. Assignment Operator
Math Object
• Math Object provides collection of properties of Number objects and methods that
operate on Number objects. The math object has methods for the trignometric functions
such as sin(for sine) and cos(for cosine) as well as commonly used math operations such
as floor, round, max, min
• Floor-truncate a number , round- to round a number,max –returns the largest of two
numbers.
• All of the math methods are referenced through the Math object.
e.g., Math.cos(x)
JavaScript String Operators
The + operator can also be used to add (concatenate) strings.
txt1 = “smitha";
txt2 = “jacob";
txt3 = txt1 + " " + txt2;
o/p
smitha Jacob
txt1 = "What a very "; txt1 += "nice day";
o/p
What a very nice day
We will discuss two operators here that are quite useful in JavaScript: the conditional
operator (? :) and the typeof operator.
• Conditional Operator (? :) The conditional operator first evaluates an expression for a
true or false value and then executes one of the two given statements depending upon
the result of the evaluation.
• typeof Operator
JavaScript typeof operator is used to find the type of a JavaScript variable. The typeof operator
returns the type of a variable or an expression. Returns "number", "string", or "boolean" for
Number, String, or Boolean, "undefined" for Undefined,"function" for functions, and "object"
for objects and NULL . Objects do not have types. If the operand is a variable that has not been
assigned a value ‘typeof’ produces ‘undefined’ .
• typeof "" // Returns "string“
• typeof "John“ // Returns "string"
• typeof "John Doe“ // Returns "string“
• typeof 0 // Returns "number"
• typeof 314 // Returns "number"
• typeof 3.14 // Returns "number“
• typeof (3) // Returns "number"
• typeof (3 + 4) // Returns "number
Using document.write()
• document.write() for writing
Example
<html>
<body>
<h1>my paragraph</h1>
<p>fjhjdskhfjhdfkjhfjkj</p>
<script type="text/javascript">
document.write("helllo.......");
</script>
</body</html>
The Window object has three methods for creating dialog boxes for user interactions , alert,
confirm , and prompt
Alert Box
• An alert box is often used if you want to make sure information comes through to the user. •
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax: window.alert("sometext");
The window.alert() method can be written without the window prefix.
Eg’;
<html lang =“en”>
<head><title>hi.html</title>
<meta charset = “utf-8” />
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Confirm Box
• A confirm box is often used if you want the user to verify or accept something.
• When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed
if the user clicks "OK", the box returns true.
• If the user clicks "Cancel", the box returns false.
Syntax: window.confirm("sometext");
The window.confirm() method can be written without the window prefix.
Prompt Box
• A prompt box is often used if you want the user to input a value before entering a page.
• When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed
after entering an input value.
• If the user clicks "OK" the box returns the input value.
• If the user clicks "Cancel" the box returns null.
Syntax window.prompt("sometext","defaultText");
The window.prompt() method can be written without the window prefix.
</html>
1. Using if Statement
The if statement is used to evaluate a particular condition. If the condition holds true, the
associated code block is executed.
In JavaScript we have the following conditional statements:
The if Statement
Syntax
• if (condition) {
// block of code to be executed if the condition is true
}
Ex:
<script>
let a=90,b=50;
if(a<b)
document.write("a is gerater");
</script>
The else statement to specify a block of code to be executed if the condition is false.
Syntax
• 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
}
Ex:
3. else if Statement
The else if statement in JavaScript allows handling multiple possible conditions and outputs,
evaluating more than two options based on whether the conditions are true or 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
}
ex:
3. 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
}
4. 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
}
JavaScript Loops
• Expression 1 is executed (one time) before the execution of the code block.
• Expression 3 is executed (every time) after the code block has been executed.
Ex: <script>
document.write(text);
</script>
• The for...in loop in JavaScript is used to loop through an object's properties. The
JavaScript for...in loop is a variant of the for loop.
• The for loop can't be used to traverse through the object properties. So, the for...in
loop is introduced to traverse through all object properties.
Syntax
document.getElementById("demo").innerHTML = txt;
</script>
The for...of loop in JavaScript is used to traverse elements of the iterable object.
• Syntax
<p id="demo"></p>
<script>
text += x + "<br>";
document.getElementById("demo").innerHTML = text;
</script>
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
}
Ex:
let i = 0;
i++;
document.write(text);
</script>
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);
Ex:
do {
text += "The number is " + i;
i++;
}
while (i < 10);