A Simple Guide to JavaScript Conditions (If, Else If, Else and Switch Statement)

codingnninja

Ayobami Ogundiran

Posted on December 12, 2020

A Simple Guide to JavaScript Conditions (If, Else If, Else and Switch Statement)

Welcome to this lesson, in this lesson, we are going to discuss conditional statements.

If

If I tell you I love you, you should know I mean it.

Stop there! That is like a conditional statement in JavaScript.

Let's re-write this with JavaScript as in

let iLoveYou = true;

if( iLoveYou ) {
    let status = "you should know I mean it"; 

    console.log(status)
}
Enter fullscreen mode Exit fullscreen mode

Since we set "iLoveYou" to true, that means "you should know I mean it" and by the time we use it in an 'if statement" and it is true, the body of the "if statement" will execute.

Let's explain it further

The if statement takes conditions in the parenthesis and the conditions always execute to either true or false.

If it is true, the code in the curly braces { } will execute, if not, it won't execute.

if ( 10 > 3 ) {
    console.log('Yeah! That is true');
}
Enter fullscreen mode Exit fullscreen mode

What would happen in this code?

Since 10 is greater than 3, "Yeah! That is true" will be logged in the console.

That takes us to "else" statement examples.

Else

You can extend an if statement with an else statement, which adds another block to run when the if conditional doesn’t pass as in:

let outcome;
if ("man" === "woman") {
      outcome = "Not true";
} else {
      outcome = "Maybe the man is 'trans-gendered'";
}

console.log(outcome);
Enter fullscreen mode Exit fullscreen mode

In the example above, "man" and "woman" are not equal in value, so the else block runs and the variable outcome gets the value "Maybe the man is trans-gendered".

That takes us to else if statement.

Else if

You can also extend an if statement with an else if statement, which adds another conditional and its block to the if statement as in:

let number = 6;
let outcome; // we only declared outcome without assigning any value to it.
if (number == "") {
      outcome = " Number has no value. Please, enter a value";
} else if ( number > 2 ) {
      outcome = "The number is greater than two";
} else {
      outcome = "The number is equal 2";
}

console.log(outcome);
Enter fullscreen mode Exit fullscreen mode

In the example above, "number" is not empty because the number is six in value, so the if block will not run. It will move to the else if block, and it will run because the number is greater than two.

So, its output is "The number is greater than two". Yeah! That is what we see in the console.

If we change the value of the number to 1, " the number is equal to two" is logged in the console.

Oops! That is wrong.

We didn't check whether "number" is less than two, we only check for empty value and if "number" is greater than two, that means, when "number" is less than two, it will log "The number is equal to 2" because we didn't check for "number" less than two.

That takes us to using multiple else-if conditionals.

JavaScript will run them one after another until one condition is true.

JavaScript skips any remaining conditionals after it runs the first one that passes.

Okay, update the previous if statement by adding another else if statement with (number < 2) as in:

let number = 6;
let outcome; // we only declared outcome without assigning any value to it.
if (number == "") {
      outcome = " Number has no value. Please, enter a value";
} else if ( number > 2 ) {
      outcome = "The number is greater than two";
} else if ( number < 2) {
      outcome = "The number is less than two";
}
else {
      outcome = "The number is equal 2";
}

console.log(outcome);
Enter fullscreen mode Exit fullscreen mode

"outcome" will now be equal to "The number is less than two" any time we set the number to 1;

Wow! It is now working. "The number is less" than two is now logged in the console after changing the number.

If we change the number to two, "The number is equal to two" is now logged in the console.

That is cool! It is now working properly.

Hey! Stop there!

An "else if" statement doesn’t need a following "else" statement to work.

In that case, if none of the "if or else if" conditions passes, then JavaScript moves to another part of the code without running any of the conditional blocks of code since "else" statement is not provided.

Now, let delete a part of this if block up to number > 2 and see what happens.

Let's change the value of the number to 6 again as in:

let number = 6;
let outcome; // we only declared outcome without assigning any value to it.
if (number == "") {
      outcome = " Number has no value. Please, enter a value";
} else if ( number > 2 ) {
      outcome = "The number is greater than two";
}

console.log(outcome);
Enter fullscreen mode Exit fullscreen mode

Boom! It is still working.

Switch Statement

A switch statement is used to carry out different actions based on different conditions.

Let's show how it is used in JavaScript:

let anchor = 0;
let price;

switch( anchor ) {
    case 1:
        price = 1000;
    break;
    case 2:
        price = 2000
    break;
    case 3: 
        price = 3000;
    default:
        price = 'free';
}
console.log(price);
Enter fullscreen mode Exit fullscreen mode

JavaScript engine will evaluate any switch statement once. This is how it does it.

In this case, zero is assigned to anchor and it is passed to the switch statement.

The switch check if the value of "anchor" is strictly equal to 1 in the first case and if they are equal, its code block will be executed and the price will be set to 1000 and the break keyword will break the execution from the switch statement and move to console.log(price).

If the value of anchor doesn’t match the value in the first case, it will move to the second case and then to the third case and if there are other cases, it will still check them too but if none of them has an equal value to that of "anchor", the default code block will be executed and the price will be set to "free".

Boom! "Free" is logged in the console.

That is it.

These are all you should keep in mind while dealing with a switch statement:

  1. Whenever there is no "break" keyword between the current matched case and the next case, the next cases will run with the current matched case as in:
let anchor = 1;
let price;

switch( anchor ) {
    case 1:
        price = 1000;
    case 2:
        price = 2000
    break;
    default:
        price = 'free';
}
console.log(price);
Enter fullscreen mode Exit fullscreen mode

We have removed the break keyword between the first and second case.

Sit back and see what happens.

Boom! 2000 is logged in the console. That means the first case was run and set price to 1000 then the second case was run and reset the price to 2000. That is how we get 2000 in the console.

  1. If the matched current case shares the same code block with the next case, the same code block will be run for both cases as in:
let anchor = 1;
let price;

switch( anchor ) {
    case 1:// no block of code
    case 2:
        price = 2000
    break;
    default:
        price = 'free';
}
console.log(price);
Enter fullscreen mode Exit fullscreen mode

We remove "price = 1000" code block - and case 1 and case 2 now share the same code block.

gangan gangan-an!

2000 is logged when "anchor" is 1. now let's change the value of the anchor to 2 to see what happens. We are expecting 2000 because they share the same code block.

let anchor = 2;
let price;

switch( anchor ) {
    case 1:// no block of code
    case 2:
        price = 2000
    break;
    default:
        price = 'free';
}
console.log(price);
Enter fullscreen mode Exit fullscreen mode

Sit back and see what happens!

Boom Boom!

Still, "2000" is still logged.

  1. Switch statement checks for strict equality - that is, it checks equality in both type and value.

For instance, these cases will not be run if we make the cases statement string while the anchor has a number type.

In that case, the default value will be logged as in:

let anchor = 2;
let price;

switch( anchor ) {
    case "1":
        price = 1000;
    case "2":
        price = 2000
    break;
    default:
        price = 'free';
}
console.log(price);
Enter fullscreen mode Exit fullscreen mode

Boom! Do you see that?

Yeah! We are done with this part of the course.

Every other things in JavaScript will be explained practically.

In the next section, we will start discussing how to use JavaScript to build applications for the real world.

Follow me on Twitter: Shakespeare of Code

See you in the next section.

Hurrrray!

Bye for now and stay connected.

One more thing:

Are you struggling to build projects with HTML, CSS & JavaScript? Or you just want to transition to tech without struggling unnecessarily, check out: You Too Can Code

💖 💪 🙅 🚩
codingnninja
Ayobami Ogundiran

Posted on December 12, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related