Control structures

In our program, we can control the flow, i.e. what happens, based on conditions. This is done using if statements and loops.

What if?

Let's imagine that we want to print a value to the console, but only if it is not undefined. We can use the "is not equal" operator (!=) as part of an expression in an if statement:

if(variableName != 'undefined'){
    console.log(variableName)
}

The expression variableName != 'undefined' will return either true or false, and if it is true, the code inside the block will be executed. Should the expression evaluate to false, the block will be skipped.

Inside the parentheses you can use all the logical operators previously defined, and create complex expressions. Sometimes we need to see if a variable have a certain value:

if(weather == "sun"){
    console.log("You can safely walk outside")
}

Sometimes though, it's not enough with just one case, e.g. weather == "sun", so we need to ask ourselves, what else if? This statement also takes an expression that will be evaluated to true or false.

if(weather == "sun"){
    console.log("You can safely walk outside")
} else if (weather == "rain"){
    console.log("Bring an umbrella")
}

The if statement is the first to be evaluated, and if it is false, the program will evaluate the next one, and the next one, and the next one, until it finds one that evaluates to true. After that, it will not evaluate any more expressions in that block. If you need one "catch all" case, that should be executed should all else fail, well, JavaScript got that.

if(weather == "sun"){
    console.log("You can safely walk outside")
} else if (weather == "rain"){
    console.log("Bring an umbrella")
} else {
    console.log("Look outside and decide for yourself")
}

The else block doesn't need to evaluate an expression. If no other expressions evaluate to true, the else block will be executed.

Using these statements will let you run different blocks of code based on the program's state, or the user's actions.

Last updated