


It can’t be stated too often or too strongly that the first step of writing conditional code is to state the conditions clearly and make sure they do not conflict. All too often, the root problem is revealed as an unclear and/or conflicting statement of the necessary conditions. Problems with conditional execution are a very common issue posted to the forums. The conditions must make sense, not conflict with one another, and be testable from concrete values available to the code.

The first rule of writing conditional statements is to clearly and simply express the complete set of conditions in English. If( nSubTotal > 100) event.value = nSubTotal * 0.10 The following code is placed in the calculation event for the discount field: var nSubTotal = this.getField("subtotal").value The Acrobat JavaScript code for performing this conditional calculation is exactly the same as our English statement, only it is expressed in JavaScript syntax. To express this idea in English, in the context of our form we might say " If the Subtotal is greater than 100, then set a 10% discount." In this case, we are comparing the value of the order’s subtotal to the constant value 100, then placing a percentage of the subtotal into the discount field if the result of the comparison is true. For example, on an order form we might want to give the customer a discount if they spend more than $100. In computer programming, all decisions are made by comparing values. While there are others, none is as generic and widely used as the "if" statement. In Acrobat JavaScript, the primary element of conditional execution is the "if" statement. It is the ability to execute a piece of code depending on some condition. It's the only one JavaScript currently has, though.One of the most important features of any programming language is the ability to make decisions, called Conditional Execution. They can even be chained: serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine') īe careful, though, or you will end up with convoluted code like this: var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j ġ Often called "the ternary operator," but in fact it's just a ternary operator. Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification: userIsYoungerThan21 ? serveGrapeJuice() : serveWine() ServeDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine") This can be shortened with the ?: like so: var userType = userIsYoungerThan18 ? "Minor" : "Adult"

Here is an example of code that could be shortened with the conditional operator: var userType This is a one-line shorthand for an if-else statement.
