CommonLounge Archive

JavaScript: Conditional Statements and Comments

September 26, 2018

In the last tutorial, you learnt about writing to HTML document and taking input using the prompt function.

In this tutorial, you’ll learn about if-statements, using which you can do certain things only if certain conditions are met. In plain English, if-else-statements correspond to “If this is true, do this; else, do that.” or “If this condition is true, perform this action; otherwise, do that action.”

A good way to visualize if-statements is flow charts. If-statements represent the yes / no questions in the flowchart below.

Before getting into if-statements, you’ll first learn how to compare things in JavaScript as well as the Boolean data type (values true and false). At the end of the lesson, you’ll also see comments, which are useful for making your code more readable and easy to follow.

Compare things

A big part of programming involves comparing things. What’s the easiest thing to compare? Numbers, of course. Let’s see how that works:

console.log(5 > 2);
console.log(3 < 1);
console.log(5 > 2 * 2);
console.log(1 === 1);
console.log(5 !== 2);

Output:

true
false
true
true
true

There are two types of equality comparators in JavaScript, == and ===. Try, typing "1" == 1 and "1" === 1 in the console, and see if the result is true or false.

console.log("1" == 1);
console.log("1" === 1);

Output:

true
false

The == operator first does the necessary type conversions and then checks for equality. So, one of 1 or "1" first gets converted to a string or an int, respectively. Then the comparison happens and they are found to be equal.

On the other hand, the === operator does not do any type conversions and compares the values directly. Therefore, in this case the result is false since a string can not be equal to an integer.

Generally, you wouldn’t want to convert types and then compare two values. So, it’s recommended you use the === operator instead of ==. Similarly, there’s a !== operator and a != operator for checking that two values are unequal.


Not only can JavaScript compare numbers, but it can also compare method results.

console.log("Commonlounge".length > 10);
console.log("David".length > 10);

Output:

true
false

Nice, huh?

Give JavaScript two more tasks:

console.log(6 >= 12 / 2);
console.log(3 <= 2);

Output:

true
false

We’ve seen > and <, but what do >= and <= mean? Read them like this:

  • x > y means: x is greater than y
  • x < y means: x is less than y
  • x <= y means: x is less than or equal to y
  • x >= y means: x is greater than or equal to y

We’ve summarized the list of comparison operators in JavaScript in a table at the end of the article.

Logical operators

JavaScript also has logical operators which allows us to combine multiple comparison. You can give JavaScript as many numbers to compare as you want, and it will give you an answer! The following are the logical operators:

  • and operator (&&) – if you use the && operator, both comparisons have to be true in order for the whole expression to be true.
  • or operator (||) – if you use the || operator, only one of the comparisons has to be true in order for the whole expression to be true
  • not operator (!) - if you use the ! operator, it inverts the value of the expression

Here are some examples:

console.log(6 > 2 && 2 < 3);
console.log(3 > 2 && 2 < 1);
console.log(3 > 2 || 2 < 1);

Output:

true
false
true

As we’ve done with examples before, let’s see the step-by-step evaluation of one of the above expressions to make sure everything is crystal clear.

3 > 2 && 2 < 1
=> true && 2 < 1
=> true && false
=> false

The first part turned out to be true so JavaScript evaluates the second part as well. It was false, so the result came out to be false. If the first statement was false, then the evaluation would have stopped because the result will be false, independent of the result of the second part.

Consider another example.

3 < 5 || 5 < 6
=> true || 5 < 6
=> true

In this case the first part is true. Since there’s an or operator, ||, JavaScript knows whatever the result be of the second part, the result of the entire statement is going to be true (because for or, only one of the comparisons has to be true). So, the evaluation ends there itself.

If the first part was false, JavaScript would have evaluated the second part and based on its value decide whether the result will be true or false.

Boolean

Incidentally, you just learned about a new type of object in JavaScript. It’s called Boolean.

There are only two Boolean objects:

  • true
  • false

But for JavaScript to understand this, you need to always write it as true (all letters in lowercase). True, TRUE, and tRUE won’t work – only true is correct. (The same applies to false as well, of course.)

Booleans can be variables, too! See here:

var a = true;
console.log(a);

Output:

true

You can also directly assign the value of a comparison:

var a = 2 > 5;
console.log(a);

Output:

false

Practice and have fun with Booleans by trying to run the following commands:

  • true && true
  • false && true
  • true || 1 === 1
  • 1 !== 2

Congrats! Booleans are one of the coolest features in programming, and you just learned how to use them!

If … else if … else

Lots of things in code should be executed only when given conditions are met. That’s why JavaScript has something called if statements.

JavaScript runs the immediate next line of the if statement only if the condition is true. To run multiple lines of code if a certain condition is true you need to put those lines inside of what is called a code block. You specify the start and end of a code block by using opening and closing braces {}.

For example,

if (3 > 2) {
    console.log("It works!");
    console.log("3 is greater than 2");
}

This will print "It works!", followed by "3 is greater than 2" on the next line.

What if a condition isn’t true?

In the previous example, code was executed only when the condition was true. But JavaScript also has else if and else statements. Replace the code in your HTML file with the following:

if (5 > 2)
    console.log("5 is indeed greater than 2");
else
    console.log("5 is not greater than 2");

Output:

5 is indeed greater than 2

If 2 were a greater number than 5, then the second command would be executed. Let’s see how else if works:

var name = 'Dave';
if (name === 'Commonlounge')
    console.log('Hey Commonlounge!');
else if (name === 'Dave')
    console.log('Hey Dave!');
else
    console.log('Hey anonymous!');

Output:

Hey Dave!

See what happened there? else if lets you add extra conditions that run if the previous conditions fail.

You can add as many else if statements as you like after your initial if statement. For example:

var volume = 57;
if (volume < 20)
    console.log("It's kinda quiet.");
else if (20 <= volume && volume < 40)
    console.log("It's nice for background music");
else if (40 <= volume && volume < 60)
    console.log("Perfect, I can hear all the details");
else if (60 <= volume && volume < 80)
    console.log("Nice for parties");
else if (80 <= volume && volume < 100)
    console.log("A bit loud!");
else
    console.log("My ears are hurting! :(");

JavaScript runs through each test in sequence and prints on the console:

Perfect, I can hear all the details

Note that in chained if … else if … else statements, only the first condition that is met gets executed. As soon as the first condition is met, none of future else (or else if) conditions will be considered. Hence, the above code could be written more concisely as:

var volume = 57;
if (volume < 20)
    console.log("It's kinda quiet.");
else if (volume < 40)
    console.log("It's nice for background music");
else if (volume < 60)
    console.log("Perfect, I can hear all the details");
else if (volume < 80)
    console.log("Nice for parties");
else if (volume < 100)
    console.log("A bit loud!");
else
    console.log("My ears are hurting! :(");

We’re making use of the fact that, when we compare volume < 60 (for example), all the previous conditions must have been false. This automatically implies that volume >= 40 (since the first two conditions were false). The code might be slightly harder to read, but it is equivalent to the previous one.

Comments

Comments are, as the word suggests, commentary (descriptive statements) for your code. Single line comments are lines beginning with //. You can write whatever you want after the // and JavaScript will ignore it. Comments can make your code easier for other people to understand.

You can also write multi line comments by enclosing the lines in /* and */.

Let’s see how that looks:

// Change the volume if it's too loud or too quiet
/* This program changes the volume to 50
   if it's greater than 80 or less than 20
*/
var volume = 99;
if (volume < 20 || volume > 80) {
    volume = 50;
    console.log("That's better!");
}

You don’t need to write a comment for every line of code, but they are useful for explaining why your code is doing something, or providing a summary when it’s doing something complex.

Summary

In the last few exercises you learned about:

  • comparing things – in JavaScript you can compare things by using >, >=, ===, <==, < and the &&, || operators
  • Boolean – a type of object that can only have one of two values: true or false
  • if … else if … else – statements that allow you to execute code only when certain conditions are met.
  • comments - lines that JavaScript won’t run which let you document your code

Appendix: List of Comparison Operators

The following is a list of all comparison operations supported by JavaScript.

Operator | Example   | Result | Description 
---------|------——---|--------|-------------------------------------------
   ==    | 4 == '4'  | true   | is equal to (does type conversions)
   ===   | 4 === '4' | false  | is equal to (without type conversions)
   !=    | 4 != '4'  | false  | is not equal to (does type conversions)
   !==   | 4 !== '4' | true   | is not equal to (without type conversions)
   >     | 4 > 5     | false  | is greater than
   <     | 4 < 5     | true   | is less than 
   >=    | 4 >= 5    | false  | is greater than or equal to
   <=    | 4 <= 5    | true   | is less than or equal to

Appendix: List of Boolean Operators

The following is a list of all boolean operations supported by JavaScript.

Operator | Examples        | Result | Description 
=========|=================|========|====================================
  &&     | 3 < 4 && 5 < 4  | false  | true if both values are true
         | 3 < 4 && 5 > 4  | true   | 
---------|-----------------|--------|------------------------------------
  ||     | 3 < 4 || 5 < 4  | true   | true if at-least one value is true
         | 3 > 4 || 5 < 4  | false  | 
---------|-----------------|--------|------------------------------------
  !      | !false          | true   | inverts the value 
         | !true           | false  | 

Time for a quiz and then the last part of this section!


© 2016-2022. All rights reserved.