2.1 Study Material - Javascript - An Introduction To Javascript
2.1 Study Material - Javascript - An Introduction To Javascript
3 V
5
CS8501
20CSPC501
THEORY OF COMPUTATION
INTERNET PROGRAMMING
UNIT No. 1
UNIT No. 2
1.3.Inductive Proof
2.1 JavaScript: An Introduction to Javascript
Version: 1.XX
1
CS8651
INTERNET PROGRAMMING
JavaScript is the scripting language of the Web. All modern HTML pages are using JavaScript.
Developed by Brendan Eich as a part of Netscape. JavaScript is the world's most popular
programming language.
The <script> and </script> tells where the JavaScript starts and ends.
<script>
alert("My First JavaScript");
</script>
JavaScript in <body>
<!DOCTYPE html>
<html>
<body>
.
.
<script>
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph</p>");
</script>
.
.
</body>
</html>
JavaScript Statements
JavaScript statements are "commands" to the browser.
The purpose of the statements is to tell the browser what to do.
Semicolon separates JavaScript statements.
2
CS8651
INTERNET PROGRAMMING
JavaScript Comments
Comments will not be executed by JavaScript.
Comments can be added to explain the JavaScript, or to make the code more readable.
// Write to a heading:
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
/*
The code below will write
to a heading and to a paragraph,
and will represent the start of
my homepage:
*/
JavaScript Variables
As with algebra, JavaScript variables can be used to hold values (x=5) or expressions (z=x+y).
Variable can have short names (like x and y) or more descriptive names (age, sum, totalvolume).
3
CS8651
INTERNET PROGRAMMING
var carname;
carname="Tata";
However, you can also assign a value to the variable when you declare it:
var carname="Tata";
var lastname="Sairam",
age=30,
job="carpenter";
Value = undefined
4
CS8651
INTERNET PROGRAMMING
In computer programs, variables are often declared without a value. The value can be something
that has to be calculated, or something that will be provided later, like user input. Variable
declared without a value will have the value undefined.
The variable carname will have the value undefined after the execution of the following
statement:
var carname;
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:
y=5;
x=y+2;
JavaScript Strings
A string is a variable which stores a series of characters like "John Sairam".
A string can be any text inside quotes. You can use single or double quotes:
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
JavaScript Numbers
JavaScript has only one type of numbers. Numbers can be written with, or without decimals:
Extra large or extra small numbers can be written with scientific (exponential) notation:
5
CS8651
INTERNET PROGRAMMING
JavaScript Booleans
var x=true;
var y=false;
Booleans are often used in conditional testing. You will learn more about conditional testing in a
later chapter of this tutorial.
JavaScript Arrays
The following code creates an Array called cars:
cars[0]="Maruti";
cars[1]="Tata";
cars[2]="RENAULT";
or (condensed array):
<body>
<script>
var i;
var cars = new Array();
cars[0] = "Maruti";
cars[1] = "Tata";
cars[2] = "RENAULT";
for (i=0;i<cars.length;i++)
{
document.write(cars[i] + "<br>");
}
</script>
6
CS8651
INTERNET PROGRAMMING
</body>
JavaScript Functions
function functionname()
{
some code to be executed
}
The code inside the function will be executed when "someone" calls the function.
The function can be called directly when an event occurs (like when a user clicks a button), and it
can be called from "anywhere" by JavaScript code.
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
7
CS8651
INTERNET PROGRAMMING
<head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.
<html>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</script>
</body>
</html>
When you call a function, you can pass along some values to it, these values are called
arguments or parameters.
8
CS8651
INTERNET PROGRAMMING
myFunction(argument1,argument2)
function myFunction(var1,var2)
{
some code
}
The variables and the arguments must be in the expected order. The first variable is given the
value of the first passed argument etc.
<body>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
</body>
The function above will alert "Welcome Harry Potter, the Wizard" when the button is
clicked.
Sometimes you want your function to return a value back to where the call was made.
9
CS8651
INTERNET PROGRAMMING
When using the return statement, the function will stop executing, and return the specified value.
Syntax
function myFunction()
{
var x=5;
return x;
}
The function above will return the value 5.
<body>
<p>This example calls a function which performs a calculation, and returns the result:</p>
<h1><p id="demo"></p></h1>
<script>
function myFunction(a,b)
{
return a*b;
}
document.getElementById("demo").innerHTML=myFunction(4,3);
</script>
</body>
O/P: This example calls a function which performs a calculation, and returns the result:
12
JavaScript Operators
= is used to assign values.
+ is used to add values.
<body>
10
CS8651
INTERNET PROGRAMMING
<p id="demo"></p>
<h1 id="d"></h1>
<script>
function myFunction()
{
y=5;
z=2;
x=y+z;
document.getElementById("demo").innerHTML=x;
document.getElementById("d").innerHTML=x;
}
</script>
</body>
O/P: Click the button to calculate x.
7
7
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:
Re Re
Op Ex
sul sul
era Description am
t of t of
tor ple
x y
x=
+ Addition y+ 7 5
2
x=
- Subtraction 3 5
y-2
x=
* Multiplication 10 5
y*2
x=
/ Division 2.5 5
y/2
11
CS8651
INTERNET PROGRAMMING
Modulus x=
% (division y 1 5
remainder) %2
x=
+ 6 6
+y
++ Increment
x=
y+ 5 6
+
x=-
4 4
-y
-- Decrement
x=
5 4
y--
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:
Ope Description Comp Retu
rato aring rns
12
CS8651
INTERNET PROGRAMMING
r
x==8 false
== equal to
x==5 true
x==="
exactly equal to (equal false
=== 5"
value and equal type)
x===5 true
!= not equal x!=8 true
x!
not equal (different true
!== =="5"
value or different type)
x!==5 false
> greater than x>8 false
< less than x<8 true
>= greater than or equal to x>=8 false
<= less than or equal to x<=8 true
You will learn more about the use of conditional statements in the next chapter of this tutorial.
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:
O
pe
Description Example
rat
or
& and (x < 10 && y > 1) is
13
CS8651
INTERNET PROGRAMMING
& true
(x==5 || y==5) is
|| or
false
! not !(x==y) is true
Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some
condition.
Syntax
variablename=(condition)?value1:value2
<body>
<p id="demo"></p>
<script>
function myFunction()
{
var age,voteable;
age=document.getElementById("age").
value;
voteable=(age<18)?"Too young":"Old
enough";
document.getElementById("demo").inn
erHTML=voteable;
}
</script>
</body>
14
CS8651
INTERNET PROGRAMMING
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 to execute some code only if a specified condition is true
● if...else statement - use this statement 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 to select one of many blocks of code to be
executed
● switch statement - use this statement to select one of many blocks of code to be executed
If Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax Make a "Good day" greeting if
if (condition) the time is less than 20:00:
{ if (time<20)
code to be executed if condition {
is true x="Good day";
} }
Note that if is written in The result of x will be:
lowercase letters. Using Good day
uppercase letters (IF) will
generate a JavaScript error!
If...else Statement
Use the if....else statement to execute some code if a condition is true and another code if the
condition is not true.
Syntax If the time is less than 20:00,
if (condition) you will get a "Good day"
{ greeting, otherwise you will get
code to be executed if condition a "Good evening" greeting
is true if (time<20)
} {
else x="Good day";
{ }
code to be executed if condition else
is not true {
} x="Good evening";
}
The result of x will be:
Good day
15
CS8651
INTERNET PROGRAMMING
16
CS8651
INTERNET PROGRAMMING
Example
If the day is NOT Saturday or Sunday, then write a default message:
17
CS8651
INTERNET PROGRAMMING
break;
default:
x="Looking forward to the Weekend";
}
The result of x will be:
Looking forward to the Weekend
JavaScript Loops
Different Kinds of Loops
JavaScript supports different kinds of loops:
● for - loops through a block of code a number of times
● for/in - loops through the properties of an object
● while - loops through a block of code while a specified condition is true
● do/while - also loops through a block of code while a specified condition is true
The for loop is often the tool you will use when you want to create a loop.
The for loop has the following syntax:
for (statement 1; statement 2; statement 3)
{
the code block to be executed
}
for (var i=0; i<5; i++)
{
x=x + "The number is " + i + "<br>";
}
<script> <script>
cars=["RENAULT","Tata","M cars=["RENAULT","Tata","
aruti","Ford"]; Maruti","Ford"];
for (var i=0,l=cars.length; i<l; i+ var i=2,len=cars.length;
+) for (; i<len; i++)
{ {
document.write(cars[i] + document.write(cars[i] +
"<br>"); "<br>");
} }
</script> </script>
18
CS8651
INTERNET PROGRAMMING
19
CS8651
INTERNET PROGRAMMING
You have already seen the break statement used in an earlier chapter of this tutorial. It was used
to "jump out" of a switch() statement.
for (i=0;i<10;i++)
{
if (i==3)
{
break;
}
x=x + "The number is " + i + "<br>";
}
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
for (i=0;i<=10;i++)
{
20
CS8651
INTERNET PROGRAMMING
JavaScript Labels
As you have already seen, in the chapter about the switch statement, JavaScript statements can be
labeled.
label:
statements
cars=["RENAULT","Tata","Maruti","Ford"];
list:
{
document.write(cars[0] + "<br>");
document.write(cars[1] + "<br>");
document.write(cars[2] + "<br>");
break list; // after this stmt break in o/p ie no o/p
document.write(cars[3] + "<br>");
document.write(cars[4] + "<br>");
document.write(cars[5] + "<br>");
}
21