If Statements
The If condition determines that certain code is to be executed only if a specified condition is true.
| Syntax |
if ( condition )
{
JavaScript Statements
} |
If the 'condition' evaluation returns true, the JavaScript statement is executed, but if the condition turns out to be false, JavaScript statements will be skipped. Any number of If statements can be included in a program.
| Example |
var year = 2000;
if ( year = = 2000)
{
document.write ( " Leap year ");
} |
If - Else Statement
It is similar to If statement, but the only difference is that instead of skipping the JavaScript statements, when encountered condition turns to be false, the control is passed to the Else block. The Else block then executes the JavaScript statements contained in it.
| Syntax |
if ( condition )
{
JavaScript Statements;
}
else
{
JavaScript Statements;
} |
The Else block can embed any number of ' if-else blocks ' in it.
| Example |
var num;
if ( num > = 85 )
{
document.write ( "Excellent " );
}
else
{
if ( num > = 65 && num < 85 )
{
document.write( " Good " );
}
else
{
if( num >=50 && num<65)
{
document.write ( " Fair " );
}
else
{
document.write ( " V. Poor " );
}
}
} |
Switch Statement
The switch statement is similar to the if-else statements. It is better to use switch statement, if you want to test a single expression, multiple times. Switch statement lets you conveniently execute a different statement depending on the value of an expression. Switch statement selects from a number of alternatives.
| Syntax |
switch ( expression )
{
Case 1:
statement 1;
break;
Case 2 :
statement 2;
break;
default:
default statement;
} |
Expression is the variable which is to be tested. 'Case' is the value of the variable, you are testing for. 'Statement' consists of JavaScript code that you wish to execute if the case tests to true. 'Break' is included so as to pass control out of the switch otherwise, statements in multiple cases might be executed whether they match or not. The 'default' case allows you to specify the default statement to execute if all other cases fail to match.
Break and Continue Statements
JavaScript provides commands through which iterations of a loop can be skipped or stopped or to pass the control out of the loop. These are Break statement, and continue statement.
Break statement
Break statement immediately terminates the loop construct. The break statement causes an exit from the innermost loop. It is useful if you want to prematurely end a loop or if you want to come out of a loop because of error prone statements. It only involves a writing break, to move you out of the conditional statement and shifts you to the first statement outside of the conditional statement. Break statement may be used to skip out of a while, if, switch, do-while or for statements
| Example |
var x;
if ( x % 2 = = 0 )
{
break;
}
else
documenent.write ( " Odd number " ); |
|