0% found this document useful (0 votes)
6 views16 pages

Unit 2

This document provides an introduction to JavaScript, detailing its purpose as a scripting language for enhancing HTML pages and creating interactive web applications. It covers key concepts such as JavaScript's integration with HTML, its interpreted nature, variable declaration, data types, and basic syntax, along with examples of JavaScript code. Additionally, it discusses operators, conditional statements, and looping structures used in JavaScript programming.

Uploaded by

akka6286
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views16 pages

Unit 2

This document provides an introduction to JavaScript, detailing its purpose as a scripting language for enhancing HTML pages and creating interactive web applications. It covers key concepts such as JavaScript's integration with HTML, its interpreted nature, variable declaration, data types, and basic syntax, along with examples of JavaScript code. Additionally, it discusses operators, conditional statements, and looping structures used in JavaScript programming.

Uploaded by

akka6286
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Department of Computer Science

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

Numbers Any number, such as 17, 21, or 54e7

Strings "Greetings!" or "Fun"

Boolean Either true or false

Null A special keyword for exactly that – the null


value (that is, nothing)

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.

Rules for JavaScript variable names:


Variable names are case sensitive (y and Y are two different variables)
Variable names must begin with a letter or the underscore character

JavaScript Variable Scope


The scope of a variable is the region of your program in which it is defined. JavaScript
variables have only two scopes.
 Global Variables − A global variable has global scope which means it can be defined
anywhere in your JavaScript code.
 Local Variables − A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function

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.

1. Declaring (Creating) JavaScript Variables


Creating variables in JavaScript is most often referred to as "declaring" variables.
You can declare JavaScript variables with the var statement:
var x;
var carname;
After the declaration shown above, the variables are empty (they have no values yet).
However, you can also assign values to the variables when you declare them:
var x=5;
var carname="Scorpio";
After the execution of the statements above, the variable x will hold the value 5, and carname
will hold the value Scorpio.
Note: When you assign a text value to a variable, use quotes around the value.

2. Assigning Values to Undeclared JavaScript Variables


If you assign values to variables that have not yet been declared, the variables will
automatically be declared.These statements:
x=5;
carname="Scorpio";
have the same effect as:
var x=5;
var carname="Scorpio";
Department of Computer Science
3. Redeclaring JavaScript Variables
If you redeclare a JavaScript variable, it will not lose its original value.
var x=5;
var x;
After the execution of the statements above, the variable x will still have the value of 5. The
value of x is not reset (or cleared) when you redeclare it.

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.

S.No Methods Description


1. concat() Returns a new array comprised of this array joined with other
array(s) and/or value(s).

2. forEach() Calls a function for each element in the array.


3. indexOf() Returns the first (least) index of an element within the array equal to
the specified value, or -1 if none is found.

4. join() Joins all elements of an array into a string.


5. lastIndexOf() Returns the last (greatest) index of an element within the array equal
to the specified value, or -1 if none is found.

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:

var days=new Array(3);


2. Adding elements to Arrays:
Adding an element to an array can be done as shown below:
var days[4]=“Thursday”;
In javascript we have a benefit. If the array is full, then also we can add elements to array.
The interpreter simply extends the array and inserts new item. For example:
3. Accessing Array elements:
The elements in the array are accessed through their index. The same access
method is used to find elements and to change their values.
Length:
When accessing array elements we need to know how many elements have been stored into
the array. This is done through the length attribute. The index number runs from 0 – length-
1.
4. Removing Array elements:
Javascript does not provide a built-in function to remove array members. To remove array
elements we use the following procedure:
Department of Computer Science
1. Read each element in the array.
2. If the element is not the one which we want to delete, copy it to temporary array.
3. If the element is the one we want to delete, do nothing.
4. Increment loop counter.
5. Repeat the process and copy the array elements again into original array.

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:

2. JavaScript Assignment Operators


Assignment operators are used to assign values to JavaScript variables.
Given that x=10 and y=5, the table below explains the assignment operators:
Department of Computer Science

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";
}

3) If...else if...else Statement


You should use the if....else if...else statement if you want to select one of many sets of lines
to execute.
Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and condition2 are not true
}
Example
if (time < 10)
{
greeting = "Good morning";
}
else if (time < 20)
{
greeting = "Good day";
}
Else {
greeting = "Good evening";
}
Department of Computer Science
JavaScript Controlling(Looping) Statements
Loops in JavaScript are used to execute the same block of code a specified number of
times or while a specified condition is true.
JavaScript Loops
Very often when you write code, you want the same block of code to run over and over again
in a row.Instead of adding several almost equal lines in a script we can use loops to perform a
task like this.
In JavaScript there are two different kind of loops:
 for - loops through a block of code a specified number of times
 while - loops through a block of code while a specified condition is true
The for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}
Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

The while loop


The while loop is used when you want the loop to execute and continue executing while the
specified condition is true.

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>

The do...while Loop


The do...while loop is a variant of the while loop. This loop will always execute a block of
code ONCE, and then it will repeat the loop as long as the specified condition is true. This
loop will always be executed at least once, even if the condition is false, because the code is
executed before the condition is tested.
Syntax
do
{
code to be executed
}
while (var<=endvalue);
Example
<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
while (i<0);
</script>
</body>
</html>

JavaScript Break and Continue


There are two special statements that can be used inside loops: break and continue.
JavaScript break and continue Statements
There are two special statements that can be used inside loops: break and continue.
 Break
The break command will break the loop and continue executing the code that follows after
the loop (ifany).
Example
<html>
<body>
<script type="text/javascript">
var i=0;
Department of Computer Science
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</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>

How to Define a Function


The syntax for creating a function is:
function functionname(var1,var2,...,varX)
{
some code
}
var1, var2, etc are variables or values passed into the function. The { and the } defines the
start and end of the function.

The return Statement


The return statement is used to specify the value that is returned from the function.
So, functions that are going to return a value must use the return statement.
Example
The function below should return the product of two numbers (a and b):
function prod(a,b)
{
x=a*b;
return x;
}
When you call the function above, you must pass along two parameters:
product=prod(2,3);

JavaScript Dialogue Boxes


Dialogue boxes are a kind of popup notification, this kind of informative functionality is used
to show success, failure, or any particular/important notification to the user.
JavaScript uses 3 kinds of dialog boxes:
 Alert
 Prompt
 Confirm
These dialog boxes can be of very much help in making our website look more attractive.
Department of Computer Science
Alert Box: An alert box is used on the website to show a warning message to the user that
they have entered the wrong value other than what is required to fill in that position.
Nonetheless, an alert box can still be used for friendlier messages. The alert box gives only
one button “OK” to select and proceed.

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.

You might also like