conditionals

In this module we will introduce conditionals.

File Location

You should be working in the following file:

   javascript-library
        └── 0-PreWork
            └── 1-HTML-Basics
            └── 2-CSS-Basics
            └── 3-JavaScript-Basics
                05-conditionals.js       <-----Yep, that one

Description

Hopefully, you've noticed the difference in an application when you are logged in versus when you are logged out. Most times, these values are based on certain conditions being true or false. Conditional statements, using boolean variables, are all over the place in applications.

Conditionals are used to check certain conditions in your application. Conditionals have the power to alter the state of your application based on certain conditions being met or unmet, true or untrue.

In this module, we'll look at if statements and how they are used with conditionals.

Sample Code

Consider the following:

//1
var isOn = true;

//2   //3
if(isOn === true) {
    console.log("The light is on."); //4
}
  1. We declare a variable and initialize it with true.

  2. We use the if keyword to check a certain condition.

  3. Our condition checks if isOn is set to true.

  4. If the value of isOn equals true, then we'll execute a console statement.

Shorter Phrasing

You'll often see the statement written in a shorthand way:

var isOn = true;
    //1
if(isOn) {
    console.log("The light is on. It's bright.");
}

Here, it's implicitly checking if the condition is true. Same as the original statement.

More Practice

Let's write a conditional that checks to see if the weather is greater than 70. If it is, we want to print "Wear shorts today! It's going to be hot!".

var weather = 75;

if(weather > 70){
    console.log("Wear shorts today! It's going to be hot!");
}

More Practice

Practice writing if statements that involve concepts from your everyday life. Keep it simple:

  • If caveman is hungry, print: "Caveman need food."

  • If episode number equals ten, print: "I am sad that this season is ending."

Have some fun with things like that, and gain fluency with conditionals using if.

Last updated