Quantcast
Channel: The Joe Code
Viewing all articles
Browse latest Browse all 4

Controlling the flow

$
0
0

Code that does the same thing every time is not very useful. It only needs to be ran once and then you can write down the results and never use it again. Most code makes some decisions based on input or state. In order to make a decision in code one must control the flow. In computer science the pieces of code that control the flow are called control structures.

if (x)

The if statement checks that its input (the code between the parentheses) is true. Only if it is true will the next line or block be ran. A block is any code between matching curly braces {}. It could be a single line or multiple lines of code.

if (true)

    <this is ran>

 

if (true) {

    <this is ran>

<this also is ran>

<anything within this block is ran>

}

 

The if can be paired with an else. The else gets ran only when the if is false.

 

if (true) {

    // will be ran

} else {

    // won’t be ran

}

 

if (false) {

    // will not be ran

} else {

    // will be ran

}

 

You can chain multiple if elses together by putting an if right after the else. The next if will only be checked if the first if evaluates false. This means that only one block will ever be ran in the chain.

if (true) {

    //will run

} else if(true) {

//won’t run even though it is true

} else {

//won’t run

}

 

if (false) {

//won’t run

} else if(true) {

//will run

} else {

//won’t run

}

 

if (false) {

//won’t run

} else if(false) {

//won’t run

} else {

//will run

}

 

You do not need to end with an else by itself. However think about why you are not including it. Without the catchall else at the end of the chain, it is possible that none of the if’s are true and everything is skipped. You might want this behavior, just make sure.

 

Best Practice Tip: Always include the curly braces, even for a single line if statement. If you add another line of code and forget to add the {} later, you will get unexpected results.

if (true)

    <do something>

 

later…

if (x)

     <do something>

     <do something else>    // This line will always be ran no matter what the value of x is

 

if (x) {

    <do something>

    <do something else> // now it works

}



Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles



Latest Images