learn more...The "thinking" structure in JavaScript is found in the different types of conditional statements in the language. Used in concert with different types of comparative operators, conditional statements take the script on different routes, depending on what conditions have been met. At the same time that JavaScript has a thinking structure, so should designers. The ability to fluently write your own scripts rather than cutting and pasting someone else's design frees you from that person's vision of a page or page component. Let JavaScript figure out what the user is doing, and provide the user with an interesting response from JavaScript rather than something that you don't understand but can only cut and paste. The if StatementWhen testing for a condition to execute one or more statements, the if statement is the most common to use. It has the following general format: If (condition) {
Conditional Statement(s)
}
The conditional statement is executed only if the condition resolves to a Boolean true. Otherwise, the script continues to the next line after the second curly brace. Single or multiple conditions can be a part of the triggering condition. The following script contains a single condition that resolves as false so that the conditional statement is not executed. <html>
<head>
<title>False Condition</title>
<script language="JavaScript">
var alpha="High";
var beta="Low";
var message="The condition is not met";
if(alpha > beta) {
message="The condition is met";
}
document.write(message);
</script>
</head>
<body bgcolor="mediumspringgreen">
</body>
</html>
The expression found to be false is the condition that the variable alpha is greater than the variable beta. Because beta's value is Low and alpha's value is High, and because letters higher in the alphabet are resolved to be greater than letters lower in the alphabet, the false Boolean value prevented the script from executing the conditional statement. When the condition is changed to this: if(beta >alpha) {
the condition is found to be true, and the value of the variable message is changed to "The condition is met," and that's what appears on the screen. Multiple statements (compound statements) may appear within the curly braces in an if statement, allowing several different events to occur. For example, the following example has three different statements when a condition is met in the if statement: <html>
<head>
<title>Multiple Statements in Conditional</title>
<script language="JavaScript">
var alpha="Zebras";
var beta="Monkeys";
if(alpha > beta) {
//"Zebras" are greater than "Monkeys" because 'Z' is further up the alphabet than 'M.'
var polite="Please enter your name:"
var yourName=prompt(polite);
alert("Hiya " + yourName);
}
</script>
</head>
<body bgcolor="beige">
</body>
</html>
The else KeywordThe limitation of the if statement by itself is that no alternative branch is made available for a false condition. So another keyword, else, had to be added as an alternative form of if. The following format uses two sets of curly braces: if (condition) {
Conditional statement(s)
} else {
Different conditional statement(s)
}
For example, in the following example, a Boolean outcome forces a different branch (conditional statement) for a true or false value: <html>
<head>
<title>If Else</title>
<script language="JavaScript">
var stillSmokin="cough";
var quitSmokin="freeAtLast";
if(stillSmokin > quitSmokin) {
alert("You\'re going to die too soon fool!");
} else {
alert("Way to go Jack!");
}
</script>
</head>
<body bgcolor="whitesmoke">
</body>
</html>
In scripts with user input, such as forms or prompt functions, the else option provides a step for a second type of feedback. When the parser (interpreter) is going through the code line by line, the else statement is interpreted only if the first condition is false. The else if ConventionSometimes several options must be considered and several alternatives must be provided. The else if "statement" combines the if keyword and the else keyword into a conventionally used pair to create a unique statement. Combining else and if beyond a single if keyword differentiates it from the standard combination of if and else. Consider the following else if format: if (condition1) {
Conditional statement/s 1;
}
else if (condition2) {
Conditional statement/s 2;
}
else {
Conditional statement/s 3;
}
Because the else if "statement" is not a unique JavaScript word but rather is a programming convention, what is really happening is that the first if statement can be used with the first else statement. The else branch is to another if statement. Therefore, the last statement in an else if sequence is the lone else statement. <html>
<head>
<title>else if Structure</title>
<script language="JavaScript">
var puppy=prompt("What kind of pup would you like?","");
var puppyLC=puppy.toLowerCase( );
if(puppyLC=="greater swiss mountain dog") {
alert("Yes we have Swissies!");
}
else if(puppyLC=="great dane") {
alert("Yes we have those big wonderful Great Danes!");
}
else if(puppyLC=="irish wolfhound") {
alert("Yes we have the Gentle Giants!");
}
else {
alert("Sorry we only have giant dogs.");
puppy="information where to find that breed";
}
var message="<p>Come get your <b>" + puppy;
message +="</b> at<h3>Goliath\'s Breeders</h3>";
document.write(message);
</script>
</head>
<body bgcolor="palegreen">
</body>
</html>
The final else statement is typically used as a residual category, one in which the if statements exhausted the categories provided in the series of else if combinations. It works like a "none of the above" selection in a multiple-choice quiz. Using switch, case, and breakThe series of else if combination statements makes multiple comparisons against a condition. JavaScript provides an alternative to the repeated checking conditions using the switch and case statements: switch(expression) {
case alpha:
Alpha statements execute
break; // skip the other cases if case alpha==expression
case beta:
Beta statements execute
break; // skip the other cases if case beta==expression
default: //if no matches execute this
Tell user that nothing matches
}
To see how the switch and case keywords work together in a script, the next script takes a similar topic as was done with the else if statements. Using switch and case as statements, the switch statement includes what amounts to a true condition to be matched with the different cases. In most real-world applications of switch, the contents of the expression in the switch statement would be based on data from external input by a user. If the case matches the expression in the switch statement, the statements in that case are executed. Then the parser moves down to the next line and into the next case statement. To prevent that from happening, one of the statements within each case should be break. Because the break statement is executed only if the case statement for that segment of the script is true, the only time that break will affect the parsing of the script is when the condition that is sought in the switch statement has been found. Thus, when case resolves as true, break moves the script execution out of the larger switch condition (beyond the closing curly brace) and on to the next line of JavaScript. <html>
<head>
<script language ="JavaScript">
var puppy="Irish Wolfhound";
puppy=puppy.toLowerCase( );
var found;
switch(puppy) {
case 'great dane':
alert("Big Guy Breeders have Great Danes");
found="Big Guy Breeders phone: 555-9943";
break;
case 'irish wolfhound':
alert("Gentle Giant Breeders have Irish Wolfhounds");
found="Gentle Giant Breeders phone: 555-1912";
break;
case 'greater swiss mountain dog':
alert("The Swissy Center Breeders have Greater Swiss Mountain Dogs");
found="The Swissy Center Breeders phone: 555-5432";
break;
default:
alert("Contact the American Kennel Club for other breeds and breeders.");
found="American Kennel Club: 555-8989";
}
var message="<p><p>Be sure to contact them as soon as possible";
message +="<h2>" + found + "</h2>"
document.write(message);
</script>
</head>
<body bgcolor="lightgreen">
</body>
</html>
NOTE Using break is sometimes associated with poor programming practices, and it generally should be avoided in conditional statements, especially for novices. However, the break keyword is a perfectly legitimate one and has useful applications that conform with good programming; using break with switch and case is a good example of the break keyword's appropriate use. Placing the break at the end of every case within a switch statement is optional, but doing so is good practice to save processing time and protect against errors. Some uses of case and switch might mitigate against using break (for example, you might have more than a single matching case and want to launch different actions from within a switch statement with more than a single case), but, for the most part, using break with switch and case is a good practice. Conditional ShortcutsA ternary conditional can be substituted for a simple if / else statement. For example, both of the following scripts do the same thing, except that the ternary conditional is far more concise. Ternary Shortcut2 > 3 ? alert("It is true") : alert("Not true!");
Standard if/else Statementif(2 > 3) {
alert("It is true");
} else {
alert("Not true!");
}
You can save some coding time with the ternary operator conditional shortcut, and while it is perhaps not as clear as the standard if / else statement, once you get used to using the shortcut, you will find it helpful to get through a project quickly. The following script shows how the ternary shortcut appears in the context of a script: <html>
<head>
<title>Conditional Shortcut</title>
<script language="JavaScript">
2 > 3 ? alert("It is true") : alert("Not true!");
</script>
</head>
<body>
</body>
</html>
|
||||||
Disclaimer
1) E-articles is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringement, please read the terms of service and contact us to investigate the problem.
2) E-articles is not responsible for inaccuracies, falsehoods, or any other types of misinformation this article may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here. link to this article |