Control Flow

Sometimes I want to modify the flow of how my program works, or in other words, some time I only want to run code if some condition is true. This is where if statements are very useful. Imagine if we tried this.

const skyIsBlue = true;
 
if (skyIsBlue) {
  console.log("The sky is blue!");
} else {
  console.log("The sky is … not blue?");
}

In the above example, the condition inside of the parens is evaluated and if it's true, the first block is run and the second is skipped. If it is false, the second block is run and the first block is skipped.

You should note that you don't have to include the else and the second curly brace block — the following is also perfectly legal code:

if (condition) {
  /* code to run if condition is true */
}
 
/* run some other code */

Ternary Operator

Sometimes, we need to assign a variable depending on a condition. The so-called “conditional” or “question mark” operator lets us do that in a shorter and simpler way.

The operator is represented by a question mark ?. Sometimes it’s called “ternary”, because the operator has three operands. It is actually the one and only operator in JavaScript which has that many.

let accessAllowed = (age > 18) ? true : false;

Logical operators

If you want to test multiple conditions without writing nested if...else statements, logical operators can help you. When used in conditions, the first two do the following:

  • && — AND; allows you to chain together two or more expressions so that all of them have to individually evaluate to true for the whole expression to return true.
  • || — OR; allows you to chain together two or more expressions so that one or more of them have to individually evaluate to true for the whole expression to return true.
  • ! - NEGATE; can be used to negate an expression
if ((x === 5 || y > 3 || z <= 10) && (loggedIn || userName === "Steve")) {
  // run the code
}

Switch Statements

switch (expression) {
  case choice1:
    // run this code
    break;
 
  case choice2:
    // run this code instead
    break;
 
  // include as many cases as you like
 
  default:
    // actually, just run this code
    break;
}

Loops

While Loop

while (condition) {
  // code
  // so-called "loop body"
}

Do While Loop

do {
  // loop body
} while (condition);

For Loop

for (begin; condition; step) {
  // ... loop body ...
}
for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2
  alert(i);
}

Functions

To create a function we can use a function declaration.

It looks like this:

function showMessage() {
  alert( 'Hello everyone!' );
}

The function keyword goes first, then goes the name of the function, then a list of parameters between the parentheses (comma-separated, empty in the example above, we’ll see examples later) and finally the code of the function, also named “the function body”, between curly braces.

function name(parameter1, parameter2, ... parameterN) {
 // body
}