Javascript allows to execute block of code(statements) in program on the basis of different conditions. It is also called decision making statements and they are
- if
- if else
- if else if
- switch
All decision making statements should be written in lower case.
Inside if-elseif-else, if their is only one or single statement, then curly braces {} are not required. If statements are more than one, that curly braces are mandatory.
Single Statement inside if else
<script>
let a = 10;
if(a == 10)
document.write("Hello");
else
document.write("World");
</script>
Single statement can be written without curly braces {} inside if elseif and else in javascript.
Multiple statements inside if else
<script>
let a = 10;
if(a == 10){
a = a + 20;
document.write(a);
}
else{
document.write("Hello ");
document.write("World");
}
</script>
Multiple statements must be written withcurly braces {} inside if elseif and else in javascript.
if
It checks given condition/expression is true or false, if condition is true, then executes the statement inside if block otherwise it skips the if block.
Syntax
if(condition)
{
//set of statements
}
Firstly if, checks given condition is true, if found true then only statements inside if block gets executed.
Example
<script>
let a = 50;
if(a < 70)
{
a = a + 10;
document.write(a);
}
</script>
if else
else statements executes only, when if condition fails.
Syntax
if(condition)
{
//set of statements
}
else{
//set of statements
}
Example
<script>
let a = 50;
if(a == 70)
{
document.write(a);
}
else{
document.write("Not equals to 70");
}
</script>
if else-if else
- It allows to check multiple conditions, using if elseif.
- elseif also allows to check condition like if.
- elseif can be used as many times as required.
- elseif always comes after if block.
- else is optional, but when all conditions fails, then only else block executes.
Syntax
if(condition)
{
//set of statements
}
elseif{
//set of statements
}
elseif{
//set of statements
}
elseif{
//set of statements
}
else{
//set of statements
}
Example
<script>
let marks = 40;
if(a <= 30)
{
document.write("Fail");
}
elseif(a <= 50)
{
document.write("Average");
}
elseif(a <= 70)
{
document.write("Good");
}
elseif(a <= 100)
{
document.write("Very Good");
}
else{
document.write("Absent");
}
</script>