Conditionals

“Do you want to add on the extra screen protectors to your purchase, for $9.99?” The helpful phone store employee has asked you to make a decision. And you may need to first consult the current state of your wallet or bank account to answer that question. But obviously, this is just a simple “yes or no” question.

There are quite a few ways we can express conditionals (aka decisions) in our programs.

The most common one is the if statement. Essentially, you’re saying, “If this condition is true, do the following…”. For example:

  1. var bank_balance = 302.13;
  2. var amount = 99.99;
  3. if (amount < bank_balance) {
  4. console.log( "I want to buy this phone!" );
  5. }

The if statement requires an expression in between the parentheses ( ) that can be treated as either true or false. In this program, we provided the expression amount < bank_balance, which indeed will either evaluate to true or false depending on the amount in the bank_balance variable.

You can even provide an alternative if the condition isn’t true, called an else clause. Consider:

  1. const ACCESSORY_PRICE = 9.99;
  2. var bank_balance = 302.13;
  3. var amount = 99.99;
  4. amount = amount * 2;
  5. // can we afford the extra purchase?
  6. if ( amount < bank_balance ) {
  7. console.log( "I'll take the accessory!" );
  8. amount = amount + ACCESSORY_PRICE;
  9. }
  10. // otherwise:
  11. else {
  12. console.log( "No, thanks." );
  13. }

Here, if amount < bank_balance is true, we’ll print out "I'll take the accessory!" and add the 9.99 to our amount variable. Otherwise, the else clause says we’ll just politely respond with "No, thanks." and leave amount unchanged.

As we discussed in “Values & Types” earlier, values that aren’t already of an expected type are often coerced to that type. The if statement expects a boolean, but if you pass it something that’s not already boolean, coercion will occur.

JavaScript defines a list of specific values that are considered “falsy” because when coerced to a boolean, they become false — these include values like 0 and "". Any other value not on the “falsy” list is automatically “truthy” — when coerced to a boolean they become true. Truthy values include things like 99.99 and "free". See “Truthy & Falsy” in Chapter 2 for more information.

Conditionals exist in other forms besides the if. For example, the switch statement can be used as a shorthand for a series of if..else statements (see Chapter 2). Loops (see “Loops”) use a conditional to determine if the loop should keep going or stop.

Note: For deeper information about the coercions that can occur implicitly in the test expressions of conditionals, see Chapter 4 of the Types & Grammar title of this series.