Mark As Completed Discussion

Understanding Program Execution Flow: Mastering Control Statements

Key Objectives

In today's lesson, we delve into the crucial topic of program execution flow. We'll concentrate on answering two fundamental questions:

  1. How can you manipulate the execution sequence of a program?
  2. How do if/else and try/catch statements help in directing the program's control flow?

For those interested in the Python-specific aspects of this lesson, you can find it here.

Building on Past Knowledge

In our prior lessons, we've covered the basics like variables, data types, and various operations involving these variables. Today, we're shifting our focus towards the concept known as control flow. This concept governs how a program behaves during its runtime.

Zooming in on If/Else and Try/Catch Statements

Control flow is not a free-for-all; it's dictated by specific constructs built into programming languages. Today, we're going to explore two of the most commonly used constructs for controlling program behavior: if/else and try/catch statements. These elements act as the traffic signals of a program, guiding it along the path defined by the programmer.

Control Flow of a Program

Control flow of a program refers to the order of execution of various code elements in the program. This means that we can ask the program to perform certain actions when some specific condition is triggered. This allows the program to make decisions according to different situations that it may encounter during its execution.

The first control flow element that we will discuss is if/else statements. They allow the programmer to specify certain decisions within a program and execute different statements in a program under various specified conditions. The second control flow element discussed will be try/catch statements. They are responsible for handling errors and exceptions that may arise in a program. They change the flow of execution whenever such a situation occurs so that the flow of execution of the program is not disturbed.

If/Else Statements

If/else statements can be best visualized and understood in the form of flow chart diagrams. For example, suppose we want to determine if a number is odd or even, and display a helpful message accordingly. In a sequential program, we cannot do this as it executes the program in a single flow, executing all statements. However, here we need different path flows for different outcomes, as shown below.

If/Else Statements

Thus, we need to be able to control the flow of the program by specifying that if the number is even print "x is even" else the number is odd print "x is odd". Depending on the number, the decision and output will be shown automatically through the execution.

Below is another example, where multiple execution paths are defined. This allows for specification of more than 2 different conditions.

If/Else Statements

Let's see how these concepts take effect in JavaScript.

If/else Statements in JavaScript

In JavaScript, if/else statements are implemented using if and else keywords. The if keyword is followed by an expression, which must be enclosed in round brackets (). The body of the if statement is denoted using curly braces{}. This is also known as the scope of the if statement. The body of the if statement contains one or several statements which need to be evaluated under the specified condition.

In general, we have the syntax as,

SNIPPET
1if (expression){
2    statement
3}

For the odd-even number example above, if-else statements in JavaScript will be written as,

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

If we have multiple if statements, we can use the if-else if-else structure for conditional statements. For the positive-negative-zero number example above, the JavaScript code will be,

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

It is important to note that if conditions can exist independently (without else if or else) as well. However, an else if or else condition cannot work without an if condition beforehand.

Time for some practice questions!

Try this exercise. Is this statement true or false?

There is a limit to the number of statements that we can have under an if block.

Press true if you believe the statement is correct, or false otherwise.

Are you sure you're getting this? Click the correct answer from the options.

What is wrong in the below code?

JAVASCRIPT
1var length = 5
2var breadth = 5
3
4if length == breadth{
5    console.log("This is a square")
6}
7else{
8    console.log("This is not a square")
9}

Click the option that best answers the question.

  • Missing `elif` condition
  • Round brackets missing for conditional expression
  • Curly braces used instead of colon and indentation

Try/Catch Statements

When an error occurs during the execution of a program, the compiler of the programming language will stop execution and generate an error message. However, if we want to control what happens when an error occurs, we can use try/catch statements. They are triggered when an error occurs during the execution of the program. The try block allows to check for any errors and its body executes statements (if any) in case errors were not occured. The catch block allows the programmer to handle the error by telling the program what to do if the try block catches any errors.

Try/Catch Statements in JavaScript

try and catch keywords in JavaScript are used with the statements to implement this functionality. A try block is specified using the try keyword, and the body of the try statement is denoted by curly braces (similar to if/else statements). Its body can contain one or several statements which need to be evaluated if an exception does not occur. The catch block is called if the try block catches any errors. Instead of halting the program, the statements in its body are executed, and the program flow will not break.

Let's consider an example. Suppose we try to print a variable x without declaring it. This will cause the program to raise an exception. But we do not want the program to stop, so we use a try-catch block to work around this problem.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Try this exercise. Is this statement true or false?

Can we have a catch block without declaring a try block beforehand?

Press true if you believe the statement is correct, or false otherwise.

Build your intuition. Fill in the missing part by typing it in.

What will be the output of following code block?

JAVASCRIPT
1try{
2    return 1
3}
4except{
5    return 2
6}

Write the missing line below.

Summary

In this lesson, we learned about controlling the flow of execution in programs, and how to make the program perform certain specific tasks under specific conditions. These control flow elements allow us to cater to any uncertain conditions that may occur on input (if/else statements) or during the execution of the program due to any flaws (try/catch statements). This is extremely powerful, as it is even used in complex applications such as those in artificial intelligence.

One Pager Cheat Sheet

  • We will learn about controlling the behavior of a program using if/else and try/catch statements to establish its control flow.
  • The control flow of a program is the order of execution of code elements, taking different decisions based on if/else and try/catch statements to handle errors and exceptions.
  • If/Else Statements provide a way to control program execution, by defining different flows depending on the conditions, such as in the form of a flow chart diagram.
  • Using the if and else keywords, JavaScript allows for conditions to be evaluated with the syntax if (expression) { statement; }, enabling developers to create a scope within the curly braces for the statement to be evaluated against the given expression.
  • We can use the if-else if-else structure to determine a number's value in JavaScript using multiple if statements.
  • An if condition is essential for else if and else statements to work, but it is possible to have an if condition that stands alone.
  • There is no limit to the number of statements that can be included under an if block.
  • The code needs a boolean expression enclosed in round brackets ( ) in the if block in order to be evaluated by the compiler.
  • Using try/catch statements allow the programmer to handle errors that occur during the execution of the program.
  • Using the try and catch keywords, a JavaScript program can handle errors by running the statements in the catch block, preventing the program from halting.
  • No, we cannot have a catch block without a try block because it is a syntax structure in JavaScript that requires both.
  • The try block will attempt to execute the return statement, producing the output of 1 and the catch block will never be used as there was no error to handle.
  • We can control the flow of execution in a program and adapt to uncertain conditions using if/else and try/catch statements, which is necessary for many complex applications such as in artificial intelligence.