Introduction to Programming

Page 3

 

 

Learn About Conditionals or Else

If and if-then statements are commonly used conditionals in most programming languages. They check a condition and then take the appropriate action based on whether the condition is true or false. The basic structure of an if-then statement is:


if (condition)

{
(action);
}

else

{
(else-action);
}


Conditionals always start with the word if. If the condition is true, then the action within the body is applied and the appropriate results are produced. It's possible for more than one action to be applied. If the condition is false, then else-action, also in the body, is applied and produces the appropriate return value. If you're thirsty for more about the if and if-then structure in JavaScript, take a peek here.

The if statement only evaluates whether a function is true, and then proceeds to the next condition or line of code. The nice thing about using an if-else instead is that you have more control over the flow of the program. In addition, the else allows you to create command blocks (grouped commands) when the condition is false. This eliminates the work of writing several if statements to create a command block since they can all be combined and listed inside the else statement.

Predicates, or conditional operators as they're called in JavaScript, are functions that return true or false values. They are frequently used in conditionals and can evaluate to one or two different values depending on the condition. Sometimes it's easier to use a conditional operator than an if-then statement. Other times, they are used in conjunction with the if-then statements to produce the desired results. It all depends on the situation. You can usually identify them by the question mark that they end with. The structure for conditional operators is as follows:


(condition) ? val1 : val2


Let's say you wanted to create a function called printName that checked to see if the variable name is equal to "Deeter" and then returned something accordingly. If name is not equal to "Deeter" then the function would return something else. Here's what it would look like:


function printName(name) {

alert((name == "Deeter")?"The monkey likes Deeter":"Who invited you to this party?");

}


Now let's take this all a step further with loops.


To Next Page

 

BreBru.com Information Technology HTML