JavaScript Conditionals

JavaScript Conditionals

·

8 min read

In programming, it's frequently required to write code that relies on some condition to be true. For a suitable example, let's imagine we're constructing a website!

We want users to be sent to the dashboard exclusively if they are logged in. Otherwise, we should send them to the login page:

if(loggedIn){
    //loggedIn is true
    goToDashboard();
}else{
    //loggedIn is false
    goToLogin();
}

You could think of this logic as if the user is logged in, then send them to the dashboard. If not, send them to the login page.

Our logic is branched based on the condition of whether or not the user is logged in. We can look at this from the perspective of a flow chart:

Ready to begin coding your conditionals? Let's get into it!

If Statement

Time to present the if statement!

Utilize "if" when you require to branch based on a condition:

if(1 === 1 ){
    console.log("Yup, that's true?");
}

Here [ 1===1 ] is the condition. The === operator is typically referred to as the strict equality operator. It compares values and evaluates them as true if they are identical. The expression 1===1 is always true, so this code will always log "Yup, that's true!"

Wondring about the console.log function?

Console Log

The console.log will log values during the program's execution. You can use it when you're trying to debug your program in these code exercises.

You will often see console.log used in code examples:

let a = 32;
 a = a +10;
console.log(a);// 42;

This final line with console.log and the comment sysntax indicates that 42 would be logged to the console. You'll see this sort of indicator quit often in code tutorials!

A more interesting case is when the condition contains a variable:

if(num === 1 ) {
    console.log("The num is 1!");
}

This depends on the value of num. If num is 1, we'll return the message. Otherwise, this code will not run.

Is Not Equal

"Hello? Yes, I'd like an operator!"

Well, you're in luck!

Our following operator is the !== or the strict inequality operator. This operation will evaluate to true if the two values are not equal.

There are also loose equality/Inequality operator: == nd != respectively. We'll discuss these when we dig into types!

Let's check out some examples:

console.log( 1 !== 2 );
//true
console.log( 2 !== 2 );
//false
console.log( 3 !== 2 );
//true

Notice that 2!==2 is the only expression evaluating false because these two values are equal.

Returning the Expression

Especially when returning a boolean, it's often useful to just return the expression itself.

Take, for instance:

function isEqual(a,b){
    if( a === b ){
        return true;
    }
}

The expression a===b evaluate to true so we could achive similar functionality by just returning the expression:

function isEqual(a,b){
    return a===b;
}

If we look closely, this function actually does more then the first function. If a and b are not equal, this will return false. In the first example, nothing is returned. We'll talk about what happens when nothing is returned in the next stage.

Else Statement

In complement to the if statement we also have an else statement. The else statement runs only if the if condition is not true.

Suppose the statement:

"If it rains today I'll stay indoors, otherwise I'll go outside".

The condition is whether or not it rains. If it does, I'll stay indoors. The "I'll go outside" would be our else course.

if(isRaining === true){
    stayIndoors();
}else{
    //isRAining is not true
    goOutside();
}

For boolean values we can also simply use the value rather than a comprison operator.

Booleans as Conditions

Consider the following code:

const a = true;
if( a === true ){
    console.log("hi!");
    //hi!
}

This will always log "hi!" because the expression a === ture ealuates to true.

Is there a simpler way to accomplish this?

Sure is! Consider:

const a = true;
if(a){
    console.log("hi!");
    //hi!
}

In this case the boolean itself is the condition upon which we are branching.

You can also provide other values in an if condition! Any value considered truthy will run the statement. We'll discuss this futher when we dive into data types!

Greater Then

We discovered how to compare equality. Now we want to be able to compare various values!

Let's take a look at two new operators:

console.log( 1 > 4 );
//false
console.log( 4 > 1 );
//true
console.log( 4 < 1 );
//false
console.log( 1 < 4 );
//true

Here we have the greater than\> and less than < operators!

Both > and < will evaluate to false if the operands are equal:

console.log( 4 > 4 );
//false
console.log( 4 < 4 );
//false

The term "operand" refers to the values on either side of the operator. For the expression 1 > 4, the operands are 1 and 4

Curious what happens when you don't return anything?

No Return Value

In JavaScript, We can explicitly choole to return a value from a function :

function add(a,b){
    return a+b;
}

What happens when we don't return a value?

function add(a,b){

}
const value = add(2,3);
//undifined

The value return from add in this case is undifined.

Greater Than Or Equal To

What if we wanted any value greater than or equal to another value?

We could compose a function:

function greaterThenOrEqualTo(a,b){
    if(a>b){
        return true;
    }
    if(a === b){
        return true;
    }
}

Fortunately, there's an easier way! Let's take a look at two new operators:

console.log(1>=2);//false
console.log(1>-1);//true
console.log(2<=1);//false
console.log(2<=2);//true

Here we have the greater than or equal to >= and less than or equal to <= operators!

Unlike the > and < operators, both >= and <= will evaluate to true when the operands are equal.

What a tip to simplify your code? We can avoid using else by returning early.

Return ing Early

It should be noted that using return always exits the function immediately. Doing something like this:

function isEqual(a,b){
    if(a===b){
        return true;
    }else{
        return false;
    }
}

Accomplishes the same functionality as:

function isEqual(a,b){
    if(a===b){
        return true;
    }
    return false;
}

In both cases, the return false is only reached if a is not equal to b. If a is equal to b in second example, the return true will exit the function and the last line will never be reached.

Let's consider another example however:

function isEqual(a,b){
    if(a===b){
        console.log("They are equal!");
    }else{
        console.log("They are not equal!");
    }
}

Removing the else here would not work!

function isEqual(a,b){
    if(a===b){
        console.log("They are equal!");
    }
    //this line will always be reached 
    console.log("They are not equal!");
}

In this case, the last line will always be reached.

Else If

Let's imagine we want three behaviors based on two conditions.

We could use else and if together:

if(firstCondition){
    //firstCondition is true
}else if(otherCondition){
    //firstCondition is not true and otheCondition is true
}else{
    //nither condition is true
}

If neither condition is true your function will default to the else statement.

What if both firstConditon and otherCondition are true? Let's take a closer look.

In JavaScript, we have the keywords if and else.

Technically, else if is just the combination of therse two keywords. Seem confusing? Consider this example:

if(a>b){
    console.log("a is greater!");
}else if (b>a){
    console.log("b is greater!");
}else{
    console.lgo("they are the same!");
}

This is actually short-hand for:

if(a>b){
    console.log("a is greater!");
}else {
    if(b>a){
        console.lgo("b is greater!");
    }else{
        console.lgo("they are the same!");
    }
}

The reason this works is because we don't actually need the braces for an if or else statement:

if(a>b)
    console.log("a is greater");

This also works! However, in most style guides this is discouraged.

Just because you can do something dosen't mean you should. Many organizations mantain a strict style guide to ensure code is legible to a standard. Typically, braces {} are encouraged for if/else statements.

So let's consider the qustion posed in the Task. What Happens if the two conditions wer true?

const a = true;
const b = true;

if(a){
    //this will run 
}else if(b){
    //this will not run!
}else{
    //ths will definitely not run.
}

Why dosen't the code after else if run?

It may be easier to once again look at it from the long-hand perspective:

const a = true;
const b = true;

if(a){
    //this will run 
}else {
    if(b){
        //this will not run!
    }else{
        //this will definitely not run.
    }
}

The important thing to take away from all of this is that else statement will only run if the original condition is not true.

In the next lesson, we will discuss loops in javascript.

Hope you are liking this series so far