4 - Conditional Statements
Often times while building code, you will want to check the truth value of a statement. A couple examples of what I mean by that is checking if two integer values are equal, or checking if a variable is defined. Conditional statements can have multiple paths that the code can flow down. Code paths are sometimes called branches. There can be hundreds of different branches, but it is a good practice to keep the number of branches to an absolute minimum. Not only will it save debugging time, it will also make your code smaller and more readable.
If statements are the most common conditional statement that you will use. An if statement will evaluate whatever logic is held within it and either execute the code within condition within the if statement is true, or skip the code within if false.
An additional else statement can be added to run a different set of code if the conditions in the if statement are not met. In addition to providing another code path, else statements are useful for catching conditions that you might not think of right away. For instance, if you are creating a function which takes in two numbers and adds them together, you may use an if statement to compare them. You could add an else statement at the end to handle any number combinations that your if statements might not cover. They can also be used for conditions that cover all other conditions that may be used. For example, if you only want a statement to be debugged when x is equal to 1, but you want another debug statement for when that is not true. You can use an else statement to cover all of those other branches.
If you would like to have multiple related conditional statements, you can use multiple else if statements until all cases are met. Just to note, you can also use an else statement after a sequence of if/elses. Again, it can be used to cover instances that you might not think of, or a bunch of different instances.
nested if statements
Conditional statements can also be nested within other conditional statements. This allows for more complex logic within your code. Take some time to design your code flow, and minimize that number of code paths that you have. As stated earlier, this will help you solve a lot of work in the long run. Trust me.