|
|
JavaScript IF StatementThe beauty of programs lies in the fact that they are able to take decisions on the basis of information you provide. In all the programming languages I've come across, the If statement is extensively used for this purpose.
if (condition)
{
statements to execute
}
When JavaScript encounters an if statement, it checks the condition. If and only if, it is found to be true, the statements enclosed within the curly braces are executed. Note, the condition is always enclosed by a pair of parenthesis. Let's look at some examples.
var a = 5;
var b = 5;
if (a == b)
{
alert("The two quantities are equal");
}
First, two variables are initialized and assigned the same numeric value (5). The if statement then checks for their equality and pops-up an alert box if the two variables are equal.
The == is a 'Comparison Operator' while = is an 'Assignment Operator'. Be sure to use the comparison operator in a condition. If you use the assignment operator, the code will not function and JavaScript will NOT throw an error... it'll simply reassign the variable on the left. The 'Confirm' Box
confirm("Did you like the movie 'Godfather'?");
Click here to test a confirm box The confirm box has two buttons, an "OK" and a "Cancel" button. When the user clicks on "OK" the value 'true' is returned, while clicking on "Cancel" returns 'false'. We can capture this returned value in a variable and test it through an if statement. Let's look at a similar real world example:
var response = confirm("Have you understood the confirm box?");
if (response == false)
{
alert("Go thru the sessions again");
}
Click here to test the code
Page contents: Javascript if statement, javascript condition statement, javascript confirm box
Page URL: http://www.webdevelopersnotes.com/tutorials/javascript/ javascript_if_statement.php3
|
|