- Home
- javascript Tutorial
- decision-making
Desicion Making
Very often while writing code, there is a need for performing different actions for different decisions. Conditional statements are used to meet those needs. Javascript offers the following conditional statements
if condition to decide to execute a block of code when the specified condition is true.
else condition to decide to execute a block of code when the condition specified in if is false.
else if to specify a new condition to execute a new block when the first condition is false
switch to jump between many alternative blocks of code based on the requirement
The if Statement
if condition to decide to execute a block of code when the specified condition is true.
Syntax:
block of code to be executed if the condition is true
}
Example
<html>
<body>
<p id="demo">a is greater than b</p>
<script>
var a=10;
var b=20;
if (a<b) {
document.getElementById("demo").innerHTML = "a is less than b";
}
</script>
</body>
</html>
Output
The if else statement:
The 'if...else' statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way.
Syntax:
Statement(s) to be executed if expression is true
}
else{
Statement(s) to be executed if expression is false
}
Example:
<body>
<script>
var a=10;
var b=20;
if (a>b) {
document.write("a is less than b");
}
else{
document.write("a is greater than b");
}
</script>
</body>
</html>
Output:
The else if Statement
else if statement is used to specify a new condition which will be assesed when the first condition is false.
Syntax:
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}
Example:
<html>
<body>
<script>
var greeting;
var time = new Date().getHours();
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.write(greeting);
</script>
</body>
</html>
Output:
The Switch Statement
switch statement is used to select one of many blocks of code to be executed.
Syntax:
case n:
code block
break;
case n:
code block
break;
default:
code block
}
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
Example:
<html>
<body>
<script>
var i=2;
switch(i){
case 0:
document.write("i equals to 0");
break;
case 1:
document.write("i equals to 1");
break;
case 2:
document.write("i equals to 2");
break;
default:
document.write("i equals to 0 or 1 or 2");
}
</script>
</body>
</html>