The “If” Statement

What If?

The purpose of the “if” statement is to help control the flow of logic in a program. It can be used to execute one set of code in one situation and a different set of code in a different situation. I consider “if” to be the most basic control structure in programming.

Formula for If

The different languages represent “if” in slightly different ways, but almost all of the languages I know follow this basic formula.

if <boolean expression> then <primary statement> otherwise <secondary statement>

I have not used any language specific keywords for the formula so the actual syntax (wording and structure) is going to be different, but the above is the appropriate formula for nearly all languages I know.

So What Does it Look Like for Real?

JavaScript

// To get the results below open your browsers developer tools, 
// hit F12 on the keyboard. Then select the console and you 
// will be able to type the code below

if(<boolean-expression>) {
  <primary statement>
} else {
  <secondary statement>
}

How Does it Work?

When the boolean expression of the “if” statement is evaluated as true, the primary statement is executed and the secondary statement is not. When the boolean expression is evaluated as false, the exact opposite happens. The secondary statement is executed and the primary is not. Most languages do not require the use of the secondary statement at all. When the secondary statement is not included and the boolean expression is false, the primary statement is skipped and at the next statement after the if regular execution is resumed.

JavaScript

var result = 0;
undefined

if(1 === 1) {
  result = 1;
}

result;
1

if(1 === 2) {
  result = 2;
}

result;
1

// Using else
if(1 === 1) {
  result = 2;
} else {
  result = 3;
}

result;
2

if(1 === 2) {
  result = 3;
} else {
  result = 4;
}

result;
4

But I Want More

Well, your thinking, that’s all good and well if I only have two conditions but what if there are three or four possibilities? That my friend is where “else if” comes in. You can pretty much infinitely add to an “if” statement by using an “else if” statement. Let me show you how those work.

JavaScript

var someValue = 5;
var result = 0;

if(someValue < 3) {
  result = 1;
} else if(someValue < 6) {
  result = 2;
} else if(someValue < 9) {
  result = 3;
} else {
  result = 4;
}

result;
2

// result would have been 3 
// if we had not used "else if" and only used "if"

We’re Done

That is all there is to “if” statements. As Always, I hope you learned something from this, but if not please look at some of the other articles as they are more advanced and may lend you some insight in the world of software development.

Leave a Reply

Your email address will not be published. Required fields are marked *