Implementing Flow Control in JavaScript
JavaScript's flow control structures close resemble thoce found in Java.
Conditional Statements
if-else Statemenst
<html>
<head>
<meta charset="UTF-8">
<script>
let month = 10;
if (month === 12 || month === 1 || month === 2) {
alert("Winter season: Enjoy hot pot meals");
} else if (month >= 3 && month <= 5) {
alert("Spring season: Fresh vegetables are recommended");
} else if (month >= 6 && month <= 8) {
alert("Summer season: Perfect for barbecue and beer");
} else if (month >= 9 && month <= 11) {
alert("Autumn season: Time for seasonal nourishment");
} else {
alert("Invalid month entered");
}
</script>
</head>
<body></body>
</html>
switch Statements
<html>
<head>
<meta charset="UTF-8">
<script>
let currentMonth = 10;
switch (currentMonth) {
case 3: case 4: case 5:
alert("Spring arrives with blooming flowers");
break;
case 6: case 7: case 8:
alert("Summer brings warm weather and outdoor activities");
break;
case 9: case 10: case 11:
alert("Autumn features colorful foliage");
break;
case 1: case 2: case 12:
alert("Winter offers snowy landscapes");
break;
default:
alert("Month value is invalid");
}
</script>
</head>
<body></body>
</html>
Loop Structures
while Loop
<html>
<head>
<meta charset="UTF-8">
<script>
let counter = 1;
while (counter <= 10) {
alert(counter);
counter++;
}
</script>
</head>
<body></body>
</html>
do-while Loop
<html>
<head>
<meta charset="UTF-8">
<script>
let total = 0;
let number = 1;
do {
total += number;
number++;
} while (number <= 10);
alert("Sum: " + total);
</script>
</head>
<body></body>
</html>
for Loop
<html>
<head>
<meta charset="UTF-8">
<script>
let result = 0;
for (let index = 1; index <= 10; index++) {
result += index;
}
alert("Total: " + result);
</script>
</head>
<body></body>
</html>
Practical Example: Multiplication Table
<html>
<head>
<meta charset="UTF-8">
<script>
for (let row = 1; row <= 9; row++) {
for (let col = 1; col <= row; col++) {
document.write(col + "×" + row + "=" + (row * col) + " ");
}
document.write("<br/>");
}
</script>
</head>
<body></body>
</html>