if statements and conditional logic

JavaScript

0 Comments

Sometimes you want to test for some condition (like was a valid element returned from querySelector) before continuing with your JavaScript code. We haven't been doing this so far, and it can cause problems, so let's learn how if statements work, so we can fix this.

So, what can you do with if statements?

var name = 'Brian';
var age = 25;
var isHired = true;

if (name == 'Brian') {
    // do this if name equals 'Brian'
} else {
    // do this otherwise
}

if (name != 'Brian') {
    // do this if name does NOT equal 'Brian'
}

if (age < 30) {
    // do this if age is less than 30
}

if (age >= 30) {
    // do this if age is greater than or equal to 30
}

// This is equivalent to "if (isHired == true)"
if (isHired) {
    // Do this if isHired is true.
}

// This is equivalent to "if (isHired == false)"
if (!isHired) {
    // Do this if isHired is false.
}
  • ! means NOT

else if

var age = 25;

if (age < 18) {
    // do this if age < 18
} else if (age < 30) {
    // do this if age < 30 and age >= 18
} else {
    // do this in all other cases
}

The way this works is that it stops checking as soon as it finds something that is true. If age < 18, we never do the check for age < 30.

AND/OR - Testing multiple conditions at the same time

var name = 'Alice';
var age = 25;

// OR
if (name == 'Alice' || name == 'Bob') {
    // do this if name equals 'Alice' OR 'Bob'
}

// AND
if (name == 'Alice' && age <= 25) {
    // do this if name equals 'Alice' AND age <= 25
}
  • || means OR
  • && means AND

Testing if a valid element was returned by querySelector

function setupButton() {
    var myButton = document.querySelector('#myButton');

    if (!myButton) {
        return;
    }

    myButton.addEventListener('click', hideParagraph);
}

The if statement in the code shown above is used very often in JavaScript. This basically says: if myButton is NOT a valid element, execute the code inside the curly braces. In this case, the only code inside the curly braces is return;, which will exit the current function.

This check is needed because if you try to run addEventListener on an element that doesn't exist, your JavaScript code will crash.

If the code isn't inside a function, you can't use the return keyword

You could also rewrite the previous code as follows (and it will do the same thing):

var myButton = document.querySelector('#myButton');

if (myButton) {
    myButton.addEventListener('click', hideParagraph);
}

This time we test if myButton does exist, and if so, setup our event listener inside the if statement. I personally prefer the first way I showed you because it requires less indentation, so that's the way I'll be doing the examples in this guide (if the code is inside a function).

Leave a Comment