Introduction to JavaScript​ 3


Introduction to Control Flow

In this lesson, we’ll explore how we can use the building blocks of JavaScript to write programs that make decisions.

Control flow statements enable JavaScript programs to make decisions by executing code based on a condition. If a given condition is true, we execute one block of code. If the statement is false, we execute another block of code. For instance, if we were making a game in which the user had to choose which door to enter, we’d need a way for the program to know what to do once the user was in the next room.

In this lesson, we’ll learn how to make decisions with JavaScript and how it can control the program’s flow.



  1. If you wish, set userName equal to your name. Also, you can change the value of knowsJavaScript to true, if you’d like!
    Try to predict what will be logged to the console. Run the code when you’re ready!


let userName = ‘julio’;

let knowsJavaScript = false;

if (knowsJavaScript && userName) {

  console.log(‘Great, ‘ + userName + ‘! Get ready to practice your JavaScript!’);

} else if (knowsJavaScript) {

  console.log(‘Great! Get ready to practice your JavaScript!’);

} else if (userName) {

  console.log(‘Great, ‘ + userName + ‘! Get ready to learn something new!’);

} else {

  console.log(‘Great! Get ready to learn something new!’);




if/else Statements

The core task of programming is writing lists of instructions for computers, or translating our ideas from human-speak to computer-speak.

Let’s learn how we can ask JavaScript to think like us and make decisions the way we do.

We’ll start with human-speak. Many decisions we make everyday boil down to this sentence in some form:

“If something is true, let’s do option 1, or else, if it is false, let’s do option 2.”

This sentence looks fairly similar when we write it with JavaScript. See for yourself:


let needsCoffee = true;

if (needsCoffee === true) {

    console.log(‘Finding coffee’);

} else {

    console.log(‘Keep on keeping on!’);


  • Lines of code between curly braces are called blocks. if/else statements have two code blocks. If the variable needsCoffee is true, the program will run the first block of code. Otherwise, it will run the other block of code. 
  • needsCoffee is the condition we are checking inside the if’s parentheses. Since it is equal to true, our program will run the code between the first opening curly brace { (line 2) and the first closing curly brace } (line 4). It will ignore the else { … } part. In this case, we’d see Finding coffee log to the console.
  • If needsCoffee were false, only the console.log() statement in the else block would be executed.

if/else statements are how programs can process yes/no questions programmatically.




  1. Create a variable named isSoccerFan and set it equal to a boolean, based on your preference.
    Booleans are either true or false.
  2. Write an if/else statement that uses isSoccerFan as its condition. If it is true, then log, Goal!. If it is false, then log, No goal!.


True and False Values

In the previous exercise, we wrote if/else statements. If a given condition were true, one block of code would run. If that condition were false, a different block of code would run. However, there are data types that are not booleans. Let’s explore the concepts of true and false in variables that contain other data types, including strings and numbers.

In JavaScript, all variables and conditions have a truthy or falsy value.


let variableOne = ‘I Exist!’;

if (variableOne) {

// This code will run because variableOne contains a truthy value.

} else {

// This code will not run because the first block ran.



In the first line of the program above, a variable is created and set. The value of this variable is a string rather than a boolean. How does this program determine which code block to run?

The second line of this program checks a condition if (variableOne). In the previous exercise, we checked if a variable was equal to true or false. By only writing the name of the variable as the condition, we are checking the truthiness of the variableOne. In this case, variableOne contains a truthy value.

If we changed if (variableOne) to say if (variableTwo), that condition would evaluate to falsy because we have not created a variable called variableTwo in this program. In other words, variableOne is truthy and variableTwo is falsy.

All variables that have been created and set are truthy (and will evaluate to true if they are the condition of a control flow statement) unless they contain one of the seven values listed below:

  • false
  • 0 and -0
  • “” and ” (empty strings)
  • null
  • undefined
  • NaN (Not a Number)
  • document.all (something you will rarely encounter)

There is an important distinction between a variable’s value and its truthiness: variableOne’s value is ‘I exist’ because that is the data saved to the variable. variableOne is truthy because it exists and does not contain any of the seven falsy values listed above.




  1. Change the value of wordCount so that Great! You’ve started your work! is logged to the console.
  2. Change the value of favoritePhrase so that This string doesn’t seem to be empty is logged to the console.


True and False Values II

In programming, we often evaluate whether or not an expression is true or truthy. Conveniently, JavaScript provides a shorthand notation for this.


let isRaining = true;

if (isRaining) {

   console.log(‘Carry an umbrella!’);

} else {

  console.log(‘Enjoy the sun!’);



In the example above, the condition is simply if (isRaining). In JavaScript, this is evaluating whether isRaining is truthy. If you read the code out loud to yourself, it sounds like a simple sentence: “If it’s raining, carry an umbrella. Else, enjoy the sun!”

JavaScript provides an operator for swapping the truthiness and falsiness of values – the exclamation point (!). We can use this in conditional statements as shorthand to check if the value of a variable evaluates to false rather than true.


let isPhoneCharged = true

if (!isPhoneCharged) {

  console.log(‘Plug in your phone!’);

} else {

  console.log(‘No need to charge!’);



In the example above, the program checks if isPhoneCharged evaluates to false. Because isPhoneCharged is true, the second block of code will execute.




  1. Use the ! operator to cause This string is definitely empty to log to the console.


Comparison Operators

In addition to checking whether a variable evaluates to true or false, sometimes we need to compare variables to other values. We can achieve this with comparison operators.

There are two comparisons you might be familiar with:

  • Less than: <
  • Greater than: >

You may also recognize these:

  • Less than or equal to: <=
  • Greater than or equal to: >=

These comparisons evaluate to true or false.




  1. Using let, write a variable named hungerLevel and set it equal to 5.
  2. Write an if/else statement that checks if hungerLevel is greater than 7. If so, log Time to eat!. Otherwise, log We can eat later!.


Comparison Operators II

There are two more useful comparisons we can make. Often, we might want to check if two things are equal to each other or if they are not.

  • To check if two things equal each other, we write === (three = signs in a row).
  • To check if two things do not equal each other, we write !== (an exclamation with two = signs in a row).

It can be confusing when to use one = sign and when to use three === signs. Use a single = to assign a value to a variable. Use ===to compare the values of two different variables.




  1. Create a variable named moonPhase and set it equal to full.
    When setting a variable, use a single equals sign: =
  2. Write an if/else statement that checks if the moon is full. If the moonPhase is full, log Howl! to the console, and if it is anything else, log I swear I am not a werewolf.
    Notice the code inside the first block of curly braces { } ran. That’s because moonPhase equals full, and therefore the condition evaluates to true.


else if Statements

We’ve explored if/else statements that answer questions that are either yes or no. What can we do if we have a question that has multiple yes conditions, or multiple no conditions?

We can add more conditions to our if/else statement with else if. Check out how this fits into our current knowledge of if/else statements:


let stopLight = ‘green’;


if (stopLight === ‘red’) {


} else if (stopLight === ‘yellow’) {

  console.log(‘Slow down’);

} else if (stopLight === ‘green’) {


} else {

  console.log(‘Caution, unknown!’);



  1. We created a variable named stopLight that is assigned to the string green.
  2. Then, there’s an if/else statement with multiple conditions, using else if. else if allows us to check multiple values of the stopLight variable and output different things based on its color.
  3. 3. The block ends with the singular else we have seen before. The else is a catch-all for any other situation. For instance, if the stopLight was blinking blue, the last else would catch it and return a default message.



  1. We all know that turning into a werewolf is not an instantaneous event. It happens in stages. So let’s expand our program to accommodate that.
    If the moon is mostly full, log Arms and legs are getting hairier. If the moon is mostly new, log Back on two feet.
    If someone enters in an invalid moon phase, make sure to log Invalid moon phase in the else code block.
  1. Set moonPhase to mostly full and run your code.
    We expect Arms and legs are getting hairier to log to the console.
  2. Set moonPhase to mostly new and run your code.
    We expect Back on two feet to log to the console.
  3. Now set moonPhase to solar eclipse and run your code.
    Since there is not an else if condition for solar eclipse, we expect the default else code block to run. You should see Invalid moon phase print to the console.


Logical Operators

We can translate certain thoughts into JavaScript code such as, “Are these things equal?” with ===, or, “Is one thing greater than another thing?” with >.

In English, sometimes we say “both of these things” or “either one of these things.” Let’s translate those phrases into JavaScript with special operators called logical operators.

  • To say “both must be true,” we use &&.
  • To say “either can be true,” we use ||.

For example:

if (stopLight === ‘green’ && pedestrians === false) {


} else {



  • In the example above, we make sure that the stopLight is ‘green’ and (&&) there are no pedestrians before we log Go!.
  • If either of those conditions is false, we log Stop.

Just like the operators we learned previously, these logical operators will return either true or false.

These logical operators are helpful when writing if/else statements since they let us make sure multiple variables are true or false. We can combine these operators with all of the ones we have learned throughout this lesson.


  1. Let’s say the werewolf can only become its wolf form when there is a full moon and a it’s a foggy night.
    We already have a moonPhase variable, so let’s start with making a isFoggyNight variable set equal to true.
  2. Now, set moonPhase to ‘full’ again. Now that we have both conditions, let’s write that in our if/else statement.
    In the first condition of the if/else statement, check that moonPhase === ‘full’ and isFoggyNight is true, using &&.

if (moonPhase === ‘full’ && isFoggyNight) {



  1. Now, change the isFoggyNight variable to equal false and run it again.
    Because isFoggyNight is now false, the first if condition will not run since it requires the moonPhase to be full and isFoggyNight to be true.
    When isFoggyNight is false, we expect the else condition to print Invalid moon phase to the console.
  2. The default else will print to the console. That’s because && requires both moonPhase and isFoggyNight to be true to execute its code block.
    Replace the && that you wrote in the previous steps with ||.
    Make the if/else statement print Howl! if moonPhase is ‘full’ or if isFoggyNight is true.
    Leave the moonPhase variable’s value as ‘full’ and the isFoggyNight variable’s value as false. Which block is executed?


switch Statements

Before we move on, let’s circle back to else if statements.

Using else if is a great tool for when we have a few different conditions we’d like to consider.

else if is limited, however. If we want to write a program with 25 different conditions, like a JavaScript cash register, we’d have to write a lot of code, and it can be difficult to read and understand.

To deal with times when you need many else if conditions, we can turn to a switch statement to write more concise and readable code.

To a computer, a switch statement and an if/else statement are the same, but a switch statement can be easier for other humans to read. Part of being a good developer is writing code that both computers and other humans can read.

switch statements look like this:


let groceryItem = ‘papaya’;


switch (groceryItem) {

  case ‘tomato’:

    console.log(‘Tomatoes are $0.49’);


  case ‘lime’:

    console.log(‘Limes are $1.49’);


  case ‘papaya’:

    console.log(‘Papayas are $1.29’);



    console.log(‘Invalid item’);



  • The switch keyword initiates the statement and is followed by ( … ), which contains the condition that each case will compare to. In the example, the condition is groceryItem.
  • Inside the block, { … }, there are cases. case is like the else if part of an if/else if/else statement. The word following the first case is ‘tomato’. If groceryItem equalled ‘tomato’, that case’s console.log() would run.
  • groceryItem equals ‘papaya’, so the first and second case statements are skipped. The third case runs since the case is ‘papaya’, which matches groceryItem’s value. This particular program will log Papayas are $1.29.
  • Then the program stops with the break keyword. This keyword will prevent the switch statement from executing any more of its code. Without adding break at the end of each case, the program will execute the code for all matching cases and the default code as well. This behavior is different from if/else conditional statements which execute only one block of code.
  • At the end of each switch statement, there is a default condition. If none of the cases are true, then this code will run.



  1. Let’s illustrate this by converting our werewolf program to a switch statement. For now, let’s also delete the isFoggyNight variable so it doesn’t fog up this concept.
    moonPhase will become the condition of the switch statement. Then, each moon phase will become each case that the switch statement checks for.
    Start by writing a switch statement with moonPhase as its condition.


switch (moonPhase) {


  1. Then, write each else if condition as a case. If moonPhase is ‘full’, then use console.log() to print Howl!. If moonPhase is ‘mostly full’, then use console.log() to print Arms and legs are getting hairier. If moonPhase is ‘mostly new’, then use console.log() to print Back on two feet. Remember to add a break after each console.log(), like in the example in the instructions.


switch (moonPhase) {

  case ‘full’:

    // run full code


  case ‘mostly full’:

    // run mostly full code





  1. Now, add a default at the end of the switch that uses console.log() to print Invalid moon phase, in the case that moonPhase does not equal one of our cases.


Ternary Operator

In the previous exercise, we learned shorthand for writing multiple if/else if/else statements to make them easier to read. JavaScript also provides a way to shorten simple if/else statements called the ternary operator.


let isNightTime = true;


if (isNightTime) {

  console.log(‘Turn on the lights!’);

} else {

  console.log(‘Turn off the lights!’);


In the example above, we see a very familiar pattern. See the example below for an equivalent way to express this.


isNightTime ? console.log(‘Turn on the lights!’) : console.log(‘Turn off the lights!’);


The code in the example above will operate exactly as the code from the previous example. Let’s break this example into its parts:

  • isNightTime ? — the conditional statement followed by a question mark. This checks if isNightTime is truthy.
  • console.log (‘Turn on the lights!’) — this code will be executed if the condition is truthy.
  • : — a colon separates the two different blocks of code that can be executed.
  • console.log(‘Turn off the lights!’); — this code will be executed if the condition is falsy

In this example, we checked if the value of a variable was true or false. The ternary operator can be used for any condition that can be evaluated to true or false, such as those with comparison operators.


age >= 16 ? console.log(‘You are old enough to drive in the United States!’) : console.log(‘You are not old enough to drive in the United States!’);


In the example above, the conditional statement is checking whether the value of the variable age is greater than or equal to 16. If so, a message that states the user is old enough to drive will be logged to the console. Otherwise, a message that states the user is not old enough to drive will be logged.



  1. In main.js, refactor the first if/else block to user the ternary operator.
  2. In main.js, refactor the second if/else block to user the ternary operator.


  1. In main.js, refactor the third if/else block to use the ternary operator.





Review: Control Flow

Way to go! We just learned a lot of control flow concepts:

    • if/else statements make binary decisions and execute different code based on conditions.
    • All conditions are evaluated to be truthy or falsy.
    • We can add more conditional statements to if/else statements with else if.
    • switch statements make complicated if/else statements easier to read and achieve the same result.
    • The ternary operator (?) and a colon (:) allow us to refactor simple if/else statements.
    • Comparison operators, including <, >, <=, and >= can compare two variables or values.
    • After two values are compared, the conditional statement evaluates to true or false.
    • The logical operator && checks if both sides of a condition are truthy.
    • The logical operator || checks if either side is truthy.
    • The logical operator !== checks if the two sides are not equal.
    • An exclamation mark (!) switches the truthiness / falsiness of the value of a variable.
    • One equals symbol (=) is used to assign a value to a variable.
    • Three equals symbols (===) are used to check if two variables are equal to each other.

Sé el primero en comentar

Deja una respuesta