Control State
Control State
JavaScript has a similar set of control structures like the other languages such as c, c++ and Java.
conditional statements are supported by if and else described below: Conditional Statements • In
JavaScript we have the following conditional statements as defected
• else (statement) specify a block of code to be executed, if the same condition isfalse
• else if (statement) specify a new condition to test, if the first condition is false
Example
Prg1:
<!DOCTYPE> <html> <head></head> <body>
<script type="text/javascript">
if (age >18)
else
Prg2:
<html> <head></head> <body>
<p>Display Good Day! if the hour is less than 18:00: otherwise Display Good
Eveening</p>
<script type="text/javascript">
else
</script> </body>
Prg3:
<!DOCTYPE> <html><body>
if (n== 1)
day = "Sunday";
else if (n== 2)
day = "Monday";
else if (n==3)
day = "Tuesday";
else if(n==4)
day = "Wednesday";
else if(n==5)
day = "Thursday";
else if(n==6)
day = "Friday";
else if(n==7)
day = "Saturday";
}
SWITCH
The switch statement is used to select one of many blocks of the code to be executed in a
program described below. the switch expression is evaluated once and the value of the expression is
compared with the values of each case. if there is a match found, then the associated block of code is
executed otherwise default code block is executed.
switch (expression)
case n:
code block
break;
case n:
code block
break;
default:
Example: Use the weekday number to calculate weekday name with the help of getday() method.the
getday() method returns the weekday as a number between 0 and 6. (Sunday=0,Monday=1, Tuesday=2
..)
<!DOCTYPE> <html><body>
<script>
var da= prompt(“Enter 1 for Sunday, 2 for Monday ………….7 for Saturday”);
da= parseInt(n);
switch(n){
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";}
• do/while - also loops through a block of code while a specified condition is true
*For Loop The for loop is best suited when you already know the number of times the statements
should be executed. the loop executes until the condition becomes false.
Statements
Example:
<!DOCTYPE html>
<html> <body>
<script>
* For..in Loop
The for/in loop: the JavaScript for/in statement loops through the properties of an object
explain below.