SlideShare a Scribd company logo
You can use multiple if...else…if statements, as in the previous chapter, to perform a multiway branch. However,
this is not always the best solution, especially when all of the branches depend on the value of a single variable.
Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation, and it does so
more efficiently than repeated if...else ifstatements.
Flow Chart
The following flow chart explains a switch-case statement works.
Syntax
The objective of a switch statement is to give an expression to evaluate and several different statements to execute
based on the value of the expression. The interpreter checks each case against the value of the expression until a
match is found. If nothing matches, a default condition will be used.
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the interpreter would continue
executing each statement in each of the following cases.
We will explain break statement in Loop Control chapter.
Example
Try the following example to implement switch-case statement.
<html>
<body>
<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;
case 'F': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Entering switch block
Good job
Exiting switch block
Set the variable to different value and then try...
Break statements play a major role in switch-case statements. Try the following code that uses switch-case
statement without any break statement.
<html>
<body>
<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("Good job<br />");
case 'B': document.write("Pretty good<br />");
case 'C': document.write("Passed<br />");
case 'D': document.write("Not so good<br />");
case 'F': document.write("Failed<br />");
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Entering switch block
Good job
Pretty good
Passed
Not so good
Failed
Unknown grade
Exiting switch block
Set the variable to different value and then try...
While writing a program, you may encounter a situation where you need to perform an action over and over again.
In such situations, you would need to write loop statements to reduce the number of lines.
JavaScript supports all the necessary loops to ease down the pressure of programming.
The while Loop
The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The purpose of
a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the
expression becomes false, the loop terminates.
Flow Chart
The flow chart of while loop looks as follows −
Syntax
The syntax of while loop in JavaScript is as follows −
while (expression){
Statement(s) to be executed if expression is true
}
Example
Try the following example to implement while loop.
<html>
<body>
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop ");
while (count < 10){
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...
The do...while Loop
The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This
means that the loop will always be executed at least once, even if the condition is false.
Flow Chart
The flow chart of a do-while loop would be as follows −
Syntax
The syntax for do-while loop in JavaScript is as follows −
do{
Statement(s) to be executed;
} while (expression);
Note − Don’t miss the semicolon used at the end of the do...while loop.
Example
Try the following example to learn how to implement a do-while loop in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
do{
document.write("Current Count : " + count + "<br />");
count++;
}
while (count < 5);
document.write ("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop Stopped!
Set the variable to different value and then try...
The 'for' loop is the most compact form of looping. It includes the following three important parts −
 The loop initialization where we initialize our counter to a starting value. The initialization statement is
executed before the loop begins.
 The test statement which will test if a given condition is true or not. If the condition is true, then the code
given inside the loop will be executed, otherwise the control will come out of the loop.
 The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Flow Chart
The flow chart of a for loop in JavaScript would be as follows −
Syntax
The syntax of for loop is JavaScript is as follows −
for (initialization; test condition; iteration statement){
Statement(s) to be executed if test condition is true
}
Example
Try the following example to learn how a for loop works in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++){
document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...
<html>
<script language = "javascript">
var a, b = 0;
a = parseInt(prompt("Enter number to reverse: "));
while(a > 0)
{
b = b * 10
b = b + parseInt(a % 10)
a = parseInt(a / 10)
}
document.write("Reversed number: ", b)
</script>
</html>
JavaScript provides full control to handle loops and switch statements. There may be a situation when you need to
come out of a loop without reaching its bottom. There may also be a situation when you want to skip a part of your
code block and start the next iteration of the loop.
To handle all such situations, JavaScript provides break and continuestatements. These statements are used to
immediately come out of any loop or to start the next iteration of any loop respectively.
The break Statement
The break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking
out of the enclosing curly braces.
Flow Chart
The flow chart of a break statement would look as follows −
Example
The following example illustrates the use of a break statement with a while loop. Notice how the loop breaks out
early once x reaches 5 and reaches to document.write (..) statement just below to the closing curly brace −
<html>
<body>
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20)
{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Entering the loop
2
3
4
5
Exiting the loop!
Set the variable to different value and then try...
We already have seen the usage of break statement inside a switchstatement.
The continue Statement
The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the
remaining code block. When a continuestatement is encountered, the program flow moves to the loop check
expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control
comes out of the loop.
Example
This example illustrates the use of a continue statement with a while loop. Notice how the continue statement is
used to skip printing when the index held in variable x reaches 5 −
<html>
<body>
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10)
{
x = x + 1;
if (x == 5){
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Entering the loop
2
3
4
6
7
8
9
10
Exiting the loop!
Using Labels toControl the Flow
Starting from JavaScript 1.2, a label can be used with break and continue to control the flow more precisely.
A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. We will see
two different examples to understand how to use labels with break and continue.
Note − Line breaks are not allowed between the ‘continue’ or ‘break’statement and its label name. Also, there
should not be any other statement in between a label name and associated loop.
Try the following two examples for a better understanding of Labels.
Example 1
The following example shows how to implement Label with a break statement.
<html>
<body>
<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 5; i++)
{
document.write("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++)
{
if (j > 3 ) break ; // Quit the innermost loop
if (i == 2) break innerloop; // Do the same thing
if (i == 4) break outerloop; // Quit the outer loop
document.write("Innerloop: " + j + " <br />");
}
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
</body>
</html>
Example 2
<html>
<body>
<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 3; i++)
{
document.write("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++)
{
if (j == 3){
continue outerloop;
}
document.write("Innerloop: " + j + "<br />");
}
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
</body>
</html>
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.
JavaScript allows us to write our own functions as well. This section explains how to write your own functions in
JavaScript.
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 aFunction
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>
What is anEvent ?
JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates
a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples
include events like pressing any key, closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows,
messages to be displayed to users, data to be validated, and virtually any other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events
which can trigger JavaScript Code.
Please go through this small tutorial for a better understanding HTML Event Reference. Here we will see a few
examples to understand a relation between Event and JavaScript −
onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can
put your validation, warning etc., against this event type.
Example
Try the following example.
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>
</body>
</html>
Output
onsubmit Event type
onsubmit is an event that occurs when you try to submit a form. You can put your form validation against this
event type.
Example
The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a
form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not
submit the data.
Try the following example.
<html>
<head>
<script type="text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method="POST" action="t.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>
onmouseover and onmouseout
These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and the onmouseout triggers when
you move your mouse out from that element. Try the following example.
<html>
<head>
<script type="text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
Output
HTML 5Standard Events
The standard HTML 5 events are listed here for your reference. Here script indicates a Javascript function to be
executed against that event.
Attribute Value Description
Offline script Triggers when the document goes offline
Onabort script Triggers on an abort event
onafterprint script Triggers after the document is printed
onbeforeonload script Triggers before the document loads
onbeforeprint script Triggers before the document is printed
onblur script Triggers when the window loses focus
oncanplay script Triggers when media can start play, but might has to
stop for buffering
oncanplaythrough script Triggers when media can be played to the end,
without stopping for buffering
onchange script Triggers when an element changes
onclick script Triggers on a mouse click
oncontextmenu script Triggers when a context menu is triggered
ondblclick script Triggers on a mouse double-click
ondrag script Triggers when an element is dragged
ondragend script Triggers at the end of a drag operation
ondragenter script Triggers when an element has been dragged to a
valid drop target
ondragleave script Triggers when an element is being dragged over a
valid drop target
ondragover script Triggers at the start of a drag operation
ondragstart script Triggers at the start of a drag operation
ondrop script Triggers when dragged element is being dropped
ondurationchange script Triggers when the length of the media is changed
onemptied script Triggers when a media resource element suddenly
becomes empty.
onended script Triggers when media has reach the end
onerror script Triggers when an error occur
onfocus script Triggers when the window gets focus
onformchange script Triggers when a form changes
onforminput script Triggers when a form gets user input
onhaschange script Triggers when the document has change
oninput script Triggers when an element gets user input
oninvalid script Triggers when an element is invalid
onkeydown script Triggers when a key is pressed
onkeypress script Triggers when a key is pressed and released
onkeyup script Triggers when a key is released
onload script Triggers when the document loads
onloadeddata script Triggers when media data is loaded
onloadedmetadata script Triggers when the duration and other media data of
a media element is loaded
onloadstart script Triggers when the browser starts to load the media
data
onmessage script Triggers when the message is triggered
onmousedown script Triggers when a mouse button is pressed
onmousemove script Triggers when the mouse pointer moves
onmouseout script Triggers when the mouse pointer moves out of an
element
onmouseover script Triggers when the mouse pointer moves over an
element
onmouseup script Triggers when a mouse button is released
onmousewheel script Triggers when the mouse wheel is being rotated
onoffline script Triggers when the document goes offline
onoine script Triggers when the document comes online
ononline script Triggers when the document comes online
onpagehide script Triggers when the window is hidden
onpageshow script Triggers when the window becomes visible
onpause script Triggers when media data is paused
onplay script Triggers when media data is going to start playing
onplaying script Triggers when media data has start playing
onpopstate script Triggers when the window's history changes
onprogress script Triggers when the browser is fetching the media
data
onratechange script Triggers when the media data's playing rate has
changed
onreadystatechange script Triggers when the ready-state changes
onredo script Triggers when the document performs a redo
onresize script Triggers when the window is resized
onscroll script Triggers when an element's scrollbar is being
scrolled
onseeked script Triggers when a media element's seeking attribute is
no longer true, and the seeking has ended
onseeking script Triggers when a media element's seeking attribute is
true, and the seeking has begun
onselect script Triggers when an element is selected
onstalled script Triggers when there is an error in fetching media
data
onstorage script Triggers when a document loads
onsubmit script Triggers when a form is submitted
onsuspend script Triggers when the browser has been fetching media
data, but stopped before the entire media file was
fetched
ontimeupdate script Triggers when media changes its playing position
onundo script Triggers when a document performs an undo
onunload script Triggers when the user leaves the document
onvolumechange script Triggers when media changes the volume, also
when volume is set to "mute"
onwaiting script Triggers when media has stopped playing, but is
expected to resume

More Related Content

PPT
Decision making and looping
Hossain Md Shakhawat
 
PPTX
Loops in java script
Ravi Bhadauria
 
PPTX
Control Statement programming
University of Potsdam
 
PPTX
Final requirement
arjoy_dimaculangan
 
PPT
Decision making and branching
Hossain Md Shakhawat
 
DOC
Jumping statements
Suneel Dogra
 
PPTX
Presentation of control statement
Bharat Rathore
 
PPTX
Javascript conditional statements
nobel mujuji
 
Decision making and looping
Hossain Md Shakhawat
 
Loops in java script
Ravi Bhadauria
 
Control Statement programming
University of Potsdam
 
Final requirement
arjoy_dimaculangan
 
Decision making and branching
Hossain Md Shakhawat
 
Jumping statements
Suneel Dogra
 
Presentation of control statement
Bharat Rathore
 
Javascript conditional statements
nobel mujuji
 

What's hot (20)

PPTX
Switch case and looping
aprilyyy
 
PDF
Control statement
Sakib Shahriar
 
PDF
Control statements
Kanwalpreet Kaur
 
PPTX
Switch case and looping
ChaAstillas
 
PDF
Control statements anil
Anil Dutt
 
DOCX
Java loops
ricardovigan
 
PDF
C++ control structure
bluejayjunior
 
PPTX
Switch case and looping jam
JamaicaAubreyUnite
 
PPTX
Switch case and looping new
aprilyyy
 
PPTX
Types of loops in c language
sneha2494
 
PPTX
Javascript conditional statements 1
Jesus Obenita Jr.
 
PPT
Mesics lecture 6 control statement = if -else if__else
eShikshak
 
PPTX
Macasu, gerrell c.
gerrell
 
PPTX
Understand Decision structures in c++ (cplusplus)
Muhammad Tahir Bashir
 
PPT
C++ chapter 4
SHRIRANG PINJARKAR
 
PPTX
Program control statements in c#
Dr.Neeraj Kumar Pandey
 
PDF
Java conditional statements
Kuppusamy P
 
PPTX
Loops in C Programming Language
Mahantesh Devoor
 
Switch case and looping
aprilyyy
 
Control statement
Sakib Shahriar
 
Control statements
Kanwalpreet Kaur
 
Switch case and looping
ChaAstillas
 
Control statements anil
Anil Dutt
 
Java loops
ricardovigan
 
C++ control structure
bluejayjunior
 
Switch case and looping jam
JamaicaAubreyUnite
 
Switch case and looping new
aprilyyy
 
Types of loops in c language
sneha2494
 
Javascript conditional statements 1
Jesus Obenita Jr.
 
Mesics lecture 6 control statement = if -else if__else
eShikshak
 
Macasu, gerrell c.
gerrell
 
Understand Decision structures in c++ (cplusplus)
Muhammad Tahir Bashir
 
C++ chapter 4
SHRIRANG PINJARKAR
 
Program control statements in c#
Dr.Neeraj Kumar Pandey
 
Java conditional statements
Kuppusamy P
 
Loops in C Programming Language
Mahantesh Devoor
 
Ad

Similar to Janakiram web (20)

PPTX
javascriptbasicsPresentationsforDevelopers
Ganesh Bhosale
 
PDF
Javascript basics
shreesenthil
 
PPTX
Cordova training : Day 3 - Introduction to Javascript
Binu Paul
 
PPTX
Bansal presentation (1).pptx
AbhiYadav655132
 
PPS
Programming in Arduino (Part 2)
Niket Chandrawanshi
 
RTF
Java scripts
Capgemini India
 
PPTX
Control Structure in JavaScript (1).pptx
BansalShrivastava
 
PPTX
web presentation 138.pptx
AbhiYadav655132
 
PPT
Control statements
CutyChhaya
 
DOCX
Loops and iteration.docx
NkurikiyimanaGodefre
 
PPTX
06-Control-Statementskkkkkkkkkkkkkk.pptx
kamalsmail1
 
PPTX
While loop and for loop 06 (js)
AbhishekMondal42
 
PDF
PROBLEM SOLVING USING NOW PPSC- UNIT -2.pdf
JNTUK KAKINADA
 
PDF
Control flow statements in java web applications
RajithKarunarathne1
 
DOC
Web programming[10]
Muhammad Awaluddin
 
PPTX
Flow of control C ++ By TANUJ
TANUJ ⠀
 
PDF
web programming javascriptconditionalstatements.pdf
Jayaprasanna4
 
PPT
Javascript sivasoft
ch samaram
 
PPTX
Introduction to java script
DivyaKS12
 
PDF
Learn C# Programming - Decision Making & Loops
Eng Teong Cheah
 
javascriptbasicsPresentationsforDevelopers
Ganesh Bhosale
 
Javascript basics
shreesenthil
 
Cordova training : Day 3 - Introduction to Javascript
Binu Paul
 
Bansal presentation (1).pptx
AbhiYadav655132
 
Programming in Arduino (Part 2)
Niket Chandrawanshi
 
Java scripts
Capgemini India
 
Control Structure in JavaScript (1).pptx
BansalShrivastava
 
web presentation 138.pptx
AbhiYadav655132
 
Control statements
CutyChhaya
 
Loops and iteration.docx
NkurikiyimanaGodefre
 
06-Control-Statementskkkkkkkkkkkkkk.pptx
kamalsmail1
 
While loop and for loop 06 (js)
AbhishekMondal42
 
PROBLEM SOLVING USING NOW PPSC- UNIT -2.pdf
JNTUK KAKINADA
 
Control flow statements in java web applications
RajithKarunarathne1
 
Web programming[10]
Muhammad Awaluddin
 
Flow of control C ++ By TANUJ
TANUJ ⠀
 
web programming javascriptconditionalstatements.pdf
Jayaprasanna4
 
Javascript sivasoft
ch samaram
 
Introduction to java script
DivyaKS12
 
Learn C# Programming - Decision Making & Loops
Eng Teong Cheah
 
Ad

Recently uploaded (20)

PPTX
Parallel & Concurrent ...
yashpavasiya892
 
PDF
LB# 820-1889_051-7370_C000.schematic.pdf
matheusalbuquerqueco3
 
PDF
Slides: PDF Eco Economic Epochs for World Game (s) pdf
Steven McGee
 
PPTX
Artificial-Intelligence-in-Daily-Life (2).pptx
nidhigoswami335
 
PDF
KIPER4D situs Exclusive Game dari server Star Gaming Asia
hokimamad0
 
PPTX
The Internet of Things (IoT) refers to a vast network of interconnected devic...
chethana8182
 
PPTX
Blue and Dark Blue Modern Technology Presentation.pptx
ap177979
 
PPTX
The Latest Scam Shocking the USA in 2025.pptx
onlinescamreport4
 
PPTX
Crypto Recovery California Services.pptx
lionsgate network
 
PPTX
Different Generation Of Computers .pptx
divcoder9507
 
PDF
The Internet of Things (IoT) refers to a vast network of interconnected devic...
chethana8182
 
PPTX
Black Yellow Modern Minimalist Elegant Presentation.pptx
nothisispatrickduhh
 
PPTX
原版北不列颠哥伦比亚大学毕业证文凭UNBC成绩单2025年新版在线制作学位证书
e7nw4o4
 
PPTX
The Internet of Things (IoT) refers to a vast network of interconnected devic...
chethana8182
 
PPTX
How tech helps people in the modern era.
upadhyayaryan154
 
PPTX
AI ad its imp i military life read it ag
ShwetaBharti31
 
PPTX
Slides Powerpoint: Eco Economic Epochs.pptx
Steven McGee
 
PPTX
Google SGE SEO: 5 Critical Changes That Could Wreck Your Rankings in 2025
Reversed Out Creative
 
PPTX
Microsoft PowerPoint Student PPT slides.pptx
Garleys Putin
 
PPTX
The Monk and the Sadhurr and the story of how
BeshoyGirgis2
 
Parallel & Concurrent ...
yashpavasiya892
 
LB# 820-1889_051-7370_C000.schematic.pdf
matheusalbuquerqueco3
 
Slides: PDF Eco Economic Epochs for World Game (s) pdf
Steven McGee
 
Artificial-Intelligence-in-Daily-Life (2).pptx
nidhigoswami335
 
KIPER4D situs Exclusive Game dari server Star Gaming Asia
hokimamad0
 
The Internet of Things (IoT) refers to a vast network of interconnected devic...
chethana8182
 
Blue and Dark Blue Modern Technology Presentation.pptx
ap177979
 
The Latest Scam Shocking the USA in 2025.pptx
onlinescamreport4
 
Crypto Recovery California Services.pptx
lionsgate network
 
Different Generation Of Computers .pptx
divcoder9507
 
The Internet of Things (IoT) refers to a vast network of interconnected devic...
chethana8182
 
Black Yellow Modern Minimalist Elegant Presentation.pptx
nothisispatrickduhh
 
原版北不列颠哥伦比亚大学毕业证文凭UNBC成绩单2025年新版在线制作学位证书
e7nw4o4
 
The Internet of Things (IoT) refers to a vast network of interconnected devic...
chethana8182
 
How tech helps people in the modern era.
upadhyayaryan154
 
AI ad its imp i military life read it ag
ShwetaBharti31
 
Slides Powerpoint: Eco Economic Epochs.pptx
Steven McGee
 
Google SGE SEO: 5 Critical Changes That Could Wreck Your Rankings in 2025
Reversed Out Creative
 
Microsoft PowerPoint Student PPT slides.pptx
Garleys Putin
 
The Monk and the Sadhurr and the story of how
BeshoyGirgis2
 

Janakiram web

  • 1. You can use multiple if...else…if statements, as in the previous chapter, to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable. Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation, and it does so more efficiently than repeated if...else ifstatements. Flow Chart The following flow chart explains a switch-case statement works. Syntax The objective of a switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used. switch (expression) { case condition 1: statement(s) break; case condition 2: statement(s) break; ... case condition n: statement(s) break; default: statement(s)
  • 2. } The break statements indicate the end of a particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases. We will explain break statement in Loop Control chapter. Example Try the following example to implement switch-case statement. <html> <body> <script type="text/javascript"> <!-- var grade='A'; document.write("Entering switch block<br />"); switch (grade) { case 'A': document.write("Good job<br />"); break; case 'B': document.write("Pretty good<br />"); break; case 'C': document.write("Passed<br />"); break; case 'D': document.write("Not so good<br />"); break; case 'F': document.write("Failed<br />"); break; default: document.write("Unknown grade<br />") } document.write("Exiting switch block"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html> Output Entering switch block Good job Exiting switch block Set the variable to different value and then try... Break statements play a major role in switch-case statements. Try the following code that uses switch-case statement without any break statement. <html> <body> <script type="text/javascript"> <!-- var grade='A'; document.write("Entering switch block<br />"); switch (grade) { case 'A': document.write("Good job<br />"); case 'B': document.write("Pretty good<br />");
  • 3. case 'C': document.write("Passed<br />"); case 'D': document.write("Not so good<br />"); case 'F': document.write("Failed<br />"); default: document.write("Unknown grade<br />") } document.write("Exiting switch block"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html> Output Entering switch block Good job Pretty good Passed Not so good Failed Unknown grade Exiting switch block Set the variable to different value and then try... While writing a program, you may encounter a situation where you need to perform an action over and over again. In such situations, you would need to write loop statements to reduce the number of lines. JavaScript supports all the necessary loops to ease down the pressure of programming. The while Loop The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates. Flow Chart The flow chart of while loop looks as follows − Syntax The syntax of while loop in JavaScript is as follows − while (expression){ Statement(s) to be executed if expression is true
  • 4. } Example Try the following example to implement while loop. <html> <body> <script type="text/javascript"> <!-- var count = 0; document.write("Starting Loop "); while (count < 10){ document.write("Current Count : " + count + "<br />"); count++; } document.write("Loop stopped!"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html> Output Starting Loop Current Count : 0 Current Count : 1 Current Count : 2 Current Count : 3 Current Count : 4 Current Count : 5 Current Count : 6 Current Count : 7 Current Count : 8 Current Count : 9 Loop stopped! Set the variable to different value and then try... The do...while Loop The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false. Flow Chart The flow chart of a do-while loop would be as follows − Syntax The syntax for do-while loop in JavaScript is as follows −
  • 5. do{ Statement(s) to be executed; } while (expression); Note − Don’t miss the semicolon used at the end of the do...while loop. Example Try the following example to learn how to implement a do-while loop in JavaScript. <html> <body> <script type="text/javascript"> <!-- var count = 0; document.write("Starting Loop" + "<br />"); do{ document.write("Current Count : " + count + "<br />"); count++; } while (count < 5); document.write ("Loop stopped!"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html> Output Starting Loop Current Count : 0 Current Count : 1 Current Count : 2 Current Count : 3 Current Count : 4 Loop Stopped! Set the variable to different value and then try... The 'for' loop is the most compact form of looping. It includes the following three important parts −  The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.  The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.  The iteration statement where you can increase or decrease your counter. You can put all the three parts in a single line separated by semicolons. Flow Chart The flow chart of a for loop in JavaScript would be as follows − Syntax The syntax of for loop is JavaScript is as follows −
  • 6. for (initialization; test condition; iteration statement){ Statement(s) to be executed if test condition is true } Example Try the following example to learn how a for loop works in JavaScript. <html> <body> <script type="text/javascript"> <!-- var count; document.write("Starting Loop" + "<br />"); for(count = 0; count < 10; count++){ document.write("Current Count : " + count ); document.write("<br />"); } document.write("Loop stopped!"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html> Output Starting Loop Current Count : 0 Current Count : 1 Current Count : 2 Current Count : 3 Current Count : 4 Current Count : 5 Current Count : 6 Current Count : 7 Current Count : 8 Current Count : 9 Loop stopped! Set the variable to different value and then try...
  • 7. <html> <script language = "javascript"> var a, b = 0; a = parseInt(prompt("Enter number to reverse: ")); while(a > 0) { b = b * 10 b = b + parseInt(a % 10) a = parseInt(a / 10) } document.write("Reversed number: ", b) </script> </html> JavaScript provides full control to handle loops and switch statements. There may be a situation when you need to come out of a loop without reaching its bottom. There may also be a situation when you want to skip a part of your code block and start the next iteration of the loop. To handle all such situations, JavaScript provides break and continuestatements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively. The break Statement The break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking out of the enclosing curly braces. Flow Chart The flow chart of a break statement would look as follows − Example The following example illustrates the use of a break statement with a while loop. Notice how the loop breaks out early once x reaches 5 and reaches to document.write (..) statement just below to the closing curly brace − <html> <body> <script type="text/javascript"> <!-- var x = 1; document.write("Entering the loop<br /> "); while (x < 20) { if (x == 5){ break; // breaks out of loop completely } x = x + 1; document.write( x + "<br />"); } document.write("Exiting the loop!<br /> ");
  • 8. //--> </script> <p>Set the variable to different value and then try...</p> </body> </html> Output Entering the loop 2 3 4 5 Exiting the loop! Set the variable to different value and then try... We already have seen the usage of break statement inside a switchstatement. The continue Statement The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continuestatement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop. Example This example illustrates the use of a continue statement with a while loop. Notice how the continue statement is used to skip printing when the index held in variable x reaches 5 − <html> <body> <script type="text/javascript"> <!-- var x = 1; document.write("Entering the loop<br /> "); while (x < 10) { x = x + 1; if (x == 5){ continue; // skip rest of the loop body } document.write( x + "<br />"); } document.write("Exiting the loop!<br /> "); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html> Output Entering the loop 2 3 4 6 7 8 9
  • 9. 10 Exiting the loop! Using Labels toControl the Flow Starting from JavaScript 1.2, a label can be used with break and continue to control the flow more precisely. A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. We will see two different examples to understand how to use labels with break and continue. Note − Line breaks are not allowed between the ‘continue’ or ‘break’statement and its label name. Also, there should not be any other statement in between a label name and associated loop. Try the following two examples for a better understanding of Labels. Example 1 The following example shows how to implement Label with a break statement. <html> <body> <script type="text/javascript"> <!-- document.write("Entering the loop!<br /> "); outerloop: // This is the label name for (var i = 0; i < 5; i++) { document.write("Outerloop: " + i + "<br />"); innerloop: for (var j = 0; j < 5; j++) { if (j > 3 ) break ; // Quit the innermost loop if (i == 2) break innerloop; // Do the same thing if (i == 4) break outerloop; // Quit the outer loop document.write("Innerloop: " + j + " <br />"); } } document.write("Exiting the loop!<br /> "); //--> </script> </body> </html> Example 2 <html> <body> <script type="text/javascript"> <!-- document.write("Entering the loop!<br /> "); outerloop: // This is the label name for (var i = 0; i < 3; i++) { document.write("Outerloop: " + i + "<br />"); for (var j = 0; j < 5; j++) { if (j == 3){ continue outerloop; } document.write("Innerloop: " + j + "<br />"); }
  • 10. } document.write("Exiting the loop!<br /> "); //--> </script> </body> </html> 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. JavaScript allows us to write our own functions as well. This section explains how to write your own functions in JavaScript. 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 aFunction 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>
  • 11. <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()
  • 12. { 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> What is anEvent ? JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page. When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc. Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable. Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events which can trigger JavaScript Code. Please go through this small tutorial for a better understanding HTML Event Reference. Here we will see a few examples to understand a relation between Event and JavaScript − onclick Event Type This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type. Example Try the following example. <html> <head> <script type="text/javascript"> <!-- function sayHello() { alert("Hello World") } //--> </script> </head> <body> <p>Click the following button and see result</p> <form> <input type="button" onclick="sayHello()" value="Say Hello" /> </form> </body> </html> Output onsubmit Event type
  • 13. onsubmit is an event that occurs when you try to submit a form. You can put your form validation against this event type. Example The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data. Try the following example. <html> <head> <script type="text/javascript"> <!-- function validation() { all validation goes here ......... return either true or false } //--> </script> </head> <body> <form method="POST" action="t.cgi" onsubmit="return validate()"> ....... <input type="submit" value="Submit" /> </form> </body> </html> onmouseover and onmouseout These two event types will help you create nice effects with images or even with text as well. The onmouseover event triggers when you bring your mouse over any element and the onmouseout triggers when you move your mouse out from that element. Try the following example. <html> <head> <script type="text/javascript"> <!-- function over() { document.write ("Mouse Over"); } function out() { document.write ("Mouse Out"); } //--> </script> </head> <body> <p>Bring your mouse inside the division to see the result:</p> <div onmouseover="over()" onmouseout="out()"> <h2> This is inside the division </h2> </div> </body> </html> Output HTML 5Standard Events
  • 14. The standard HTML 5 events are listed here for your reference. Here script indicates a Javascript function to be executed against that event. Attribute Value Description Offline script Triggers when the document goes offline Onabort script Triggers on an abort event onafterprint script Triggers after the document is printed onbeforeonload script Triggers before the document loads onbeforeprint script Triggers before the document is printed onblur script Triggers when the window loses focus oncanplay script Triggers when media can start play, but might has to stop for buffering oncanplaythrough script Triggers when media can be played to the end, without stopping for buffering onchange script Triggers when an element changes onclick script Triggers on a mouse click oncontextmenu script Triggers when a context menu is triggered ondblclick script Triggers on a mouse double-click ondrag script Triggers when an element is dragged ondragend script Triggers at the end of a drag operation ondragenter script Triggers when an element has been dragged to a valid drop target ondragleave script Triggers when an element is being dragged over a valid drop target ondragover script Triggers at the start of a drag operation ondragstart script Triggers at the start of a drag operation ondrop script Triggers when dragged element is being dropped ondurationchange script Triggers when the length of the media is changed onemptied script Triggers when a media resource element suddenly becomes empty. onended script Triggers when media has reach the end onerror script Triggers when an error occur onfocus script Triggers when the window gets focus
  • 15. onformchange script Triggers when a form changes onforminput script Triggers when a form gets user input onhaschange script Triggers when the document has change oninput script Triggers when an element gets user input oninvalid script Triggers when an element is invalid onkeydown script Triggers when a key is pressed onkeypress script Triggers when a key is pressed and released onkeyup script Triggers when a key is released onload script Triggers when the document loads onloadeddata script Triggers when media data is loaded onloadedmetadata script Triggers when the duration and other media data of a media element is loaded onloadstart script Triggers when the browser starts to load the media data onmessage script Triggers when the message is triggered onmousedown script Triggers when a mouse button is pressed onmousemove script Triggers when the mouse pointer moves onmouseout script Triggers when the mouse pointer moves out of an element onmouseover script Triggers when the mouse pointer moves over an element onmouseup script Triggers when a mouse button is released onmousewheel script Triggers when the mouse wheel is being rotated onoffline script Triggers when the document goes offline onoine script Triggers when the document comes online ononline script Triggers when the document comes online onpagehide script Triggers when the window is hidden onpageshow script Triggers when the window becomes visible onpause script Triggers when media data is paused onplay script Triggers when media data is going to start playing onplaying script Triggers when media data has start playing
  • 16. onpopstate script Triggers when the window's history changes onprogress script Triggers when the browser is fetching the media data onratechange script Triggers when the media data's playing rate has changed onreadystatechange script Triggers when the ready-state changes onredo script Triggers when the document performs a redo onresize script Triggers when the window is resized onscroll script Triggers when an element's scrollbar is being scrolled onseeked script Triggers when a media element's seeking attribute is no longer true, and the seeking has ended onseeking script Triggers when a media element's seeking attribute is true, and the seeking has begun onselect script Triggers when an element is selected onstalled script Triggers when there is an error in fetching media data onstorage script Triggers when a document loads onsubmit script Triggers when a form is submitted onsuspend script Triggers when the browser has been fetching media data, but stopped before the entire media file was fetched ontimeupdate script Triggers when media changes its playing position onundo script Triggers when a document performs an undo onunload script Triggers when the user leaves the document onvolumechange script Triggers when media changes the volume, also when volume is set to "mute" onwaiting script Triggers when media has stopped playing, but is expected to resume