Unit 4
Unit 4
UNIT- IV
JAVASCRIPT
Introduction to scripting:
1. Introduction:
JavaScript scripting language, which facilitates a disciplined
approach to designing computer programs that enhance the functionality and
appearance of web pages. JavaScript serves two purposes- it introduces client-side
scripting, which makes web pages more dynamic and interactive, and it provides the
programming foundation for the more complex server side developments.
JavaScript contains a standard library of objects,
like Array, Date, and Math, and a core set of language elements
like operators, control structures, and statements.
Client-side: It supplies objects to control a browser and its Document Object Model
(DOM). Like if client-side extensions allow an application to place elements on an
HTML form and respond to user events such as mouse clicks, form input, and page
navigation.
Server-side: It supplies objects relevant to running JavaScript on a server. Like if the
server-side extensions allow an application to communicate with a database, and
provide continuity of information from one invocation to another of the application, or
perform file manipulations on a server.
indicate to the browser that the text which follows is part of a script. The language
attribute specifies the type of file as well as the scripting languages used in the script.
The line 5 instruct the browser’s JavaScript interpreter to perform an action, namely,
to display in the web page the string of characters contained between the double
quotation marks. In the same line 5 use the browser’s document object, which
represents the HTML document the browser is currently displaying. The document
object allows a script programmer to specify text to display in the HTML document.
The</head> tag in line 7 indicates the end of the <head> section. Also in line 8
to 10 , the tags <body> and </body> specify body section in the HTML document.
Finally the line 11 indicates the end of the HTML document.
Output:
In the next example, we demonstrate that a single statement that can cause the
browser to display multiple lines through by using line-break HTML tags(<br/>
throughout the string of HTML text in a write or writeln method call.
Ex: 1. <html>
2.<head>
3.<title>Printing multiple lines</title>
4. <script language=” javascript”>
5.document.writeln(“<h1>welcometo <br/>javascript<br/>programming</h1>”);
6.</script>
7. </head>
8.<body></body>
9.</html>
In above example, line 5 produce three separate lines of text when the
browser renders the HTML document.
Output:
browser’s refresh button, the browser will reload the HTML document, so you can execute
the script again and change the name.
Output:
4. JAVACSRIPT VARIABLES:
All JavaScript variables must be identified with unique names.These unique names
are called identifiers. Variables are containers for storing data (storing data values).
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
total ,Volume etc).
The general rules for constructing names for variables (unique identifiers) are:
After the declaration, the variable has no value (technically it is undefined). To assign a
value to the variable, use the equal sign:
In this example, x, y, and z, are variables, declared with the var keyword:
Ex:1
<html>
<head>
<title> Variables in javascript</title>
</head>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, x, y, and z are variables.</p>
<script language="javascript">
var x = 5;
var y = 6;
var z = x + y;
document.writeln("The value of z is: " + z);
</script>
</body>
</html>
Output:
The value of z is: 11
Ex2:
In the example below, we create a variable called carName and assign the value "Volvo" to it.
<html>
<head>
<title> declaring variables</title>
</head>
<body>
<h1>JavaScript Variables</h1>
<script language="javascript">
var carName = "Volvo";
document.writeln(carName);
</script>
</body>
</html>
Output:
Volvo
One Statement, Many Variables:
You can declare many variables in one statement. Start the statement
with var and separate the variables by comma:
Ex 3:
<html>
<body>
<h1>JavaScript Variables</h1>
<p>You can declare many variables in one statement.</p>
<script language="javascript">
var person = "John Doe", carName = "Volvo", price = 200;
document.writeln(person+"<br>" +carName+"<br>"+price);
</script>
</body>
</html>
Output:
JavaScript Variables
You can declare many variables in one statement.
John Doe
Volvo
200
Arithmetic:
Many scripts perform arithmetic calculations. The arithmetic operators are
binary operators, because each operates on two operands. In javascript arithmetic
operators are five types , they are shown below:
50 + 15 is 65 (leftmost addition)
Step5: y= 65 + 7;
65 + 7 is 72
Step6: y = 72; (last operation- place 72 into y)
Ex:
<html>
<head>
<title>JavascriptArithmeticOperators </title>
</head>
<body>
<h1>Performing Arithmetic Operations </h1>
<script>
var a = 12, b = 3;
var addition, subtraction, multiplication, division, modulus;
document.write("Addition of " +a +' and ' +b +" is = " + addition + "<br />");
document.write("Subtraction of " +a +' and ' +b +" is = " + subtraction + "<br />");
document.write("Multiplication of " +a +' and ' +b +" is = " + multiplication + "<br />");
document.write("Division of " +a +' and ' +b +" is = " + division + "<br />");
document.write("Modulus of " +a +' and ' +b +" is = " + modulus + "<br />");
</script>
</body>
</html>
Output:
EQUALITY OPERATORS
== == x == y x is equal to y
!= != x != y x is not equal to y
RELATIONAL OPERATORS
> > x>y x is greater than y
< < x<y x is less than y
>= >= x>=y x is greater than or
equal to y
<= <= x<=y x is less than or equal
to y
Ex: <html>
<body>
<script language= "javascript">
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write(linebreak);
Output:
Logical operators:
These operators are used to combine two or more conditions and give the result
either true or false. These conditions are called compound conditions.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
This operator gives true if all the conditions are true otherwise it gives false. The truth
table for && operator is as follows
Condition Condition 2 Condition 1 &&Condition 2
1
True True True
True False False
False True False
False False False
Logical OR (||) Operator:
This operator gives false if all conditions are false otherwise it gives true. The truth table for
|| operator is as follows:
Condition 1 Condition 2 Condition 1 ||condition 2
True True True
True False True
False True True
False False False
Logical not (!) operator:
This operator negates (opposite) the result of a condition. It means if the condition is
true then it gives false. If the condition is false then it returns true.
The truth table for (!) Operator is as follows :
condito !(condition)
n
True False
False True
Eg: Let a=15, b=20 then
Expression Result
a==15||b==20 True
a>15&&b>=20 False
a<=15&&b<=2 True
0
!(a==15) False
different meaning depending on the position it is used. It means this operator is used in two
ways. They are
Pre decrement:
If the ‘--‘operator precedes the operand then it is called “pre
decrement.” In this method the pre decrement operator decrements the value of variable first
and then the new value is used in the expression.
Eg: c=--a; means a=a-1;
C=a;
Post decrement:
If the ‘--‘ operator succeeds the operand then it is called post decrement.
In this method the old value of the variable is used in expression and then it is decremented.
Eg: c=a--; means c=a; a=a-1;
Initial values Expression Final values
A B A B
3 7 a=++b 8 8
3 7 a=b++ 7 8
3 7 a=--b 6 6
3 7 a=b-- 7 6
Ex:
<html>
<head>
<title> Increment and Decrement Operators in JavaScript </title>
</head>
<body>
<script language="javascript">
var x = 10, y = 20;
document.writeln("<b>----INCREMENT OPERATOR EXAMPLE---- </b>"+"<br>");
document.writeln(" Value of x : "+ x+"<br>"); //Original Value
document.writeln("Value of x : "+ x++ +"<br>"); // Using increment Operator
document.writeln("Value of x : "+ x + "<br>"); //Incremented value
1. Introduction:
Before writing a script to solve a problem, it is essential to have a thorough
understanding of the problem and a carefully planned approach to solving the problem.
When writing a script, it is equally essential to understand the types of building blocks that
are available and to employ proven program construction principles.
2. Control structures:
The research of bohm and jacopini demonstrated that programs could be
written without goto statements. The researchers written in terms of only three control
structures, namely the sequence structure, the selection structure, and the
repetition structure.
The sequence structure is built into javascript , Here the computer
executes javascript statements one after the other in the order in which they are
written(i..e..sequence).
Javascript provides three types of selection structures. They are; if,
if…else,switch. The if statement is called a single- selection structure because it
selects or ignores a single action. The if…else statement is a double-selection
structure because it ignores between two different actions. The switch statement is a
multiple-selection structure because it selects among many different actions.
Javascript provides three repetition structure types, namely while,
do…while, for. The control structures are attached to one another by connecting the
exit point of one control structure to the entry point of the next. This process is
similar to the way in which a child stacks building blocks, so we call it control-
structure stacking.
If- selection statement:
If the statement is one of the most basic and simplest controls flow
statements. We can use the if statement when we want to execute a group of one or more
script statements only when a particular condition is met.
Syntax
if(condition)
{
Statement 1
}
In the preceding syntax, if the JavaScript keyword that signifies an if statement and contains a
condition, that needs to be evaluated to true, then the script statement, represented by
statement 1, enclosed within the curly braces, is executed. If the condition evaluates to false,
then the statement enclosed within the curly braces is skipped and the statement immediately
after closing curly brace (}) is executed.
1. <html>
2. <head>
3. <title>Using if Statement</title>
4. </head>
5. <body>
6. <h1>
7. Using the if Statement in the script
8. </h1>
9. <script language=”javascript">
10. var Number = 45;
11. if ((Number % 2) != 0) {
Output:
Syntax
1. if(condition)
2. {
3. Statement 1
4. }
5. else
6. {
7. Statement 2
8. }
In the given syntax, the if and else keywords signify the if...else statement. The condition of
the if....else statement is enclosed within parentheses. If the condition is true, then the group
of statements represented by statement 1 enclosed within the first curly braces is executed. If
the condition is false, then the statement 1 is skipped and the group of statements, represented
by statement 2 of the else block is executed.
1. <html>
2. <head>
3. <title>if...else Statement</title>
4. </head>
5. <body>
6. <h1>
7. Using the if...else Statement in the Script</h1>
8. <script language=”javascript">
9. var Number = 44;
10. if ((Number % 2) != 0) {
11. document.writeln(Number + " is an odd number");
12. }
13. else {
14. document.writeln(Number + " is an even number");
15. }
16. </script>
17. </body>
18. </html>
Output:
Syntax
1. switch(expression)
2. {
3. case value1:statement 1
4. break;
5. case value2:statement 2
6. break;
7. case value3: statement 3
8. break;
9. default:statement_default
10. break;
11. }
In the given syntax, the switch case, and break are JavaScript keywords. The switch keyword
indicates the switch statement. In a switch statement, the expression that is to be evaluated is
specified within parentheses. This expression is checked against each of the case values
specified in the case statements. If any of the case values match the value of the expression,
the group of statements (statement 1, statement 2 or statement 3) specified in the respective
case statement is executed.
If none of the case values matches the value of the expression, then the
default statement, specified by the default keyword, is executed. The default statement is
generally placed at the end of the switch statement; however, we can place it anywhere within
the switch statement.
1. <html>
2. <head>
3. <title>Using switch Statement</title>
4. </head>
5. <body>
6. <h1>
7. Using switch Statement in the script</h1>
8. <script language=”javascript">
9. var letter = "I";
10. switch (letter) {
11. default: document.write("consonant");
12. break;
13. case "A": document.write("A is a vowel");
14. break;
15. case "E": document.write("E is a vowel");
16. break;
17. case "I": document.write("I is a vowel");
18. break;
19. case "O": document.write("O is a vowel");
20. break;
21. case "U": document.write("U is a vowel");
22. break;
23. }
24. </script> </body> </html>
Output:
Output:
When the while statement begins executing (line6), the control variable counter is
declared and is initialized to 1. Next , the loop continuation condition, counter <=10 is
checked . The condition contains the final value ( 10) of the counter variable. The initial
value of the counter is 1. Therefore , the condition is satisfied , so the statement ( line 8) is
executed. Then the variable counter in the incremented in the expression counter++ and the
loop continues execution with the loop continuation test. This process continues until the
control variable counter becomes 10 , at which point the loop–continuation test fails and the
repetition terminates.
Ex:
1. <html>
2. <head>
3. <title> while statement</title>
4. <script language="javascript">
5. for( var counter=1; counter<=10; counter++)
6. {
8. document.writeln("The counter values are:" +counter+"<br>");
10. }
11. </script>
12.</head>
13.<body></body>
14.</html>
Output:
When the for statement begins executing (line 5), the control variable counter is
declared and is initialized to 1. Next , the loop continuation condition, counter <=10 is
checked . The condition contains the final value ( 10) of the counter variable. The initial
value of the counter is 1. Therefore , the condition is satisfied , so the statement ( line 8) is
executed. Then the variable counter in the incremented in the expression counter++ and the
loop continues execution with the loop continuation test. This process continues until the
control variable counter becomes 10 , at which point the loop–continuation test fails and the
repetition terminates.
Ex:
<html>
<head>
<title> while statement</title>
<script language="javascript">
var counter=1;
do
{
document.writeln("The counter values are:" +counter+"<br>");
counter++;
} while(counter <=10);
</script>
</head>
<body></body>
</html>
Output:
The do-while loop is a control flow statement that executes the code block at
least once and then it executes the code block repeatedly, depending on the condition given at
the end of the code block.
The do-while loop is also known as "post test loop" as in this loop, condition
is checked after the execution of loop once. There are some cases, where we want to execute
the code block infinite times, thus creating an infinite loop. When such type of loop is
created, the break statement is used that allows the termination from the loop.
BREAK statement:
The break and continue statements alter the flow of control. The break
statement, when executed in a while , for, do…while or switch statement, causes
immediately exit from the statement. Execution continues with the first statement after the
structure. The break statement is commonly used to escape early from a loop or to skip the
remainder of a switch statement.
Syntax: break;
Ex:
1.<html>
2. <head>
3. <script language=”javascript”>
4.for( var count=1; count <=5; count++)
5. {
6. if(count == 5)
7. break;
8. document.writeln(“ count is:”+count+”<br>”);
9. }
10. document.writeln( “ break out of loop” +count);
11.</script>
12. </head><body></body></html>
Output:
In above example, when the if statement in line 6 detects that count is 5, the break
in line 7 executes. This statement terminates the for statement, and the program proceeds to
line 10, where the script writes the value of count when the loop terminated. The loop
executes its body only four times.
CONTINUE statement:
Syntax: continue;
Ex:
1.<html>
2.<head>
3.<script language=”javascript”>
4.for(var count=1; count<=10;count++)
5.{
6.if (count ==5)
7.continue;
8.document.writeln(“count is:” +count+”<br>”);
9.</script>
10.</head><body></body></html>
Output: