Control Flow in JavaScript

Rianna Cleary
6 min readJul 17, 2020

--

What is control flow? What type of operators/statements change the control flow?

Requirements

  • Understanding what variables are and what makes them global/local.
  • Can explain what a function is and how they operate in JavaScript.
  • Understand primitive data types are and how to apply them.

Intro to Control Flow

Control flow in JavaScript is how your computer runs code from top to bottom. It starts from the first line and ends at the last line, unless it hits any statement that changes the control flow of the program such as loops, conditionals, or functions. In this article, I’m going to be explaining these three statements more in depth, and how they affect control flow.

Loops

Loops are iteration statements that will keep running until there is either nothing left to loop over, or if the condition becomes false. There are many types of loops in JavaScript, but for now I’m going to be going over three of them. Let’s start with the most common used one, the for loop. The for is a conditional loop, which means that it runs based on if a certain condition is true. As long as it stays true, the code is going to keep executing.

const edm = ['House', 'Dubstep', 'Drum and Bass']for (let i = 0; i < edm.length; i++) {
console.log(edm[i])
}
// 'House'
// 'Dubstep'
// 'Drum and Bass'

Let’s break down what’s going on here. The syntax for a for loop contains a variable declaration of i which is the index of the array edm that we are currently iterating over. After that we have the condition that checks if i is less than the length of our array, followed by an increase in i. Basically, the for loop is saying to itself “okay so the index is 0, as long as that’s less than the length of the array, we are going to execute the code inside the code block and increase the value of i by one”. These three statements within the loop are optional though, as you can simply write for(;;){...} which would be an infinite loop.

While Loop

The while loop is similar to the for loop because it also runs while a condition is true. The difference between them is that you would use a for loop when you already know how many times you want the loop to be executed. A while loop is used when you are unsure about how many times the loop wants to run.

const edm = ['House', 'Dubstep', 'Drum and Bass']while (edm.length > 0) {
const genre = edm.pop()
console.log(genre)
}
// 'Drum and Bass'
// 'Dubstep'
// 'House'

This loop is saying “run the code in this code block only if the length of the edm array is less than 0. An infinite loop in this situation would be if the condition in the while loop is always true. Ex while (true) {...} .

Do-while Loop

Very similar to the while loop, this loop also runs on a while condition. However, it executes the condition after the fact.

const edm = ['House', 'Dubstep', 'Drum and Bass']
let i = 0
do {
console.log('I love dancing to' + edm[i])
i++;
} while (i < 3);
//'I love dancing to House'
//'I love dancing to Dubstep'
//'I love dancing to Drum and Bass'

Here, we are saying “hey, log out this string and increase the value of i only while i is less than 3". The usage of this loop would be for when you want to loop through an element at least one time, no matter what.

Conditionals

Conditional statements are implemented when you need to perform different actions based on different conditions. We recently used conditional type logic in the loops that we implemented, but conditionals are different from what we were just working with. In JavaScript, the conditional statements that we have are if, else if, else, and switch statements.

If, Else If, Else

The if statement is used when we want a block of code to be run as long as the condition it true. Like so:

if (4 * 4 = 16) {
console.log('This will run!')
}
// 'This will run!'

This code will always print 'This will run!' because 4 * 4 is always going equal 16. Let’s say we were writing something a little more complex, and wanted to log some code based on a different condition if the first one is false. That’s where else if comes in! This condition runs when the condition before it is false.

const hungryFor = ['pizza', 'sushi', 'french fries']for (let i = 0; i < hungryFor.length; i++) {
if (hungryFor[i] === 'pizza') {
console.log('I\'m hungry for ' + hungryFor[i])
} else if (hungryFor[i] === 'french fries') {
console.log('But ' + hungryFor[i] + ' are also tasty!')
}
}
// 'I'm hungry for pizza'
// 'But french fries are also tasty!'

In this example, we iterated through the hungryFor array and had two conditionals inside it stating that if the index of the hungryFor array equaled 'pizza', then log a specific string. In this case, only the strings 'pizza' and 'french fries' were printed. 'sushi' wasn’t because it never met the conditionals requirements. If we wanted to set a default value to this if statement, then we would have to use else . The else condition only runs if everything before it is false.

const hungryFor = 'sushi' if (hungryFor === 'pizza') {
console.log('I will not print')
} else if (hungryFor === 'french fries') {
console.log('I will not print')
} else {
console.log('But I will :)')
}
// 'But I will :)'

Since the variable hungryFor is equal to just one string, the first two conditions are both false, so the else code block only runs.

Switch

Switch statements serve the same purpose as if statements, however, they have their share of differences. switch() first takes in an expression and evaluates it once. If any of the preceding cases match the expression, then the return statement within that case will be executed.

function getDayOfTheWeek(num) {
switch (num) {
case 1:
return 'Monday';
case 2:
return 'Tuesday';
case 3:
return 'Wednesday';
case 4:
return 'Thursday';
case 5:
return 'Friday';
case 6:
return 'Saturday';
case 7:
return 'Sunday';
}
}
console.log(getDayOfTheWeek(4))// 'Thursday'

In this example we have a function that takes in a number as an argument. Inside that code block is a switch statement that have various cases which return strings corresponding to the days of the week. At the end of the snippet, we console.log() the function call and passed in 4 which printed out 'Thursday' because that was under the fourth case. It’s best to use switch statements when you’re testing one value, and if, else if , and else when you’re testing multiple conditions.

Functions

Functions are blocks of code that can be called by other code, by itself, or by a variable that refers to that function object. Usually when you call a function, it takes in one or multiple arguments and it can optionally return a value. We can take our previous examples from above, apply them to functions, and see how that affects the control flow of the application.

const edm = ['House', 'Dubstep', 'Drum and Bass']const hungryFor = ['pizza', 'sushi', 'french fries']
function printGenres(arr) {
for (let i = 0; i < edm.length; i++) {
console.log(edm[i])
}
}
function printFoods(arr) {
for (let i = 0; i < hungryFor.length; i++) {
console.log(hungryFor[i])
}
}
printFoods(hungryFor)
printGenres(edm)
// 'pizza'
// 'sushi'
// 'french fries'
// 'House'
// 'Dubstep'
// 'Drum and Bass'

In this example, we have two functions that both do the same thing. This code isn’t very DRY obviously, however I did this purposely to show you how the control flow is affected. Even though the function printGenres() is declared first in the code, the second function is the first one being called. So as your code is executing, it sees that there are two functions, but will only run them when they’re eventually called. In this case, the second function printFoods() was the first one called, so it will be executed first.

All of these statements that were covered affect control flow because they essentially pause everything else that's happening until those conditions are met and everything to the possible extent could be executed. If you’d like to expand on these simple JS concepts, or learn more about control flow please checkout these documentations below!

--

--