Learning JavaScript: Functions

Learning JavaScript: If/else statements

I’m going to be looking at if/else statements in this post, finding out what they do, how they are written and how they can be used to achieve certain outcomes, with a simple multi-path game example…

Please note: This article is subject to constantly change as and when I learn more!

What is an ‘if/else statement’?

An if/else statement can be thought of as a fork in the road and it works as follows:

  • A condition is set at the beginning;
  • if that condition is true one block of code is run;
  • else another block of code is run.

Syntax

This is what an if/else statement looks like:

JavaScript

// Create the if/else statement
if(condition) {
	// Code that runs if the condition is true goes here...
}
else {
	// Code that runs if the condition is false goes here...
}

Code explanation

  1. On line 2, the if statement is started and a condition added within parentheses ( ) directly after it. The condition can be anything – a calculation, the value of a variable, etc (I’ll go through a few examples a bit later);
  2. On line 3 within the curly brackets { }, this is where code is placed that will run if the condition just stated is true. It can take up as many lines as needed. Each instruction should be followed by a semi-colon ;;
  3. On line 4, the if section is closed with a curly bracket } and is NOT followed by a semi-colon ;;
  4. On line 5, this is where the else part of the statement is started. It is exactly the same as the if section but a condition isn’t added in parentheses ( ) after it, as the block of code here runs if that condition is false. Again, no semi-colon ; is placed at the end after the closing curly bracket }.

Simple example: Check if a number is lower than another

The example below is extremely simple:

  1. I want to check if the number 10 is less than the number 5 (which of course we know isn’t true);
  2. If that statement is true, I want the console to print out "10 is less than 5";
  3. If it isn’t true, I want the console to print "10 is not less than 5" instead.
View markup

JavaScript

// Create the if/else statement
if(10 > 5) {
    console.log("10 is less than 5");
}
else {
    console.log("10 is not less than 5");
}

Result

"10 is not less than 5"
  1. On line 2, the if statement is started and the condition 10 > 5 (see my post on operators to see how this works) added within parentheses ( ) directly after it. This condition means “10 is less than 5”, so if 10 is in fact less than 5, a block of code will be run;
  2. On line 3 within the curly brackets { }, this is where code is placed that will run if the condition just stated is true. As the number 10 isn’t less than the number 5, this block of code is bypassed;
  3. On line 5, this is the block of code that will run if the condition is false. As the condition is false, this block of code is in fact run, so "10 is not less than 5" will be printed to the console.

Simple example: Check a name

In this example, I’m going to ask the user what their name is and pop up a response in an alert box, contents depending on the name entered:

  1. Before the if/else statement is started, I want to ask the user what their name is with a prompt and save their answer down as a variable;
  2. I then want to check if the variable’s value is equal to the string of text "Michelle";
  3. If that statement is true and the string "Michelle" is input, I want an alert box to pop up saying "Your name is Michelle, that's an awesome name!";
  4. If it isn’t true (which means something different to "Michelle" has been input), I want the alert box to say "Your name isn't Michelle. Too bad..." instead.

View markup

JavaScript

// Create the variable
var name = prompt("What is your name?");

// Create the if/else statement
if(name === "Michelle") {
    alert("Your name is Michelle, that's an awesome name!");
}
else {
    alert("Your name isn't Michelle. Too bad...");
}
  1. On line 2, a variable is created called name which gets its value from a prompt window where the user can type in their name;
  2. On line 5, the if statement is started and the condition name === "Michelle" added within parentheses ( ) directly after it. Translated, this condition is saying “if the value of the variable name is equal to the string of text "Michelle", run the following block of code”;
  3. On line 6 within the curly brackets { }, this is where code is placed that will run if the condition just stated is true. If I input my name here, this code block will be run and "Your name is Michelle, that's an awesome name!" will be pulled up in an alert box;
  4. On line 8, this is the block of code that will run if the condition is false. So it will be run if the name "Sarah" or "Mark", or any other name, string of text or number is entered. "Your name isn't Michelle. Too bad..." will be shown in an alert box.

Else if

What if I want to check multiple conditions and output something different for each one? This is where I would use else if statements.

An else if statement is used in exactly the same way as the if statement, and it is placed in between the if and the else statements to check multiple conditions. Multiple else if statements can be used one after the other to create many options.

Take my example below, which is very similar to my previous example with the names, but with more options…

  1. Before the if/else statement is started, I want to ask the user what their name is with a prompt and save their answer down as a variable;
  2. I then want to check if the variable’s value is equal to the string of text "Michelle";
  3. If that statement is true and the string "Michelle" is input, I want an alert box to say "Your name is Michelle, that's an awesome name!";
  4. If that statement isn’t true but the string "Andria" is input instead, I want an alert box to say "Your name is Andria, that's a fabulous name!";
  5. If neither of those first two statements are true but the string "Nichol" is input to the prompt, I want an alert box to say "Your name is Nichol, that's a wonderful name!";
  6. If neither of the previous if and else if statements are true (which means something different to "Michelle", "Andria" or "Nichol" has been input), I want an alert box to say "Your name isn't Michelle, Andria or Nichol. Bad times!".

View markup

JavaScript

// Create the variable
var name = prompt("What is your name?");

// Create the if/else statement
if(name === "Michelle") {
    alert("Your name is Michelle, that's an awesome name!");
}
else if(name === "Andria") {
    alert("Your name is Andria, that's a fabulous name!");
}
else if(name === "Nichol") {
    alert("Your name is Nichol, that's a wonderful name!");
}
else {
    alert("Your name isn't Michelle, Andria or Nichol. Bad times!");
}

Nested if/else statements

If/else statements can be nested inside of one another. The best thing I thought I could do to demonstrate how this works is by creating a very simple text game requiring user input.

The game works with text prompts to ask the user what they would like to do and alerts to tell them what happens due to their actions:

  1. First of all, the game asks the user with a text prompt where they would like to go – and they reply with either beach, forest or mountain. This is the first if/else statement. If something other than those three words are typed in, an alert comes up saying "That isn't a valid place; please enter 'beach', 'forest' or 'mountain'.".
  2. If the user types beach into the prompt window for example, another prompt comes up asking what they would like to do nextswim in the sea or eat an ice cream. Different options come up if the user types forest or mountain. These secondary options are the result of nested if/else statements inside the first ones. Again, if any of the provided options aren’t picked, an alert box comes up saying so.
  3. I won’t go through each line of code explaining everything, but it’s all pasted below, and the game can be run by selecting the button below to try it out…

View markup

JavaScript

// Ask the user where they would like to go and save the result as a variable
var place = prompt("You feel like going on an adventure. Where would you like to go today - [beach], [forest] or [mountain]?");

// Create the first if/else statement
if(place === "beach") {
    // Ask the user what they would like to do at the beach and save the result as a variable
    var beachActivity = prompt("You have gone to the beach, it's a beautiful day! What would you like to do? [swim] in the sea or [eat] an ice cream?");
    
    // Create the first nested if/else statement
    if(beachActivity === "swim") {
        alert("The sea is cool and refeshing. Watch out for the sharks!");
    }
    else if(beachActivity === "eat") {
        alert("Chocolate fudge ice cream... delicious! Careful, I think the wasps have their eyes on it too...");
    }
    else {
        alert("That isn't a valid activity; please enter 'swim' or 'eat'.");
    }
}
else if(place === "forest") {
    // Ask the user what they would like to do in the forest and save the result as a variable
    var forestActivity = prompt("You took a stroll into the forest, there are a lot of woodland creatures around. Would you like to have a [picnic] or set up your tent to [camp] for the night?");
    
    // Create the second nested if/else statement
	if(forestActivity === "picnic") {
        alert("So much food! I think a few squirrels craftily made off with a few of your sandwiches when you weren't looking...");
    }
    else if(forestActivity === "camp") {
        alert("Setting up a tent is hard work. Make sure it's water tight, as I think a storm is coming...");
    }
    else {
        alert("That isn't a valid activity; please enter 'picnic' or 'camp'.");
    }
}
else if(place === "mountain") {
    // Ask the user what they would like to do on the mountain and save the result as a variable
    var mountainActivity = prompt("You took a trek up the mountain. What a wonderful view! Would you like to [survey] the landscape or [climb] higher up?");
    
    // Create the third nested if/else statement
	if(mountainActivity === "survey") {
        alert("You look out over the landscape. Is that a castle in the distance?");
    }
    else if(mountainActivity === "climb") {
        alert("You decide to be brave and climb further up. Don't look down!");
    }
    else {
        alert("That isn't a valid activity; please enter 'survey' or 'climb'.");
    }
}
else {
    alert("That isn't a valid place; please enter 'beach', 'forest' or 'mountain'.");
}



Leave a Reply

Your email address will not be published. Required fields are marked *