Professional Documents
Culture Documents
Question Bank IAT - 1 Portion IP
Question Bank IAT - 1 Portion IP
It didn’t support audio and video without the It supports audio and video controls with
use of flash player support. the use of <audio> and <video> tags.
It uses cookies to store temporary data. It uses SQL databases and application
cache to store offline data.
Does not allow JavaScript to run in browser. Allows JavaScript to run in background.
This is possible due to JS Web worker
API in HTML5.
Vector graphics is possible in HTML with the Vector graphics is additionally an integral
help of various technologies such as VML, a part of HTML5 like SVG and canvas.
Silver-light, Flash, etc.
It does not allow drag and drop effects. It allows drag and drop effects.
Not possible to draw shapes like circle, HTML5 allows to draw shapes like circle,
rectangle, triangle etc. rectangle, triangle etc.
It works with all old browsers. It supported by all new browser like
Firefox, Mozilla, Chrome, Safari, etc.
Older version of HTML are less mobile- HTML5 language is more mobile-
friendly. friendly.
Doctype declaration is too long and Doctype declaration is quite simple and
complicated. easy.
Elements like nav, header were not present. New element for web structure like nav,
header, footer etc.
Character encoding is long and complicated. Character encoding is simple and easy.
It is almost impossible to get true GeoLocation One can track the GeoLocation of a user
of user with the help of browser. easily by using JS GeoLocation API.
Attributes like charset, async and ping are Attributes of charset, async and ping are a
absent in HTML. part of HTML 5.
6.Give the core syntax of CSS. Mention the need and types of CSS.
It consists of two parts:
Selector - the part before the left curly brace
Declaration - the part within the curly braces
The selector is the link between the HTML document and the style. It specifies what
elements are affected by the declaration. The declaration is that part of the rule that
sets forth what the effect will be. In the example above, the selector is h1 and the
declaration is "color: green." Hence, all h1 elements will be affected by the
declaration, that is, they will be turned green.
CSS is a style sheet language used for describing the presentation of a document
written in a markup language like HTML.
7.Brief CSS and List the features.
Cascading Style Sheet(CSS) is used to set the style in web pages which contain
HTML elements. It sets the background color, font-size, font-family, color, … etc
property of elements in a web pages. There are three types of CSS Inline CSS,
Internal CSS and External CSS.
An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
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
8.What do you understand about DOCTYPE and Comment in HTML?
All HTML need to have a DOCTYPE declared. The DOCTYPE is not actually an
element or HTML tag. It lets the browser know how the document should be
interpreted, by indicating what version or standard of HTML (or other markup
language) is being used.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
Comment is a piece of code which is ignored by any web browser. It is a good
practice to add comments into your HTML code, especially in complex documents, to
indicate sections of a document, and any other notes to anyone looking at the code.
Comments help you and others understand your code and increases code readability.
HTML comments are placed in between <!-- ... --> tags. So, any content placed with-
in <!-- ... --> tags will be treated as comment and will be completely ignored by the
browser.
9.List the different types of transformation elements in HTML 5
The transform property applies a 2D or 3D transformation to an element. This
property allows you to rotate, scale, move, skew, etc., elements.
Value Description
translateX(x) Defines a translation, using only the value for the X-axis
translateY(y) Defines a translation, using only the value for the Y-axis
translateZ(z) Defines a 3D translation, using only the value for the Z-axis
PART B
1. Explain the working principle of web server and Client with neat sketch. (8)
The Internet acts as a source of plethora of information to us and all we need to do, if
we want any information is to just query the internet and then we will get the desired
response.
But who provides this information to us and how? All this is facilitated by what is
called as the Web Server. Along with it there are browsers as applications which we
use such as Internet Explorer, Mozilla Firefox, Chrome, Safari etc to interact with the
web and browse & retrieve the files on web server known as Web Clients.
Web Servers are basically simple computer programs that dispense the web page
when they are requested using the web client. The machines on which this program
run are usually called as a server, with both the names web server and server almost
used interchangeably.
Generally, many people, when they think of web servers, they think of them being
some high-powered computers, while this is correct to some extent, as some high-
powered computers are also called as web servers, but these computers are built with
the purpose of web hosting . In web hosting, the web servers enable the hosting
providers to handle multiple domains (or multiple websites) on a single server. But,
normally, when someone refers to a web server, it means the piece of software that
can be downloaded on the computer system.
When is web server required?
Generally, web servers are used by web hosting companies and professional web app
developers. But, actually anyone who satisfies one of the below category can use it-
One who owns a website (to make the local copy on their system resemble
what is on internet).
One who wants to use server-side technologies, such as, PHP or ColdFusion,
can also use the web server.
How Web servers work?
A page on internet can be viewed, when the browser requests it from the web server
and the web server responds with that page. A simple diagrammatic representation of
this is as given below in the figure:
Simple process consists of 4 steps, they are:
1. Obtaining the IP Address from domain name: Our web browser first
obtains the IP address the domain name (for e.g., for this page the domain name
is www.geeksforgeeks.org) resolves to. It can obtain the IP address in 2 ways-
By searching in its cache.
By requesting one or more DNS (Domain Name System) Servers.
Note: Any website is assigned an IP address when it is first created on web server.
2. Browser requests the full URL : After knowing the IP Address, the browser
now demands a full URL from the web server.
3. Web server responds to request: The web server responds to the browser by
sending the desired pages, and in case, the pages do not exist or some other error
occurs, it will send the appropriate error message.
For example:
You may have seen Error 404, while trying to open a webpage, which is the message
sent by the server when the page does not exist.
Another common one is Error 401 when access is denied to us due to incorrect
credentials, like username or password, provided by us.
4. Browser displays the web page: The Browser finally gets the webpages and
displays it, or displays the error message.
Popular Web Servers
There are quite a few web servers available, like, Apache, Microsoft IIS, Nginx Web
Server, LightSpeed Web Server. But, the two most popular ones are-
1. Apache HTTP Server:It is the most popular web server available and is
widely used. It is developed and maintained by Apache Software Foundation.
The Software is produced under the Apache Licence, which makes it free and
open source.
It is available for a variety of operating Systems- Windows, Mac OS X, Unix,
Linux, Solaris, Novell Netware and FreeBSD.
2. Microsoft Internet Information Service: Microsoft IIS (Internet Information
Service) is the second most popularly used web server, and its market share is
increasing quite rapidly with each passing day and is likely to overhaul Apache
in the upcoming years.
IIS server has all the features just like Apache, but it is not open source. It is
developed, and maintained by Microsoft, thus it works with all the Windows
operating system platforms.
2.State and explain the various HTML elements in detail.(8)
The basic elements of an HTML page are:
The next few pages will give an overview of these basic HTML elements.
Each element can also have attributes - each element has a different set of attributes
relevant to the element. There are a few global elements, the most common of them
are:
id - Denotes the unique ID of an element in a page. Used for locating elements
by using links, JavaScript, and more.
class - Denotes the CSS class of an element. Explained in the CSS
Basics tutorial.
style - Denotes the CSS styles to apply to an element. Explained in the CSS
Basics tutorial.
data-x attributes - A general prefix for attributes that store raw information for
programmatic purposes. Explained in detailed in the Data Attributes section.
3. Describe the structure of the HTTP request and response message. (8)
HTTP messages are how data is exchanged between a server and a client. There are
two types of messages: requests sent by the client to trigger an action on the server,
and responses, the answer from the server.
HTTP messages are composed of textual information encoded in ASCII, and span
over multiple lines. In HTTP/1.1, and earlier versions of the protocol, these messages
were openly sent across the connection. In HTTP/2, the once human-readable
message is now divided up into HTTP frames, providing optimization and
performance improvements.
Web developers, or webmasters, rarely craft these textual HTTP messages
themselves: software, a Web browser, proxy, or Web server, perform this action.
They provide HTTP messages through config files (for proxies or servers), APIs (for
browsers), or other interfaces.
The HTTP/2 binary framing mechanism has been designed to not require any
alteration of the APIs or config files applied: it is broadly transparent to the user.
HTTP requests, and responses, share similar structure and are composed of:
A start-line describing the requests to be implemented, or its status of whether
successful or a failure. This start-line is always a single line.
An optional set of HTTP headers specifying the request, or describing the body
included in the message.
A blank line indicating all meta-information for the request have been sent.
An optional body containing data associated with the request (like content of an
HTML form), or the document associated with a response. The presence of the body
and its size is specified by the start-line and HTTP headers.
The start-line and HTTP headers of the HTTP message are collectively known as
the head of the requests, whereas its payload is known as the body.
HTTP Requests
Start line
HTTP requests are messages sent by the client to initiate an action on the server.
Their start-line contain three elements:
An HTTP method, a verb (like GET, PUT or POST) or a noun
(like HEAD or OPTIONS), that describes the action to be performed. For
example, GET indicates that a resource should be fetched or POST means that data is
pushed to the server (creating or modifying a resource, or generating a temporary
document to send back).
The request target, usually a URL, or the absolute path of the protocol, port, and
domain are usually characterized by the request context. The format of this request
target varies between different HTTP methods. It can be
An absolute path, ultimately followed by a '?' and query string. This is the most
common form, known as the origin form, and is used with GET, POST, HEAD,
and OPTIONS methods.
POST / HTTP/1.1
GET /background.png HTTP/1.0
HEAD /test.html?query=alibaba HTTP/1.1
OPTIONS /anypage.html HTTP/1.0
A complete URL, known as the absolute form, is mostly used with GET when
connected to a proxy.
GET http://developer.mozilla.org/en-US/docs/Web/HTTP/Messages HTTP/1.1
The authority component of a URL, consisting of the domain name and optionally the
port (prefixed by a ':'), is called the authority form. It is only used
with CONNECT when setting up an HTTP tunnel.
CONNECT developer.mozilla.org:80 HTTP/1.1
The asterisk form, a simple asterisk ('*') is used with OPTIONS, representing the
server as a whole.
OPTIONS * HTTP/1.1
The HTTP version, which defines the structure of the remaining message, acting as an
indicator of the expected version to use for the response.
Headers
HTTP headers from a request follow the same basic structure of an HTTP header: a
case-insensitive string followed by a colon (':') and a value whose structure depends
upon the header. The whole header, including the value, consist of one single line,
which can be quite long.
There are numerous request headers available. They can be divided in several groups:
General headers, like Via, apply to the message as a whole.
Request headers, like User-Agent, Accept-Type, modify the request by specifying it
further (like Accept-Language), by giving context (like Referer), or by conditionally
restricting it (like If-None).
Entity headers, like Content-Length which apply to the body of the request.
Obviously, there is no such header transmitted if there is no body in the request.
Body
The final part of the request is its body. Not all requests have one: requests fetching
resources, like GET, HEAD, DELETE, or OPTIONS, usually don't need one. Some
requests send data to the server in order to update it: as often the case
with POST requests (containing HTML form data).
Bodies can be broadly divided into two categories:
Single-resource bodies, consisting of one single file, defined by the two
headers: Content-Type and Content-Length.
Multiple-resource bodies, consisting of a multipart body, each containing a different
bit of information. This is typically associated with HTML Forms.
HTTP Responses
Status line
The start line of an HTTP response, called the status line, contains the following
information:
The protocol version, usually HTTP/1.1.
A status code, indicating success or failure of the request. Common status codes
are 200, 404, or 302
A status text. A brief, purely informational, textual description of the status code to
help a human understand the HTTP message.
A typical status line looks like: HTTP/1.1 404 Not Found.
Headers
HTTP headers for responses follow the same structure as any other header: a case-
insensitive string followed by a colon (':') and a value whose structure depends upon
the type of the header. The whole header, including its value, presents as a single line.
There are numerous response headers available. These can be divided into several
groups:
General headers, like Via, apply to the whole message.
Response headers, like Vary and Accept-Ranges, give additional information about
the server which doesn't fit in the status line.
Entity headers, like Content-Length, apply to the body of the response. Typically, no
such headers are transmitted when there is no body in the response.
Body
The last part of a response is the body. Not all responses have one: responses with a
status code, like 201 or 204, usually don't.
Bodies can be broadly divided into three categories:
Single-resource bodies, consisting of a single file of known length, defined by the two
headers: Content-Type and Content-Length.
Single-resource bodies, consisting of a single file of unknown length, encoded by
chunks with Transfer-Encoding set to chunked.
Multiple-resource bodies, consisting of a multipart body, each containing a different
section of information. These are relatively rare.
What is HTTP?
The Hypertext Transfer Protocol (HTTP) is designed to enable communications
between clients and servers.
HTTP works as a request-response protocol between a client and server.
A web browser may be the client, and an application on a computer that hosts a web
site may be the server.
Example: A client (browser) submits an HTTP request to the server; then the server
returns a response to the client. The response contains status information about the
request and may also contain the requested content.
HTTP Methods
GET
POST
PUT
HEAD
DELETE
PATCH
OPTIONS
The GET Method
GET is used to request data from a specified resource.
GET is one of the most common HTTP methods.
Note that the query string (name/value pairs) is sent in the URL of a GET request:
/test/demo_form.php?name1=value1&name2=value2
Some other notes on GET requests:
GET requests can be cached
GET requests remain in the browser history
GET requests can be bookmarked
GET requests should never be used when dealing with sensitive data
GET requests have length restrictions
GET requests are only used to request data (not modify)
History Parameters remain in browser Parameters are not saved in browser history
history
Restrictions on Only ASCII characters allowed No restrictions. Binary data is also allowed
data type
Security GET is less secure compared to POST is a little safer than GET because the
POST because data sent is part parameters are not stored in browser history
of the URL or in web server logs
Visibility Data is visible to everyone in the Data is not displayed in the URL
URL
GET Example
<!DOCTYPE html>
<html>
<body>
<p>After you submit, notice that the form values is visible in the address bar of the
new browser tab.</p>
</body>
</html>
OUTPUT
First name:
Mickey
Last name:
Mouse
Submit
After you submit, notice that the form values is visible in the address bar of
the new browser tab.
POST Example
<!DOCTYPE html>
<html>
<body>
<p>Click on the submit button, and the form will be submittied using the POST
method.</p>
</body>
</html>
First name:
Last name:
Submit
Click on the submit button, and the form will be submittied using the POST
method.
5.Develop an interactive web page for student registration using HTML form
elements (8)
<html>
<head>
<script type="text/javascript" src="validate.js"></script>
</head>
<body>
<form action="#" name="StudentRegistration" onSubmit="return(validate());">
<table cellpadding="2" width="20%" bgcolor="99FFFF" align="center"
cellspacing="2">
<tr>
<td colspan=2>
<center><font size=4><b>Student Registration Form</b></font></center>
</td>
</tr>
<tr>
<td>Name</td>
<td><input type=text name=textnames id="textname" size="30"></td>
</tr>
<tr>
<td>Father Name</td>
<td><input type="text" name="fathername" id="fathername"
size="30"></td>
</tr>
<tr>
<td>Postal Address</td>
<td><input type="text" name="paddress" id="paddress" size="30"></td>
</tr>
<tr>
<td>Personal Address</td>
<td><input type="text" name="personaladdress"
id="personaladdress" size="30"></td>
</tr>
<tr>
<td>Sex</td>
<td><input type="radio" name="sex" value="male" size="10">Male
<input type="radio" name="sex" value="Female" size="10">Female</td>
</tr>
<tr>
<td>City</td>
<td><select name="City">
<option value="-1" selected>select..</option>
<option value="New Delhi">NEW DELHI</option>
<option value="Mumbai">MUMBAI</option>
<option value="Goa">GOA</option>
<option value="Patna">PATNA</option>
</select></td>
</tr>
<tr>
<td>Course</td>
<td><select name="Course">
<option value="-1" selected>select..</option>
<option value="B.Tech">B.TECH</option>
<option value="MCA">MCA</option>
<option value="MBA">MBA</option>
<option value="BCA">BCA</option>
</select></td>
</tr>
<tr>
<td>District</td>
<td><select name="District">
<option value="-1" selected>select..</option>
<option value="Nalanda">NALANDA</option>
<option value="UP">UP</option>
<option value="Goa">GOA</option>
<option value="Patna">PATNA</option>
</select></td>
</tr>
<tr>
<td>State</td>
<td><select Name="State">
<option value="-1" selected>select..</option>
<option value="New Delhi">NEW DELHI</option>
<option value="Mumbai">MUMBAI</option>
<option value="Goa">GOA</option>
<option value="Bihar">BIHAR</option>
</select></td>
</tr>
<tr>
<td>PinCode</td>
<td><input type="text" name="pincode" id="pincode" size="30"></td>
</tr>
<tr>
<td>EmailId</td>
<td><input type="text" name="emailid" id="emailid" size="30"></td>
</tr>
<tr>
<td>DOB</td>
<td><input type="text" name="dob" id="dob" size="30"></td>
</tr>
<tr>
<td>MobileNo</td>
<td><input type="text" name="mobileno" id="mobileno" size="30"></td>
</tr>
<tr>
<td><input type="reset"></td>
<td colspan="2"><input type="submit" value="Submit Form" /></td>
</tr>
</table>
</form>
</body>
</html>
Form Validation
function validate()
{
if( document.StudentRegistration.textnames.value == "" )
{
alert( "Please provide your Name!" );
document.StudentRegistration.textnames.focus() ;
return false;
}
if( document.StudentRegistration.fathername.value == "" )
{
alert( "Please provide your Father Name!" );
document.StudentRegistration.fathername.focus() ;
return false;
}
return false;
}
if( document.StudentRegistration.District.value == "-1" )
{
alert( "Please provide your Select District!" );
return false;
}
if( document.StudentRegistration.State.value == "-1" )
{
alert( "Please provide your Select State!" );
return false;
}
if( document.StudentRegistration.pincode.value == "" ||
isNaN( document.StudentRegistration.pincode.value) ||
document.StudentRegistration.pincode.value.length != 6 )
{
alert( "Please provide a pincode in the format ######." );
document.StudentRegistration.pincode.focus() ;
return false;
}
var email = document.StudentRegistration.emailid.value;
atpos = email.indexOf("@");
dotpos = email.lastIndexOf(".");
if (email == "" || atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.StudentRegistration.emailid.focus() ;
return false;
}
if( document.StudentRegistration.dob.value == "" )
{
alert( "Please provide your DOB!" );
document.StudentRegistration.dob.focus() ;
return false;
}
if( document.StudentRegistration.mobileno.value == "" ||
isNaN( document.StudentRegistration.mobileno.value) ||
document.StudentRegistration.mobileno.value.length != 10 )
{
alert( "Please provide a Mobile No in the format 123." );
document.StudentRegistration.mobileno.focus() ;
return false;
}
return( true );
}
Output:
6.Demonstrate a java script to display the welcome message using the alert
whenever button of a html form is pressed. (8)
<!--Display Alert Message on Button Click Event.-->
<html>
<head>
<title>Display Alert Message on Button Click Event.</title>
<script type="text/javascript">
function showMessage(){
alert("Hello friends, this is message.");
}
</script>
</head>
<body>
<center>
<h1>Display Alert Message on Button Click Event.</h1>
<b>Click on button to display message: </b><br><br>
<input type="button" id="btnShowMsg" value="Click Me!"
onClick='showMessage()'/>
</center>
</body>
</html>
Result
Basic Validation − First of all, the form must be checked to make sure all the
mandatory fields are filled in. It would require just a loop through each field in the
form and check for data.
Data Format Validation − Secondly, the data that is entered must be checked for
correct form and value. Your code must include appropriate logic to test correctness
of data.
Example
We will take an example to understand the process of validation. Here is a simple
form in html format.
Live Demo
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit =
"return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>
<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>
<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
</form>
</body></html>
OUTPUT
8. Create a webpage using background-image property where the code has to
written in XHTML (8)
<!DOCTYPE html>
<html>
<style>
body {
background-image: url('img_girl.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
</style>
<body>
<h2>Background Cover</h2>
<p>Set the background-size property to "cover" and the background image will cover
the entire element, in this case the BODY element.</p>
</body>
</html>
External CSS: External CSS contains separate CSS file which contains only style
property with the help of tag attributes (For example class, id, heading, … etc). CSS
property written in a separate file with .css extension and should be linked to the
HTML document using link tag. This means that for each element, style can be set
only once and that will be applied across web pages.
Example: The file given below contains CSS property. This file save with .css
extension. For Ex: geeks.css
body {
background-color:powderblue;
}
.main {
text-align:center;
}
.GFG {
color:#009900;
font-size:50px;
font-weight:bold;
}
#geeks {
font-style:bold;
font-size:20px;
}
Below is the HTML file that is making use of the created external style sheet
link tag is used to link the external style sheet with the html webpage.
href attribute is used to specify the location of the external style sheet file.
filter_none
edit
play_arrow
brightness_4
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="geeks.css"/>
</head>
<body>
<div class = "main">
<div class ="GFG">GeeksForGeeks</div>
<div id ="geeks">
A computer science portal for geeks
</div>
</div>
</body>
</html>
10.Write and discuss HTML using image tag, font tag, hyperlink tag
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Attributes
Attribute Value Description
crossorigin anonymous Allow images from third-party sites that allow cross-origin
use-credentials access to be used with canvas
srcset URL Specifies the URL of the image to use in different situations
Font Tag
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Attributes
Attribute Value Description
<a href="https://www.w3schools.com">Visit W3Schools.com!</a>
Attributes
Attribute Value Description
href URL Specifies the URL of the page the link goes
to
11. Write a Java script to find the Prime number between 1 and 100
<script>
function primeNumbers(num) {
document.write('<table>');
if (num < 2)
return false;
for (var i = 2; i < num; i++) {
if (num % i == 0)
return false;
}
return true;
}
document.write('<tr>');
var counter = 0;
for (var i = 0; i < 100; i++) {
if (primeNumbers(i)) {
if (counter % 10 == 0) {
document.write('</tr><tr>');
counter = 0;
}
counter++;
document.write('<td>' + i + '</td>');
}
}
document.write('</table>');</script>
12. Demonstrate a java script to display the welcome message using the alert
whenever button of a html form is pressed
<script>
function display_alert()
{
alert("Welcome to java script");
}
</script>
<body>
<input type="button" onclick="display_alert()" value="Display alert box">
</body>
13. Create a form in HTML5 to provide the list of grocery for the month from the list
in the website. Create using forms, lables, text boxes, lists. Allow the user to enter his
details to get the grocery delivered to his house.
<html>
<head>
<title>Grocery List</title>
</head>
<body>
<p id="newItemLabel">Add a New Item:</p>
<form>
<input type="text" name="itemName" id="itemName" value="Item
Name"/>
<input type="text" name="itemAmount" id="itemAmount" value="Item
Amount"/>
<select>
<option value="Other">Other</option>
<option value="Vegetables">Vegetables</option>
<option value="Fruits">Fruits</option>
<option value="Grains">Grains</option>
<option value="Canned Goods">Canned Goods</option>
<option value="Snacks">Snacks</option>
<option value="Beverages">Beverages</option>
<option value="Meat">Meat</option>
<option value="Dairy">Dairy</option>
<option value="Frozen">Frozen</option>
<option value="Household">Household</option>
</select>
<input type="button" value="add" id="addButton" onClick=""
name="add"/>
</form>
</body>
</html>
14. Describe the data types, functions and objects in JavaScript with an example. (8)
JavaScript provides different data types to hold different types of values. There are
two types of data types in JavaScript.
Primitive data type
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.
Data Type Description
var a=40;//holding number
var b="Rahul";//holding string
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript.
JavaScript is template based not class based. Here, we don't create class to get the
object. But, we direct create objects.
object={property1:value1,property2:value2.....propertyN:valueN}
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
var objectname=new Object();
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
Function
A function is a group of reusable code which can be called anywhere in your program.
This eliminates the need of writing the same code again and again. It helps
programmers in writing modular codes. Functions allow a programmer to divide a big
program into a number of small and manageable functions.
Like any other advanced programming language, JavaScript also supports all the
features necessary to write modular code using functions. You must have seen
functions like alert() and write() in the earlier chapters. We were using these functions
again and again, but they had been written in core JavaScript only once.
Function Definition
Before we use a function, we need to define it. The most common way to define a
function in JavaScript is by using the function keyword, followed by a unique
function name, a list of parameters (that might be empty), and a statement block
surrounded by curly braces.
Syntax
The basic syntax is shown here.
<script type = "text/javascript">
<!--
function functionname(parameter-list) {
statements
}
//-->
</script>
Example
Try the following example. It defines a function called sayHello that takes no
parameters −
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello there");
}
//--></script>
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write
the name of that function as shown in the following code.
<html>
<head>
<script type = "text/javascript">
function sayHello() {
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body></html>
Output
Function Parameters
Till now, we have seen functions without parameters. But there is a facility to pass
different parameters while calling a function. These passed parameters can be
captured inside the function and any manipulation can be done over those parameters.
A function can take multiple parameters separated by comma.
Example
Try the following example. We have modified our sayHello function here. Now it
takes two parameters.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body></html>
Output
The return Statement
A JavaScript function can have an optional return statement. This is required if you
want to return a value from a function. This statement should be the last statement in a
function.
For example, you can pass two numbers in a function and then you can expect the
function to return their multiplication in your calling program.
Example
Try the following example. It defines a function that takes two parameters and
concatenates them before returning the resultant in the calling program.
<html>
<head>
<script type = "text/javascript">
function concatenate(first, last) {
var full;
full = first + last;
return full;
}
function secondFunction() {
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body></html>