if Statements

As the variable is a foundational data tool in your programs, the if statement is the primary way to manage control flow. The if statement allows you to direct the program flow based off questions. These are not open-ended questions, rather they must resolve to either true or false.

For example, is the user a premium account holder? Is the user over eighteen? Does the user’s post contain over ten comment?

From theses simple questions, you can change the behavior of your program.

Using Boolean Operators

Boolean operators are the key to if statements. These operators compare two values and produce a true or false result. For example:

let falseValue = "Luke" == "Yoda"

The == checks for equality. In this case, the string Luke does not equal the string Yoda so the result of this comparison is false. It may seem confusing that there are two equal signs instead of one. The single equals sign is already used to assign values to variables. You get used to it over time.

You can also check to see if things are not equal.

let trueValue = "Luke" != "Yoda"

In this case, Luke does not equal Yoda, so the result is true.

Working with Braces

When you define an if statement, you start with the keyword if followed by the checked condition. You then provide a pair of curly braces. For example:

if age > 21 {
  // code goes here
}

If the age variable is over 21, then all of the code inside of the curly braces will be evaluated. If the age variable is false, then the curly braces are skipped.

Code inside the curly braces have a scope. Variables outside the braces can accessed as normal. However, any variables declared inside the braces will be inaccessible after the code exits the braces. These variables are considered “out of scope” and thus not able to accessed again. Should the code path encounter the if statement again, then new variables are created each time the program execution enters the curly braces and reclaimed when the program executions exists the braces.

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo: Using if Statements