If...Else

Do something based on a boolean expression.

If you're cold, put on a sweater. If you're hot, take the sweater off. Simple, right?

In code, we need to make several thousand decisions per second. Think of a video game that checks for physical collisions or what happens when you click a certain key on the keyboard. The control of data, or flow control, can be determined based on boolean logic. if a particular value is true, do something. Otherwise, or else, do something else (or nothing at all).

Syntax

Same syntax for C++ , Java, Javascript, and many other languages.

if (booleanExpression1) {
   // code to be executed if true
}
else if(booleanExpression2) {
   // booleanExpression1 is false and booleanExpression2 is true
}
else if (booleanExpression3) {
   // booleanExpression1 and 2 are false and booleanExpression3 is true
}
.    // "else if" statements are optional and you can have infinitely many
.
else {
   // code to execute if all test expressions are false (optional)
}

Example 1: If

Only do something if the condition is true.

let someNumber = 5;

if (someNumber < 0) {
    console.log("That's a negative number");
}

// The above code will do absolutely nothing because 5 is NOT less than 0

Example 2: If...else

Run the following code to see how we can do something else if the condition is false:

Example 2: If...else

Example 3: If...else if

We can make a secondary check on a condition if the first condition equates to false. In this example, our third statement equates to true, so it is run. Notice how there is no default set of code in case none of the conditions equate to true:

let myName = "Karen";

if (myName == "Lola") {
    console.log("Her name was Lola...");
}
else if (myName == "Jackie") {
    console.log("You mean, like Jackie Chan? Awesome.");
}
else if (myName == "Karen") {
    console.log("What a lovely name!");
}
else if (myName == "Robert") {
    console.log("His name was Robert Paulson...");
}

// This will output: What a lovely name!

Example 4: If...else if...else

Run this second example to see multiple options and consider how this sort of conditional code can be used.

Example 5: With Numbers

Finally, just to get the message home, let's control things based on a number instead of text.

Testing Tech.io instead of Repl.it Tech.io is based on Node.js, so no prompt() or alert()

Important Notes

While all of the examples above do a simple console.log() it is important to note that you can do whatever you like inside the code block brackets { }. You can even nest another if statement, loop, function call, or more.

While I would love to continue with more examples, they are very easy to find online.

Last updated