How to Know When to Use Conditionals and Loops

Introduction

Welcome! Lately, a lot of people have been telling me they struggle with knowing when to use a loop or a conditional, or just how to go about solving a problem. They ask me how I know, and it really depends on what the problem is, but there are ways to tell what needs to be used. A lot of times, though, there is more than one right answer. I decided to write this article to hopefully help some of you out when deciding on how to start a solution. Let’s jump right in!

NOTE: The examples in this article are written in JavaScript, but it is very similar in languages such as Java and C++.

Loops

When might you want to use a loop? Loops are used when you want to execute some block of code over and over again under certain conditions. There are a few different types of loops including the for, while, do…while, and forEach loops. Keep in mind different languages have different ways of implementing each of these loops!

Googling Tip: if you don’t know the syntax for the type of loop you need, you can type in what kind of loop you want to check out followed by the name of the language you are using.
Example: “for loop in java”, “while loop in C#”, etc…

For Loop

The for loop includes a variable used as an iteration counter, a condition which the iteration counter must meet for the loop to execute, and an updating operation for the iteration counter. The for loop can be used to loop through an array, allowing you to access each index of the array individually using the iteration counter. You may also want to use this loop to visit each number in a range of numbers.

Example (iterating through an array):
for (let i = 0; i < array.length; i++) {
    console.log(array[i]);
}
Example (iterating through a range of numbers – visiting every other number):
for (let i = 1; i <= num; i += 2) {
    console.log(i);
}

Breaking down the examples above, i is our iteration counter, initialized to the value we want to start with. Iterating through an array, you usually want to start at 0, as that is the first index of an array in most languages. Next, is the condition, which has to be true for the loop to run. The condition has to evaluate to a boolean value (true or false). If the condition is true, the loop runs, otherwise, it does not.

The last part in the set up of the for loop before the commands to be executed, is the updating operation for the iteration counter. You can update the counter any way you would like, as long as it makes sense (meaning you can’t reassign the iterator to a char value). If you want to go through every single number, you would want to do i++, i += 1, or i = i + 1 (which are all the same thing). If you want to visit every other number, try i += 2. You can also decrement your counter using i–, i -= 1, or i = i – 1 (again, all do the same thing). You can determine how much the counter should change on each iteration based on what you want to do. 

While Loop

The while loop is a set of commands only executed while a specified condition is true. This can be helpful if you don’t have a certain range that you want to iterate through, but you know that you want to loop through a certain set of commands while something is true

NOTE: You can translate a for loop into a while loop, and sometimes you can translate a while loop into a for loop.

Example (iterating through each element in an array):
let i = 0;
while (i < array.length) {
    console.log(array[i]);
    i++;
}
Example (looping until the condition is false):
while (array.includes(3)) {
    array.pop();
}

The first example above is a while loop that does the same thing as the first for loop example. You start by initializing your iteration counter before the loop begins (not inside the loop, or each time it loops through, it will reset i to 0). Inside the parentheses immediately after the keyword while, you will choose a condition. As long as this condition is true, the loop will continue. The last part, of the first example is include the commands you want to execute, then increment or decrement your counter as necessary.

The next example tells the block to execute until the array no longer contains any 3s. This block will remove the last element of the array each time through until every 3 has been removed. The method in the condition returns a boolean, meaning that when you call .includes(*value*) on an array or a string (in JavaScript), it will evaluate as true or false, indicating whether the array or string includes the particular value.

Do-While Loop

Up until now, we have seen loops that only run if a condition is true from the beginning. If the condition starts out false, the previous loops will never run. That is not the case with the do…while loop. This loop ensures that the commands in your loop are run at least once, because the condition comes after you tell the loop what it is meant to do. 

Example (print a menu with a choice to exit):
do {
    console.log("Menu:");
    console.log("1. Menu item");
    console.log("2. Another item");
    console.log("0. Exit");
    // let opt = accept input
} while (opt !== 0);

The above example prints the “Menu” and accepts input, and if the user enters a 0, the loop no longer executes, but if the user does not want to exit, you may want to include more code below the accepted input to execute depending on the user’s choice. The condition following while, in the parentheses, should follow the same guidelines as for the condition of the regular while loop.

For-Each Loop

The forEach loop is a loop that visits every element in an array or list, or even every key in an object. This may be different for each language. In Java, this is called an enhanced for loop, but there are methods of certain classes that iterate over a collection. In JavaScript, there is a forEach method for arrays, and an enhanced for loop kind of setup for iterating through properties of an object. For this article, I will be focusing on the enhanced for loop setup. 

The for loop defines a variable to store an element, and the collection it is looping through. This kind of loop goes through every single element of the collection. As it loops through, the variable defined in the loop definition holds the value of the element of the current iteration.

Example (iterating through an array):
let array = ['one', 'two', 'three'];
for (let element of array) {
    console.log(element);
}
// prints:
// one
// two
// three

NOTE: In JavaScript, the keyword of used in this loop is changed to in if you want to loop through properties of an object.

This loop is most helpful if the index of any given element is not extremely important to your code. You can use a method to find the index of the element, but in most languages, that returns the first occurrence of the value, which isn’t super helpful if your collection may repeat values.

Break and Continue

When working with loops, it is also helpful to know that you can break out of a loop at any time, and you can also skip part of a loop if you choose. To do this we use the break and continue commands. These are one-word statements used to get more control of your loop. Some languages have some extra-special ways you can use these commands, but we will go over the basics, just using the one word. These commands work in most cases, they work in the loops that are defined here in this article. There may be some limitation in certain loop-imitating methods like the methods you call on an array in JavaScript.

let stillTrue = true;
while (true) {
    console.log("This is true");
    stillTrue = !stillTrue;
    if (!stillTrue) {
        continue;
    }
    console.log("Still totally true");
}

The above is an infinite loop, which is pretty bad, definitely not something you want to do, but that’s not the point. Before the loop, we define a boolean variable stillTrue, and this value is changed to the opposite of its current value. Every time that this loop executes, it will print to the console, “This is true,” but “Still totally true” will only execute every other time. The command continue is used to skip the remainder of the commands in the loop, and continue on to the next iteration.

Now, let’s fix this loop, only allowing it to execute 10 times. We could definitely change this loop in many ways to only execute 10 times, but let’s use the break statement to see how it works!

let counter = 1;
let stillTrue = true;
while (true) {
    console.log("This is true");
    stillTrue = !stillTrue;
    if (!stillTrue) {
        continue;
    }
    console.log("Still totally true");
    if (counter == 5) {
        break;
    }
    counter++;
}

Now, we have added a counter, initialized it to 1, and we added an updating operator at the end of the loop to increment the counter. This loop will run through 10 times. We only allow the counter to get to 5, though. This is because of the continue statement we included before, so the counter is only incremented every other time the loop is executed. Once the conditions are right and the break statement is executed, that is the end of the loop. The loop will no longer execute at all, commands that may come after the loop will now be executed.

NOTE: The break and continue statements only break the flow of the closest loop to the statement, meaning if the break or continue statement is inside of a loop that is nested in another loop, you will break the flow of the inner loop, but continue as normal in the outer loop.

Conditionals

So, what might conditionals be used for? Conditionals are used when you have a specific case or set of cases that you want to handle a certain way. This makes sure that a certain lines of code only execute if a condition is true at the time the conditional statement is encountered. Conditionals include if statements, which can be expanded to if…else statements or if…elseif…else statements. In some cases you may use a ternary operator (? :) rather than an if…else statement. The switch…case statement is a neat conditional statement that we will go over here as well.

If-Elseif-Else statements

if…elseif…else statements are conditional statements used if you have a particular case that you want to handle using a certain set of commands. The elseif block is for any additional cases you may want to handle a separate way only if the if statement did not already handle this certain case. Depending on the language, elseif may be two separate words, or they may be squished together. The else block is used to handle everything that was not handled by the if statement. The if statement can be a standalone block of code, but every elseif and else block must have an immediately preceding if statement. Let’s check out an example how this works:

if (x === 3) {
    console.log("This is three");
} else if (x <= 5) {
    console.log("This is less than or equal to five");
} else {
    console.log("This is greater than five");
}

Let’s say we let x = 3. This satisfies more than one condition. It is important to note that when this happens, x will be caught by the first block that is satisfied by its value, which in this case is the if statement, and it will ignore the rest of the elseif block and skip the else block. So, in this case, if x is set to 3, this code will output “This is three” to the console. If we let x = 0, it will output “This is less than or equal to five” and any number above 5 will result in the output of “This is greater than five.

The Ternary Operator

The ternary operator is represented by ? :. It is a lot like an if…else statement except it is not a standalone statement. It can be used for inline decisions when you are choosing a value to assign to a variable or choosing a value to return. Let’s see how this works:

let isLessThanFive = (x < 5) ? true : false;
return (isLessThanFive) ? x : undefined;

NOTATION:

(condition) ? value if condition is true : value if condition is false;

So if the condition in the parentheses evaluates to true, then the value following the question mark (?) before the colon (:) will be either assigned to the variable or returned for the first example set or the second, respectively. If the condition evaluates to false, the value following the colon is used instead. 

Let’s say x in the example above is 3, so isLessThanFive will be assigned the value true. If we used any value greater than or equal to 5, then the value of isLessThanFive would be false. The next statement says we should return x if isLessThanFive is true, or return undefined if it is false. So if we put these two parts together, anything less than 5 will return the value of x. If x is greater than or equal to 5, this code will return undefined.

Switch-Case Statements

switch statements are another type of conditional, but expects a predictable value in a set of possible values, like the input for the menu item from the do…while example earlier. In that case, we are expecting either a 1, 2, or 0. We can choose what to do for each case.

NOTE: The accepted values are not limited to integers, it can be any kind of primitive value.

You can also use a default case (which is recommended) to handle any unexpected input or input that is more general or unaccounted for.

We also use a break statement at the end of each case, or it will result in a waterfall effect, running through each case starting with the case that was intended to be handled, all the way until the end of the cases. The break statement in the switch…case block will only break from the flow of the switch…case statement, and not any surrounding loops. Let’s look at an example:

switch (value) {
case 1:
    console.log("This is option 1.");
case 2:
    console.log("This is option 2.");
case 0:
    console.log("Goodbye!");
default:
    console.log("Invalid Input - Please try again!");
}

So in this example, the cases don’t have break statements, so we will get a waterfall effect. Sometimes this is useful, but most of the time, you want to include a break at the end of each case. So if the user chooses option 0, so value is set equal to the user’s input, in this case 0, “Goodbye!” will be printed to the console and so will “Invalid Input – Please try again!” If they choose 1, the output will include: “This is option 1.“, “This is option 2.“, “Goodbye!“, and “Invalid Input – Please try again!” Let’s fix this, because we only want the the user’s chosen option to be addressed.

switch (value) {
case 1:
    console.log("This is option 1.");
    break;
case 2:
    console.log("This is option 2.");
    break;
case 0:
    console.log("Goodbye!");
    break;
default:
    console.log("Invalid Input - Please try again!");
    // break; (this break is always optional, because you are at the end of all the cases)
}

This switch…case block will accept the user’s input and only print the line that is associated with their choice. If the user chooses 1, the only thing output will be “This is option 1.“. Any input other than 0, 1, and 2 in this example and the previous example will result in an output telling the user that we don’t accept the value they entered. The break statement on the very last case of the switch…case block is optional, it breaks out of the switch…case block, but not any loops surrounding it, so it’s safe, but not necessary considering the switch…case is already ending.

NOTE: Cases can come in any order, it does not have to be in numerical or alphabetical order, and default does not have to come last, but usually, that’s how you would find it and want to write it.

Conclusion

It is important to know what to use to solve problems, and hopefully this article has helped. To sum it up, loops are used to repeat a block of code over and over as long as you decide. Conditionals are used when you want to handle a certain known case or a set of known cases. There are many options for loops and conditionals, so there are many different solutions for a problem. Look at the problem carefully, think about how the problem should be handled, then consider your options. Go forth and program your hearts away.

Happy Programming!

1
0

Related Posts