3.1. The if Statement

When someone asks if you are going to the Yankees' game and you tell them, "Only if it's not raining," you've expressed a condition for attending the game. The result of that condition determines whether you go. In other words, if it doesn't rain, then you'll go to the ballgame. If it does rain, then you won't go.

AppleScript has a special statement called the if statement that allows you to take action based on a condition. Here is the general format of the if statement:

if Boolean-expression then
statement
statement
...
end if

A Boolean-expression is an expression that produces a true or false result. It may be the result of a comparison, such as one between two numbers or two strings.

If the result of evaluating Boolean-expression is true, then the statements that follow — up to the end if — are executed. If the result of the evaluation is false, these statements are skipped. If they are skipped, execution continues with the statement that immediately follows the end if in the program.

If you were to express your condition for attending the ballgame in AppleScript-ese, it might look something like this:

if it's not raining then
display dialog "Take me out to the ballgame!"
end if

If it is not raining, the display dialog that follows is executed, presumably to announce your intentions to attend the ballgame. If it is raining, the display dialog that follows is skipped.

Here's an actual AppleScript if statement that sets the number stored in the variable ...

Get Beginning AppleScript® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.