Java Script Control Structures and Conditional Statements
Java Script Control Structures and Conditional Statements
Java Script
Script Control
Control
Structures
Structures and
and
Conditional
Conditional Statements
Statements
Conditional Statements
in JS
• The conditional statements available
in JavaScript for decision making
are:
• if statement
• if...else statement
• if...else if....else statement
• switch statement
if the conditional
statement
<html>
<body>
<script type="text/javascript">
var exforsys = 20
if (exforsys < 30)
{
document.write("<b>Welcome</b>")
}
</script>
</body>
</html>
If-else statement
<html>
<body> Output of the above
<script type="text/javascript"> script as produced in a
var exforsys = 40 HTML page is shown
if (exforsys < 30) below:
{
document.write("<b>Welcome</b>")
}
else
{
document.write("<b>Thank You!</b>")
}
</script>
</body>
</html>
Conditional Statement part-2
if-else-if statement
<html>
<body>
<script type="text/javascript">
var exforsys = 20
if (exforsys < 5)
{
document.write("<b>Welcome</b>")
}
else if (exforsys > 5 && exforsys < 10)
{
document.write("<b>Have a nice day!</b>")
}
else
{
document.write("<b>Thank You!</b>")
}
</script>
</body>
</html>
switch statement
<html>
<body>
<script type="text/javascript">
var exforsys = 4
switch (exforsys)
{
case 1:
document.write("<b>Hi!</b>")
break
case 2:
document.write("<b>Welcome</b>")
break
case 3:
document.write("<b>Thank You!</b>")
break
default:
document.write("<b>Have a Great Day!</b>")
}
</script>
</body>
</html>
JavaScript Iterative
Structures - Part I
• Looping can be achieved in JavaScript
using various statements:
• for loop
• while loop
• do..while loop
• for..in loop
For-loop statement
<html>
<body>
<script type="text/javascript">
var exfor=1
for (exfor=1;exfor<=15;exfor++)
{
document.write("Value is: " + exfor)
document.write("<br />")
}
</script>
</body>
</html>
Note : The break command is used for breaking the loop
and continuing with the execution of the code that follows
after the loop.
The command continue is used for breaking the current
loop and proceeding with the next value.
while-do
<html>
<body>
<script type="text/javascript">
var exfor=1
while (exfor<=15)
{
document.write("Value is: " + exfor)
document.write("<br />")
exfor=exfor+1
}
</script>
</body>
</html>
do-while
<html>
<body>
<script type="text/javascript">
var exfor=1
do
{
document.write("Value is: " + exfor)
document.write("<br />")
exfor=exfor+1
}
while (exfor<1)
</script>
</body>
</html>
Arrays in JS
• In JavaScript, arrays are objects that have some special
functionality.
• JavaScript arrays have dynamic length.
• Defining an Array in JavaScript:
Array is defined in JavaScript by making use of the
keyword new.
• General format of defining array in JavaScript is as follows:
var varaiblename = new Array( )
eg. Var your_list=new Array(100);