Javascript If Else
JavaScript use a conditional statement which is used to perform different tasks according to the conditions. There are three forms of statements use in JavaScript.
- if Statement.
- if else Statement.
- if else if Statement.
if statement
The if statement is used in JavaScript to execute the code if the condition is true or false.if (condition){ //
//content to be evaluated
}
<!DOCTYPE html>
<html>
<body>
<script>
var x=50;
if(x>30){
document.write("value of x is greater than 30");
}
</script >
</body>
</html>
Value of x is greater than 30
if else statement
The if else statement is use for either condition is true of false. Syntaxif(condition)
{
// set of statements
}
else
{
// set of statements
}
<!DOCTYPE html>
<html>
<body>
<script>
var x=20;
if(x%2==0){
document.write("x is even number");
}
else{
document.write("a is odd number")
}
</script>
</body>
</html>
X is even number
If else if
It checks the content only, if expression is true from several expressions. if else if statement is an advanced form of if else statement. SyntaxIf (condition1)
{
Statement(s) to be executed if condition 1 is true
}
else if (condition 2)
{
Statement(s) to be executed if condition 2 is true
}
else if (condition 3)
{
Statement(s) to be executed if condition 3 is true
}
else
{
Statement(s) to be executed if no condition is true
}
<!DOCTYPE html>
<html>
<body>
<script>
var x=50;
if (x==10){
document.write("x is equal to 10");
}
else if(x==50){
document.write("x is equal to 50");
}
else if(x==30){
document.write("x is equal to 30");
}
else{
document.write("a is not equal to 10, 50 or 30");
}
</script>
</body>
</html>
x is equal to 50