Following Up On IF Statements And Operators

This tutorial is part of a web programming course for people who have no programming experience.


Now that we've discussed both IF statements and operators, we are going to dig a little deeper. In this lesson we are going to get into some of the nuts and bolts of programming in JavaScript.

Nested IF Statements

You can 'nest' an IF statement within another IF statement. Consider this code sample:

var answer = prompt("Do you like ice cream (yes/no)?");

if(answer == "yes"){

    answer = prompt("Do you prefer chocolate or vanilla?");

    if(answer == "chocolate"){
      alert("One chocolate ice cream cone coming right up!");
    }else{
      alert("One vanilla ice cream cone coming right up!");
    }

}

If the user likes ice cream, then the program will go on to ask another question and evaluate the answer in a nested IF statement. It's quite common to see nested IF statements in programs.

Algorithms

And it can be helpful to write an algorithm to describe how a program should work before you begin to write the code for a problem. An algorithm is a sequence of steps that must be taken in order to complete a task. Here's an algorithm for the task of suggesting what one might do in their free time:

  1. Ask if the user likes books.
  2. If the user likes books, ask them if they like Sci Fi books:
    • If the user likes Sci Fi books, then recommend Frankenstein.
    • If the user does NOT like Sci Fi books, then recommend Gone With the Wind.
  3. If the user does NOT like books, then ask them if they like movies.
    • If the user likes movies, then recommend the movie Social Networking.
    • If the user does NOT like movies, then recommend that they take up knitting.

Here's how we can write code for the algorithm:

var likesBooks = prompt("Do you like books (enter 'yes' or 'no')?");

if(likesBooks == "yes"){
    // the user likes books...

    var likesSciFi = prompt("Do you like Sci Fi books (enter 'yes' or 'no')?");
  
    if(likesSciFi == "yes"){
        alert("I recommend Frankenstein!");
    }else{
        alert("I recommend Gone With the Wind!");
    }

}else if(likesBooks == "no"){
    // the user does NOT like books...

    var likesMovies = prompt("Do you like movies (enter 'yes' or 'no')?");
  
    if(likesMovies == "yes"){
        alert("I recommend Social Networking!");
    }else{
        alert("I recommend knitting!");
    }

}else{

    alert("It was a yes/no question! And remember that JS is case sensitive!");

}

When you write code such as the sample program above, it's very important to run the code and test all possible code branches.

The Strict Equality Operator ( === )

There are a few operators that I left out of the last lesson because I didn't want to bog you down. But now that you've had some practice with operators (hopefully you did the worksheet for the previous lesson), I can introduce you to a few more of them.

You know that variables can store different types of data (number, string, boolean, etc.). Consider what happens if you assign the number 7 to a variable, and assign the string "7" to another variable. The value of each variable is the same (they both store the value 7), but one is a number data type and the other is a string. You can use the strict equality operator to compare both the value AND the data type of two variables.

var someNumber = 7;
var someString = "7";

if(someNumber == someString){
    console.log("They have the same VALUE...");
}

if(someNumber === someString){
    console.log("They have the same VALUE...and they are the same DATA TYPE");
}

Negation Operator ( ! )

Another operator that I left out of the previous lesson is the negation operator, which is simply an exclamation mark (!). You can put this operator before a boolean expression to flip the result from true to false, or from false to true. You might wonder why you would ever want to use this operator, but there are times when you want to know if something is NOT true, or NOT false. Consider this example:

var age = prompt("Enter your age");

if(!age >= 18){
  alert("I'm sorry, you cannot vote");
}

Note that the negation operator (the exclamation mark) is placed before the boolean expression, and that it reverses the result of the boolean expression. If the boolean expressions evaluates to true, then the negation operator will change it to false, and vice versa. Although it's called the negation operator, you can think of it as the NOT operator. So you could verbalize the above IF statement like so: "If age is NOT greater than or equal to 18, then the user cannot vote."

I want to point out that some programmers avoid using the negation operator because it can be easy to miss when you are scanning code. And if you miss it, you'll misinterpret the meaning of the boolean expression. Also, if you prefer, you can use this approach to get the same result:

var age = prompt("Enter your age");

if((age >= 18) == false){
  alert("I'm sorry, you cannot vote");
}

In this example, you may find it easier to see that that the code is checking for cases when age is not greater than or eqaul to 18. But as you may have already noticed, programmers love to use short-cuts, so you'll find that the negation operator is commonly used.

Falsy Values

Some values evaluate to false when used in a boolean expression. For example, in every programming language that I know of, 0 is considered to be equal to false.

if(0 == false){
  console.log("It's true that 0 is equal to false!");
}

When a variable evaluates to false, it's known as falsy. There are other falsy values in JavaScript, such as null, undefined, or an empty string. Consider this example:

var name = prompt("Enter your name");

if(name == false){ // note thate you could write the boolean expression like this: !name
  alert("You did not enter your name");
}

In the IF statement above, we are checking to see if the name variable evaluates to false. The alert would show if the use did not enter anything into the prompt (an empty string).

One very important use of falsy values is when you aren't whether or not a variable will be initialized. If you run into this situation, you can use the variable as the boolean expression in an IF statement, like so:

  

  var likesPizza;
  var favoriteTopping;

  likesPizza = prompt("Do you like pizza ('yes' or 'no')?");

  if(likesPizza == "yes"){
    favoriteTopping = prompt("Enter your favorite topping");
  }

  // by the time our program gets to this line, it's possible that favoriteTopping has not been initialized

  if(favoriteTopping){ // this boolean expression checks to see if favoriteTopping has been initialized
    alert("Your " + favoriteTopping + " pizza is on it's way!")
  }
  

This code sample starts out by declaring two variables without initializing them, which means that they will both have a value of undefined, which is falsy. Depending on what the user does, the favoriteTopping variable may, or may not, remain undefined.

Look at the boolean expression in the final IF statement and recall that a variable all by itself is an expression that can be evaluated. When we write this program, we don't know what value will be stored in favoriteTopping because it depends on what the user does. If the user likes pizza, then it should be storing a value. But if the user does not like pizza, then the favoriteTopping variable will not get initialized.

Here's an example that demonstrates how 0 and false are considered to be the same (that 0 is falsy).

var a = 0;
var b = false;

if(a == b){
    alert("They have the same value");
}

if(a === b){
    alert("They have the same value and they are the same data type");
}

Truthy Values

The whole concept of truthy/falsy really rests on whether or not a variable is storing a value. We've already seen that variables that store zero, false, null, undefined, or empty strings are falsy, which means that these variables store 'no value' (there is one more notable falsy, which is NaN but we won't discuss it here). On the flipside, if a variable stores anything other than what was just mentioned in the previous sentence, then it will evaluate to true if used in a boolean expression.

Consider these examples:

var a = 1;
var b = "Hello";
var c = true;
var d = -7;

If you were to use any of these variables as the boolean expression for an IF statement, they would all evaluate to true. For example:

if(a){
  console.log("It's true!!!");
}

Understanding which values are truthy and which ones are falsy is critical for becomming a good JavaScript programmer, and you'll see that many programs rely on truthy and falsy values to determine how the code executes.

NEXT LESSON: JavaScript Objects