Lec #5 Javascript
Lec #5 Javascript
Control Structures
In the vernacular of programming, the kinds of statements that make decision and loop around
to repeat themselves are called control structures. An important part of the control
structure is the condition.
if constructions
The simplest program decision is to follow a special branch or path of the program if a certain
condition is true.
Syntax:
if (condition) {
statement[s] if true
}
Ex:
if (myAge < 18) {
alert(“Sorry, you cannot vote.”);
}
if else constructions
Not all program decision are as simple as the one shown for the if construction. Rather than
specifying one detour for a given condition, you might want the program to follow either
of two branches depending on that condition. It is a fine but important distinction. In the
plain if construction, no special processing is performed when the condition evaluates to
false. But if processing must follow one of two special paths, you need the if… else
construction.
Syntax:
if (condition) {
statement[s] if true
} else {
statement[s] if false
}
Ex:
var febDays;
var theyear = 2008;
if (theyear % 4 == 0) {
febDays = 29;
} else {
febDays = 28;
}
JavaScript Assignment Operators
Loop - are used to execute the same block of code a specified number of times or while a
specified condition is true.
Given that x=10 and y=5, the table below explains the assignment operators:
JAVASCRIPT LOOPS
In JavaScript there are two different kinds of loops:
for - loops through a block of code a specified number of times
while - loops through a block of code while a specified condition is true
The for loop is used when you know in advance how many times the script should run.
Syntax
for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}
Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
document.write(i + “ ”);
}
</script>
</body>
</html>
Result
0 1 2 3 4 5 6 7 8 9 10
The while loop is used when you want the loop to execute and continue executing while the
specified condition is true.
While (var<=endvalue)
{
code to be executed
}
Ex:
var xsum = 0;
var x;
for(x=1;x<=10;x++)
{
xsum + = x;
}
document.write(x);
document.write(xsum);
Example
Explanation: The example below defines a loop that starts with i=0. The loop will continue to
run as long as i is less than 10. i will increase by 1 each time the loop runs.
<html>
<body>
<script type="text/javascript">
var i=0;
while (i<10)
{
document.write(i + “ “);
i=i+1;
}
</script>
</body>
</html>
Result
0123456789