Week 8: Demo

Conditional Logic



Conditional logic is the way to create branches of decisions in your code to change behavior based on user input or interaction. This is done using if() statements. These statements use conditional operators to test an expression for a true or false state. If the condition of the expression results in true, the code inside of the curly braces directly following the parenthesis will be executed.


If you get the password correct, this div will turn green.

function checkPassword(){
    var pass = document.querySelector("#pass").value;
    if(pass == "swordfish"){
        document.querySelector("#passtest").style.backgroundColor = "green";
    }
}

document.querySelector("#passbutton").addEventListener("click", checkPassword);

if() statements can also have an else component that will execute code when the comparator expression results in false.


If you get the password correct, this div will turn green. If it's wrong, it will turn red.

function checkPassword2(){
    var pass = document.querySelector("#pass2").value;
    var div = document.querySelector("#passtest2");
    if(pass == "swordfish"){
        div.style.backgroundColor = "green";
    } else {
        div.style.backgroundColor = "red";
    }
}

document.querySelector("#passbutton2").addEventListener("click", checkPassword2);

We can also use if() statements with else if() components in order to check expressions for multiple conditions, as well as having multiple outcomes when it comes to the code that gets executed. We can also ensure that we are doing an arithmetic comparison by using the parseFloat() function to ensure that the string from the input field will be converted to a Number type variable.


If you are under 18, this div will turn red. If you are over 18, this div will turn yellow. If you're exactly 18, this div will turn green. If you enter anything that isn't a number, the div will turn gray.

function checkAge(){
    var age = parseFloat(document.querySelector("#age").value);
    var div = document.querySelector("#agetest")
    if(age < 18){
        div.style.backgroundColor = "red";
    } else if(age == 18){
        div.style.backgroundColor = "green";
    } else if(age > 18){
        div.style.backgroundColor = "yellow";
    } else {
        div.style.backgroundColor = "gray";
    }
}

document.querySelector("#agebutton").addEventListener("click", checkAge);

Resources