Conditional Branching - ENTERING THE SECOND REALM - JavaScript in Plain Language (2015)

JavaScript in Plain Language (2015)


2.2 Conditional Branching

We have just learned how to get feedback from a user but we could not do much with it because there were no tools to make decisions based on the user’s given feedback. Well, we are going to get some of those tools right now.

Suppose we ask a user if he/she wants to play along and based on the user’s answer, we either keep playing or exit the program. It sounds like we need to apply an if() else conditional code statement, right?

if, else conditionals

To make branching decisions in JavaScript we need to know about the if(), else conditional statements.

Branching is when we either go this way, or go that way, depending on the Boolean statement presented at the point of branching. In other words, “if true go this way, else go that way”.

The basic if, else syntax is as follows:

if(Boolean true) { do this stuff; } else { do that stuff; }

The else part is optional.

Notice the term Boolean true. This is a very important concept that many code students miss at the beginning. Inside of the parentheses we have a lock. Independently from what you write inside of those parentheses, the condition must always evaluate to a Boolean true in order to unlock the code within the subsequent curly braces. The Boolean true is always the correct key to unlock the if() statement. JavaScript will only execute the code on the next code block if that condition is true. On the other hand, if the condition evaluates to false the code block will be hidden from JavaScript, and JavaScript will exit or execute the next code block if there is one available, example: else { }.

· An if(), else statement is in a sense a logical OR (or XOR):
Either the first code block is executed, or the else code block is execute, but never both.
Notice how the else does not have a condition, it works automatically when and only when the Boolean if() evaluates to false.

So when the Boolean condition is false, JavaScript jumps over the curly braces and moves on. In this case we can catch the JavaScript execution with an optional else statement. The else statement does not take conditions; it is just a catcher in case the first condition is not met. We include anelse option when we want JavaScript to choose one of two paths.

Sometimes we want a certain code to execute only if a condition is met, but we do not have an alternative condition. In this case, we use the if(){} by itself without an else{}.

An if() statement by itself is like saying “Nothing to do here. Let’s keep going” when the condition is false. Or “Wait! There is something to do here. Let’s take a detour and do this thing before we keep going” when the condition is true.

· Please note: From now on, some lab work and theory lectures are going to coexist. Please code along as we discuss the subject. Part two is going to be a hands-on adventure.

Let’s construct an example just to see how the if(), else works. Since some of these scripts span for several lines, I have provided a link to an original file which is located on one of my support websites. I recommend writing your own files because you will not master the language if you copy/paste them, but at times it becomes convenient to just copy and paste. Use your best judgment.

The link to the file on my server will be located below the image, like in the example seen on the next page.

Let’s start coding:

1- On your editor (or, assign a prompt() to a variable x.
In the prompt(), ask the user to say yes if he/she want to continue,
or to say no, if he/she wants to leave the program.
Something like this:
var x = prompt("Would you like to continue? yes or no");

2- Construct an if(x === "yes") statement that prints to screen the message
"Ok, let's play!"
Otherwise, it prints to screen
"Ok, goodbye!"

After you finish coding, if you are using jsBeautifier, press the button “Beautify JavaScript”, or CTRL-ENTER to make your code more presentable. Notice how the editor adjusts the spacing to conform to standard JavaScript styling.

See the image below.

Fig 1 See original file:( here )

3- Copy your script from your own editor or from my own linked page and paste it on the Console. Then press ENTER.

If you get an error, recheck your code. Debugging is what programmers do best because that’s where they spend 90% of their time (see step 4 to learn how to repeat the execution on the Console).

When the prompt appears, type yes without quotes. If your script is well constructed you should have the following printout on your Console:

Ok, let's play!

To copy the code from my own website, click on the 2-page icon located to the right of the code script.

4- To repeat the execution, focus your mouse on the Console and press the Up Arrow. That will take you up to the last executed script. From there, (you can edit it if you need to do so) and then press Enter to run it again.
This time, answer no to the prompt question.
You should get: ok, goodbye! as a response.

5- Did you notice how the prompt() takes you to the main browser but then you have to look back at the console for an answer?
You could replace console.log() with confirm() or with alert()
in order to also get your answer on the browser.

Just for practicing purposes, change your first console.log to confirm() and your second console.log() to alert() . Don’t worry about this inconstancy, we are just practicing.
Use the editor at jsbeautifier to write your script.
Then test both if, else outcomes like we did on steps 3 and 4:
confirm("Ok, let's play!");
alert("ok, goodbye!");

Reviewing if(), else

Inside of an if(){ do this stuff; } parentheses, we include a condition. Keep in mind that it is not the condition itself that unlocks the code block: it is the truthiness of the question you write in there that unlocks the code.


if(10 === 10){} <-- since 10 is the same as 10, JavaScript will evaluate the statement as true and it unlocks the next code block.

if(10 === "10"){} <-- since 10 is a number and "10" is a string, JavaScript evaluates the statement as false and jumps over the next code block without executing it.

var x = 33;
if(x){} <-- since x has a value other than 0, undefined, or null, the statement is true.

if(!x){} <-- since x has a value other than 0, undefined, or null, this statement is false.

var y = "yes";

if(y === "yes"){} <-- since the value of y is string yes, this statement is true.

if(y !== "yes"){} <-- since the value of y is yes, this statement is false.

if(y === "no"){} <--- since the value of y is yes, this statement is false.

if(y === "no" || y === "yes"){} <-- since one of the statement is true, the statement is true.

if(y === "no" && y === "yes"){} <--- this statement is false since one of the operands is false.

What about else?

else is optional. We can have an if() conditional statement all by itself. However, we can’t have an else by itself since else is just a catcher helper for when if() fails. Or in other words, the alternate of if().

Adding a second condition in the middle of if(), else

Sometimes an if(), else, is not enough to accommodate all the outcomes. In that case there is an intermediate statement and it takes a condition just like if() does.

This intermediate conditional is called else if()

Here’s the basic syntax:

Fig 2

How to physically write the braces in a conditional statement

Notice the opening brace on line 1. This is the JavaScript common way of doing it. If you come from an older language such as C , you may be used to code the opening brace on the second line by itself. That is perfectly fine. Whichever way you choose to use just make sure you don’t mix styles.

Also, the closing brace is always at the beginning of a line (example: lines 3, 5 and 7). After the if() closing brace we may write the else on the same line, or the else if, when applicable, and finish the line with an opening curly brace (see line 3).

The very final closing brace always stand on its own (line 7). That is common to all languages that use braces. A very popular mistake is to write the closing brace to the right of the last statement. That is very ugly and very difficult to troubleshoot.

Sometimes you will find JavaScript conditionals without braces and it also works. However I do not recommend such practice because it leads to inconstancies and it may trigger an error sooner or later because the JavaScript interpreter adds semicolons automatically when it thinks they are missing, and the lack of a curly brace may trigger the interpreter to think that is has reached the end of a statement. Until you master this styling concept use jsBeautifier to style your code after you are done writing it.

When to use an else if()

Just like else, the else if() does not exist without first having an if(). We can only have one if() and one optional else, but we can have as many else if()s as we wish.


What is the difference between coding else if()s or just writing a new if() statement for a new subsequent condition?

Answer: It is a matter of semantics. When we write several if()s, we are creating independent statements. This means that JavaScript interpreter will evaluate all of them and output all those that are true. On the other hand, when we have else if()s after an if(), we are telling the JavaScript interpreter that we want just one output since both conditions are tied together. In other words, when the if() condition is true, output it and do not execute the next else if() condition because we are done here.

· Side note: When two conditions could possibly be true for both if() and else if(), try to write the most common condition first, in order to avoid an incorrect output.

Here’s what I mean: If we are probing for numbers that are divisible by 3 or divisible by 5, or both, make sure the divisibility 3 && 5 condition goes before the divisibility by 3 or by 5.

Let’s practice some more:

1- Use your editor to create this code, then paste it to the Console.
Declare a variable x and assign it the number 15.
Then create a condition that prints to the screen (console.log) one of the following:
"yes, x is divisible by 3"
"yes, x is divisible by 5"
"yes, x is divisible by 3 and 5"
"No, x is not divisible by 3 nor 5"

Remember to use the modulus in order to see if x is divisible by a certain number, like for example:
if (x % 3 === 0) Which means that if the remainder is zero, x is divisible by 3, right?

See the next page for a script discussion and a link to my own file.

Is Programming an Art or a Science?

There are many ways to finish the task. Programming is part science and part art. In a way it is like planning and cooking a meal.

First we need to look at possible solutions. In this project we probably need three conditional statements, which means that we may have to employ some else if()s in the middle before we get to the catch all else solution at the end. It’s a good idea to take a walk outside while putting all the ingredients together in our mind for the recipe we are about to create. Sketching the ingredients on a piece of paper also helps a bit (real paper and pencil).

As mentioned before, we have to address the common condition first, which is when x is divisible by both 3 and 5. That should become our main if() condition. Then we create two additional else if()s for numbers that are divisible by 3 or by 5.
Finally, we assign the output “No, x is not divisible by 3 nor 5" to the catcher else.

2- Let’s do the first condition and test:

Fig 3 (See original file: here )

On line 1 I have declared variable x with the value of 15.

On line 2 the && logical operator is used to ask JavaScript if both left and right operands are true. Notice how each operand has to be explicit. Many new programmers tend to write it this way: x % 3 && 5 === 0, JavaScript will not understand this syntax. An individual Boolean condition for each case is necessary.

We could wrap each operand in parentheses to make it easier in the human eye:
if((x % 3 === 0) && (x % 5 === 0)){
If you do it this way, be sure to close all parentheses. There is an even number of them.

On line 3, I used console.log to print the appropriate message.

3- Test your script to look for errors and to make sure you get the correct output. If you wish, reassign x to another number, like for example, 14, and run the conditional statement again. You can run it by using the Up Arrow key until you get to the script, edit the variable x and press ENTER. When x is 14 you will not get any output which means that JavaScript jumped over the code block because the condition was no longer true. In that case you will see an undefined message on the Console. That is ok, it is just an automatic echo from the Console and it does not have any influence on your script.

Note: Subdividing our code project into little test steps is a good practice. There is nothing worse than spending an hour coding a script only to realize in the end that it does not work.

4- Now we are ready to create our first else if() statement.
Which one of these conditions should we do first:
the one that checks for divisibility by 3,
or the one checking divisibility by 5?

At this point it does not matter since we have resolved the ambiguity of being divisible by both, but I would do it in numerical sequence writing the 3 condition first. See lines 4 through 6 on the image below:

Fig 4 (See original file: here )

On line 4 notice how else if is coded to the right of the brace that closes the previous if(). This is not mandatory but it looks more professional.

On line 6 the curly brace closes the else if() statement.

5- Paste your script onto the Console and press ENTER to run it. You should still get the first output because variable x is still 15 which makes the first condition true.

In order to test the second condition, reassign variable x to 9. To change the value of variable x press the Up Arrow key until you see the whole script, then place your cursor at the variable declaration, change the value to 9 and press ENTER.
Now we should get the second output: ‘x is divisible by 3’ because 9 is divisible by 3.

6- It’s time to write the final else if and also the catcher else at the very end. See the next image:

Fig 5 (See original file: here )

On line 6 we can see the second else if() condition.

On line 8, else finally catches anything that is not divisible by 3 or divisible by 5. No condition is necessary since this is the “all else” optional outcome. JavaScript will throw an error if we ever write a condition for else.

On line 10 lies the last closing brace which closes the else statement.

Don’t you feel like you are getting there? I hope so. Conditional branching is an important part of creating real programs.

We will see how to code this script without using else if() in a bit, just to illustrate another important concept: nested conditionals. For now, let’s just take a break by doing something else.