Unit 2
Unit 2
UNIT – II
INTRODUCTION TO JAVASCRIPT:
Static web pages are useful and can be informative. A number of technologies have been
developed that enable the creation of web applications rather than static web pages. The java
programming language is probably the best known such technology. Few programming languages
other than java have been adapted for use in client-side web applications. One such language that is
used in programming client-side web applications is javascript.
Javascript originates from a language called Live Script and was developed by Sun
microsystems and Netscape navigator. Scripts are small pieces of code which accomplish a single
relatively simple task. Javascript is a scripting language that is used for the development of Client-
side-in-browser applications. Javascript is a simple script based language which is only suitable for
fairly simple tasks. Javascript is a language that is best suited to tasks that run for a short time. Most
of the developers experience problems when they try to build web pages which have embedded
javascript.
What is JavaScript?
JavaScript was designed to add interactivity to HTML pages
JavaScript is a scripting language
A scripting language is a lightweight programming language
JavaScript is usually embedded directly into HTML pages
JavaScript is an interpreted language (means that scripts execute without preliminary
compilation)
Everyone can use JavaScript without purchasing a license
Important things about Javascript:
1. Javascript is embedded into HTML:
Javascript code is usually embedded into HTML code and is executed within the HTML
document. Javascript has no user interface and it relies on HTML to provide a means of interaction
with the users. Most of the javascript objects have HTML tags and provide event- driven code to
execute it.
2. Javascript is browser dependent:
Javascript depends on the web browser to support it. If the browser does not support it javascript
will be ignored. Javascript was given support from I.E 3.0 & N.N 2.0 onwards.
Department of Computer Science
3. Javascript is an interpreted language:
Javascript is interpreted at runtime by the browser before it is executed. It is not compiled into a
separate program like .exe but remains part of HTML file.
4. Javascript is a loosely typed language:
Javascript is very flexible when compared to java. There is no need to specify the data type of a
variable while declaring it. We can declare variables whenever it is necessary i.e., variables can be
declared explicitly.
5. Javascript is an object-based language:
Javascript is an object-based language that means that we can work with objects that encapsulate
data and behaviour. However, javascript object model is instance based and there is no inheritance.
6. Javascript is Event-Driven:
HTML objects such as buttons are enhanced to support event handlers. We can specify
functionality.
7. Javascript is not Java:
Java is object oriented language, whereas javascript is object-based, interpreted, loosely- typed
language meant for creating scripts.
8. Javascript is multi functional:
Javascript can be used to:
Enhance HTML pages.
Develop client-side applications.
Build to a certain extent client/server web applications.
Create extensions to a web server.
Provide database connectivity without using CGI.
9. Javascript language spans context:
Javascript can be used in server side Netscape live wire pro environment and microsoft’s Active
X server framework. It is not just a client side scripting tool.
Benefits of Javascript:
• It is widely supported in web browsers.
• It gives easy access to the document objects and can manipulate most of them.
• Javascript can give interesting animations without long download times associated with any
multimedia data types.
• Web surfers do not need any special plug-in to use your scripts.
Department of Computer Science
• Javascript is relatively secure i.e., javascript can neither read from a local hard drive nor write to it
and we cannot get a virus directly from javascript.
Javascript Basics:
Javascript programs contain variables, objects and functions. The key points that we need to apply in all
scripts are:
• Each line of code is terminated by semicolon.
• Blocks of code must be surrounded by a pair of curly braces. A block of code is a set of instructions
that are to be executed together as a unit.
• Functions have parameters which are passed inside parentheses.
• Variables are declared using keyword “var”.
• Scripts neither require a main function nor an exit condition. Execution of scripts starts with the first
line of code and runs until there is no more code.
Javascript Syntax:
Javascript need to be included in a HTML page. We cannot execute these scripts from a command line
as the interpreter is part of the browser. The script is included in the web page and run by the browser,
usually as soon as the page has been loaded. The browser is able to debug the script and can display
errors.
Javascript is embedded in HTML using <SCRIPT> element. Usually <SCRIPT> is included in <HEAD>
element.
A simple javascript code:
<html>
<head>
<title>Javascript</title>
<script language=“javascript”>
document.write(“Welcome to Javascript”);
</script>
</head>
<body>
<h1>Javascript First Page</h1>
</body>
</html>
Department of Computer Science
DataTypes
Numbers - are values that can be processed and calculated. You don't enclose them in
quotation marks. The numbers can be either positive or negative.
Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript uses the
string literally; it doesn't process it. You'll use strings for text you want displayed or values you
want passed along.
Boolean (true/false) - lets you evaluate whether a condition meets or does not meet specified
criteria.
Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number, whereas null
is the absence of any value.
TYPE EXAMPLE
Variables
Variables are declared with the var keyword as follows. JavaScript is untyped language. This
means that a JavaScript variable can hold a value of any data type.
Example
A variable's value can change during the execution of a script. You can refer to a variable by
its name to display or change its value.
Department of Computer Science
<html>
<body>
<script type="text/javascript">
var firstname;
firstname="Welcome";
document.write(firstname);
document.write("<br />");
firstname="XYZ";
document.write(firstname);
</script>
<p>The script above declares a variable,assigns a value to it, displays
the value, change the value, and displays the value again.</p>
</body>
</html>
Output :
Welcome
XYZ
NOTE:The script above declares a variable, assigns a value to it, displays the value, change
the value, and displays the value again.
JavaScript Arrays
An array object is used to create a database-like structure within a script. Grouping data
points (array elements) together makes it easier to access and use the data in a script. There
are methods of accessing actual databases (which are beyond the scope of this series) but here
we're talking about small amounts of data.
Array Methods
Here is a list of the methods of the Array object along with their description.
6. pop() Removes the last element from an array and returns that element.
7. push() Adds one or more elements to the end of an array and returns the new
length of the array.
8. reverse() Reverses the order of the elements of an array -- the first becomes the
last, and the last becomes the first.
9. shift() Removes the first element from an array and returns that element
10. slice() Extracts a section of an array and returns a new array.
11. sort() Sorts the elements of an array
12. splice() Adds and/or removes elements from an array.
13. toString() Returns a string representing the array and its elements.
Department of Computer Science
The basic array operations are:
• Creation of Arrays.
• Adding elements.
• Accessing individual elements.
• Removing elements.
1. Creating Arrays:
Javascript arrays can be created in three different ways:
1. The easiest way is simply to declare a variable and pass it some elements in array
format.
var days=[“Monday”,”Tuesday”,”Wednesday”];
2. The second approach is to create an array object using the keyword new and a set of
elements to store:
var days=new Array(“Monday”,”Tuesday”,”Wednesday”);
3. Finally, an empty array object which has a space for a number of elements can be
created:
JavaScript Operators
What is an operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is
called the operator. JavaScript supports the following types of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
1. JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y=5, the table below explains the arithmetic operators:
3. Comparison Operators
Comparison operators are used in logical statements to determine equality or difference
between variables or values.
Given that x=5, the table below explains the comparison operators:
4. Logical Operators
Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
Department of Computer Science
5. Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on
some condition.
Conditional Statements
Very often when you write code, you want to perform different actions for different
decisions. You can
use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
if statement - use this statement if you want to execute some code only if a specified
condition is true
if...else statement - use this statement if you want to execute some code if the
condition is true and another code if the condition is false
if...else if....else statement - use this statement if you want to select one of many
blocks of code to be executed
switch statement - use this statement if you want to select one of many blocks of
code to be executed
1) If Statement
You should use the if statement if you want to execute some code only if a specified
condition is true.
Syntax
if (condition)
{
code to be executed if condition is true
}
Example
if (hour < 18) {
greeting = "Good day";
}
2) If...else Statement
If you want to execute some code if a condition is true and another code if the condition is not
true, use the if....else statement.
Department of Computer Science
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example
if (hour < 18)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}
Syntax
while (var<=endvalue)
{
code to be executed
}
Example
<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=10)
{
Department of Computer Science
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html>
Continue
The continue command will break the current loop and continue with the next value.
Example
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
Javascript Functions:
A javascript function contains code that will be executed by an event or by a call to function.
We may call a function from anywhere within a page. Functions can be defined both in
<head> and <body> section of a document.
Syntax to define a function is:
function function_name(var1, var2,…..,varn)
{
//Block of code
}
A function with no parameters must include the parentheses () after function
name.
The keyword function must be written in lower case, otherwise javascript error
occurs.
Department of Computer Science
Example
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"onclick="displaymessage()" >
</form>
</body>
</html>
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 the OK button, the
window method prompt() will return the entered value from the text box. If the user clicks the
Cancel button, the window method prompt() returns null.
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 on the OK button, the window method confirm() will return true.
If the user clicks on the Cancel button, then confirm() returns false and will show null.