javascript logo

JavaScript Basics - Control Flow

Control flow is the order in which code is executed. Without intervention code runs from the first line to the last line. Normally when coding we have to manipulate functionality based on the data that is received. We can use conditional statements or loops to make those updates.

I'm going to go over a few ways to add control flow statements to your code.

Truthy/Falsy

A truthy value is a value that is considered true in the context of a boolean. Examples of truthy values are as follows:

true;
1;
{}
[];

A falsy value is a value that is considered false in the context of a boolean. Examples of falsy values are as follows:

false;
0;
-0;
null;
undefined;
NaN;

If/else

The if/else statements execute code if a truthy value is met, else if the value is falsy another piece of code will execute.

if (condition) {
  return aFunction();
} else {
  return anotherFunction();
}

If there are multiple conditions that can be met you use the else if syntax.

function greaterThan(num) {
  if (num > 10 && num <= 15){
    return `${num} is greater than 10`;
  } else if (num > 15) {
    return `${num} is greater than 15`;
  } else {
    return `${num} is less than 15`;
  }
}

Try/catch

The try/catch statement specifies a block of code to try and what to do if an error occurs. This syntax is helpful for debugging and showing a user-friendly error message.

try {
  foo();
} catch (error) {
  console.log(err);
}

//ReferenceError: foo is not defined at <anonymous>:2:3

Switch

The switch statement is used to perform different actions based on different conditions.

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

The break statement exits out of the switch statement.  Break can also be used in loops.  Test the code below to see how removing the break keyword effects the functionality.

const exp = prompt("What is the weather like?");

switch(exp) {
  case 'rain':
    console.log('Wear a raincoat!');
    break;
  case 'snow':
    console.log('Wear a warm coat!');
    break;
  case 'sunny':
    console.log('Enjoy the weather!');
  break;
  default:
    console.log('I do not understand.');
}

Loops

There are many types of loops: for, while, for/in, for/of, do/while. Each of these loops allowing you to evaluate code multiple times without having to repeat code. I'm going to show the basic for loop.

const data = [1,2,3,4,5,6,7,8,9];

function addUp(arr){
  let total = 0;
  
  for(let i =0; i < arr.length; i++){
    console.log(`Array index ${i}, Array value ${arr[i]}`);
    total += arr[i];
  }
  return total;
}
addUp(data);

//Array index 0, Array value 1
//Array index 1, Array value 2
//Array index 2, Array value 3
//Array index 3, Array value 4
//Array index 4, Array value 5
//Array index 5, Array value 6
//Array index 6, Array value 7
//Array index 7, Array value 8
//Array index 8, Array value 9

//45

Inside the parentheses we have declared a variable i. That variable helps us track the data we are looping over. In the example above we are adding up the numbers in the array and returning the total. We are also console logging i to show that it is incrementing and which element in the array corresponds to that index.

Conclusion

I've gone over a few ways to adjust the control flow of your program. If you want more examples of control statements click here.