Javascript If Statement

There are two condition control structures - If and Switch.

If statement is the most commonly used in conditional statements. In the following cases, we are using If statement.


To check single expression

If(condition ){
    Statement1;
}     

Example

<script>
var a = 5;
if(a == 5) {
document.write("Number : " + a );
}  
</script>

If the expression in the 'if statement' is true, then 'statement1' is executed.


Execute one of two statements based on the condition

In this, if the expression within the if statement is true, then the statement within the if is executed otherwise the statement within the else is executed.

If(condition ){
    Statement1;
}
else{
    Statement2;
}


If the expression in if statement is true, then 'statement1' is executed, If the expression in if statement is false, then 'statement2' is executed.

Example

<script>
var a = 5;
if(a == 10) {
document.write("Number : " + 10 );
}  
else{
document.write('Number is not equal to 5'); 
}
</script>

Multiple Conditions

If ...elseif.... else statements are used where multiple statements are need to be executed.

if (condition 1){   
    Statement 1;
}
else if (condition 2){  
    Statement 2;
}
else if (condition 3){   
    Statement3}
else{   
    Other Statement
}

Example

<script>
var a = 5;
if(a < 5) {
document.write('Number is less than 5');
}  
else if(a == 5){
document.write('Number is equal to 5'); 
}
else{
document.write('Number is greater than 5');
}
</script>




Read more articles


General Knowledge



Learn Popular Language