JavaScript Flow Control Fundamentals

Hey - Nick here! This page is a free excerpt from my $99 course JavaScript Fundamentals.

If you want the full course, click here to sign up and create an account.

I have a 30-day satisfaction guarantee, so there's no risk (and a ton of upside!) in signing up for this course and leveling up your JavaScript developer skills today!

In this lesson, you will learn the fundamentals of flow control in the JavaScript programming language.

Table of Contents

You can skip to a specific section of this tutorial using the table of contents below:

BEDMAS - The Mathematical Underpinnings of Flow Control

In computer programming, flow control refers to the logic that decides whether certain blocks of code will be executed or not.

The most common source of flow conrtol in JavaScript is BEDMAS - which is an acronym that describes the order of operations in algebra. For those unfamiliar with BEDMAS, it stands for:

  • Brackets
  • Exponents
  • Division
  • Multiplication
  • Addition
  • Subtraction

All that BEDMAS means is that brackets are computed first, then exponents, then division, and so on…

Flow control certainly becomes much more complex than simply understanding BEDMAS. However, it's impossible to learn more advanced topics without understanding BEDMAS, so I wanted to quickly review this first.

How to Write if Statements in JavaScript

if statements form the backbone of flow control in most languages. In this section of this tutorial, you will learn how to write if statements in JavaScript.

An if statement in JavaScript has two components: a condition and an action.

The generalized syntax of an if statement in JavaScript is shown below:

if (condition) {

	action;

}

Let's break down this if statement to understand how it works.

The condition in JavaScript if Statements

First, let's discuss the condition. This is generally some sort of comparison operator that evaluates to a boolean value. Remember, boolean values can only be either true or false.

Here are the main types of comparison operators in JavaScript, with comments to indicate their purpose:

>

//greater than

<

//less than

>=

//greater than or equal to

<=

//less than or equal to

Let's see a few examples of comparison operators in action in JavaScript:

10 < 3;

//Returns false

5 <= 5;

//Returns true

6 > 4

//Returns true

4 >= 5

//Returns false

The condition in JavaScript if statements can also be used to test equality by using the === operator.

Here are a few examples:

1 === 1;

//Returns true

true === false

//Returns false

2 === 3

//Returns false

'A string' === 'Another string'

//Returns false

Lastly, the condition in JavaScript if statements can also test for inequality using the !== operator.

Here are a few examples:

1 !== 2;

//Returns true

1 !== 1

//Returns false

The action in JavaScript if Statements

Let's move on to the action component of a JavaScript if statement. This statement can be anything - it can be a function declaration, some arithmetic, or even a console.log command. Said differently, you can literally build if statements to meet any possible functionality that you can think of.

JavaScript else if and else Clauses

In JavaScript, we can pair the else if and else keywords with a normal if statement to create more complex flow control.

The else if clause allows us to specify a second condition with its own action statement that will trigger if the second criteria is met. An if statement can have multiple else if clauses.

Note that unlike else if clauses in other programming languages, the JavaScript else if clause's syntax is actually else if, and not elseif or elif.

The else clause allows us to have a catch-all action that will be executed if none of the previous criteria have been satisfied. Since the else statement does not actually test a condition, it does not require round brackets.

As an example, here is how you could write a chained if statement with an else if clause and an else clause to log a different statement to the console depending on whether an outside number is less than 10, between 10 and 20, or greater than 20:

let int = 15;

if (int < 10){

    console.log('The integer is less than 10');

                }

else if (int < 20) {

console.log('The integer is between 10 and 20, including 10 and excluding 20');

    }

else {

console.log('The integer is greater than or equal to 20');

    }

In this case, with int = 15, then this short JavaScript code block logs the following statement to the console:

The integer is between 10 and 20, including 10 and excluding 20

The way that else if and else clauses work is that the condition will not be tested if a prior condition turns out to be true. Said differently, if the first condition evaluates to true, then its corresponding action is executed and the entire if statement (including the else if and else clause) is terminated.

Note that since none of these statements can be simultaneously true, you could also just list three separate if statements, like this:

let int = 15;

if (int < 10){

    console.log('The integer is less than 10');

                }

if (int < 20) {

console.log('The integer is between 10 and 20, including 10 and excluding 20');

    }

if (int >= 20) {

console.log('The integer is greater than or equal to 20');

    }

Some developers consider this version of the code to be slightly more readable. There is no right or wrong answer, however - the decision of whether to use multiple if statements versus using else if and else clauses is purely a matter of taste.

Using if Statements Inside of JavaScript Functions

One of the most important use cases for if statements in JavaScript is including them in functions. This section will discuss this technique.

Learning how to include if statements inside for JavaScript functions is best done through example. Let's build a function called petClassifier that logs a different string to the console depending on which pet is passed into it.

Specifically, let's include the following logic inside of petClassifier:

if (pet === "dog"){

	console.log("Dogs are man's best friend!");

} else if (pet === "cat"){

	console.log("Cats are cool, but litter boxes are gross!");

} else {

	console.log("You have a pet that I've never heard of before!");

}

Including this logic inside of the petClassifier function is as simple as you'd expect:

function petClassifier(pet){


    if (pet === "dog"){


    	console.log("Dogs are man's best friend!");


    } else if (pet === "cat"){


    	console.log("Cats are cool, but litter boxes are gross!");


    } else {


    	console.log("You have a pet that I've never heard of before!");


    }

}

Simple enough, right?

What if we actually wanted to return the strings as an output of the function, instead of logging them to the console?

Well, we would simply replace the console.log methods with return statements, like this:

function petClassifier(pet){


    if (pet === "dog"){


    	return "Dogs are man's best friend!";


    } else if (pet === "cat"){


    	return "Cats are cool, but litter boxes are gross!";


    } else {


    	return "You have a pet that I've never heard of before!";


    }

}

Now that we have introduced return statements into our function, there are a number of changes we can make so that the function is more readable.

First, since return statements cause the function to terminate, we actually do not need to include the else clause.

The following code behaves exactly the same way:

function petClassifier(pet){


    if (pet === "dog"){


    	return "Dogs are man's best friend!";


    } else if (pet === "cat"){


    	return "Cats are cool, but litter boxes are gross!";


    } 


    return "You have a pet that I've never heard of before!";

}

Next, since a pet variable cannot simultaneously be equal to cat and dog, some developers may argue that the else if clause should be replaced by a second if statement like this:

function petClassifier(pet){


    if (pet === "dog"){


    	return "Dogs are man's best friend!";


    } 


    if (pet === "cat"){


    	return "Cats are cool, but litter boxes are gross!";


    } 


    return "You have a pet that I've never heard of before!";

}

Voila! A simpler version of the petClassifier function.

Testing Multiple Conditions in JavaScript if Statements

It is possible to test multiple conditions in JavaScript if statements. To be more specific, there are actually two ways that developers can do this.

First, they can test whether both conditions are true. This is done using the and operator, which is denoted by the && character.

Here is an example of how you could test whether someone's age is between 18 and 22 using the && operator:

if (age < 22 && age > 18){

	console.log('This person is of typical college age!');

}

Second, developers can test whether one condition is true. This is done using the or operator, which is denoted by the || operator.

Here is an example of how you could test whether smoeone's age is either below 18 or above 22 using the || operator:

if (age > 22 || age < 18){

	console.log('This person is not of typical college age!');

}

The || and && operators can be used with every comparison operator, including the === and !== operators. They can also be used with direct true and false boolean values.

Truthy and Falsy Values in JavaScript

JavaScript does not actually require a strict true or false value inside of its if statements. Instead, if statements can also contain what are called truthy or falsy values.

truthy and falsy values are simply non-boolean values that can still affect the flow control of an if statement.

As an example, what do you think the output of the following code will be?

const name = 'Nick';

if (name) {

	console.log('the first statement was executed');

} else {

	console.log('the second statement was executed');

}

In this case, here is what gets logged to the console:

the first statement was executed

Interestingly, if the name variable were empty, the opposite would be true. More specifically, this code:

const name = '';

if (name) {

	console.log('the first statement was executed');

} else {

	console.log('the second statement was executed');

}

Logs the following statement to the console:

the second statement was executed

Many of the non-boolean values have truthy and falsy values that you'd expect. As an example, 1 is a truthy value and 0 is a falsy value.

What about every other number? Every non-0 number in JavaScript is a truthy variable.

Here are a few other examples that you should be aware of:

  • undefined: falsy
  • null: falsy
  • NaN: falsy
  • An array: truthy

Final Thoughts

In this tutorial, you learned the fundamentals of flow control in JavaScript.

Here is a specific summary of what was discussed in this lesson:

  • Table of Contents
  • BEDMAS - The Mathematical Underpinnings of Flow Control
  • How to Write if Statements in JavaScript

    • The condition in JavaScript if Statements
    • The action in JavaScript if Statements
  • JavaScript else if and else Clauses
  • Using if Statements Inside of JavaScript Functions
  • Testing Multiple Conditions in JavaScript if Statements
  • Truthy and Falsy Values in JavaScript
  • Final Thoughts