Conditional Statements in JavaScript

Conditional statements are used to control the flow of execution of the script. There are two conditional statements:

  • if...else
  • switch

if...else statement

if...else simply means if "condition is true" then this else that.

if statement

if means if "condition is true" then this.
Please have a look at the following example.


let time = 10;
if(time === 10){
    console.log("It is 10");
}
//output: "It is 10"

if(time != 11){
    console.log("It is not 11");
}
//output: "It is not 11"

if(time === 11){
    console.log("It is 11");
}
//Above condition is not true.
                    

From the above code, you can see that time is 10. The next statement is if condition which means, if time is 10 then print something. As you can see, we have used strict comparision operator.
The second condition is also true in which time is not equal to 11. As you can see, in second condition, we have used non-strict comparision operator.
We will not discuss about third condition :P.

Falsy values in if

We have learnt about falsy values and truthy values. Any falsy values in if condition is not true and condition body will not executed. Only truthy values in if condition is true.


if(NaN){
    console.log("This is not NaN");
}
//if has falsy value. So no output.

let number1 = 0;
if(number1){
    console.log("Number is other than 0");
}

let str1 = " ";
if(str1){
    console.log("This is not empty string");
}
//output: "This is not empty string"
                        

In the above code, the last condition has a string with space. So it is truthy value. So condition body gets executed.

else part

if statement may contain optional else statement.
condition of the if block is false then the block of the else part is executed.
Please have a look at following code.


if(NaN){
    console.log("This is not NaN");
} else {
    console.log("This is NaN")
}
//output: "This is NaN"

let number1 = 0;
if(number1){
    console.log("Number is other than 0");
} else {
    console.log("Number is 0");
}
//output: "Number is 0"

let str1 = " ";
if(str1){
    console.log("This is not empty string");
} else {
    console.log("This is empty string");
}
//output: "This is not empty string"
                    

In the first if...else block, NaN is falsy value. So if block isn't executed and else part is executed.
In the third if...else block, " " is truthy value. So if block is executed.

else...if statement

Sometimes, you need to add multiple conditions. So for that else...if is used.
Please have a look at the following code.


let year = 2017;
if(year < 2016){
    console.log("Year is less than 2016");
} else if(year >= 2017){
    console.log("Year is greater or equal to 2017");
} else {
    console.log("Year is invalid");
}
output: //"Year is greater or equal to 2017"
                    

In above code, year is 2017. First year < 2016 which is not true. So next part year >= 2017 is checked which is true. So that block is executed.

Ternary Operator (?)

Normally ternary operator is used to assigning value depending on the condition.
You can use ? operator to write if and if...else condition. Though you can write else...if block too but it is not advisable. Why? We will see that.
Please have a look at the following code.


let outputNumber = 2;
let output = "";
if(outputNumber > 3){
    output = "Number is greater than 3";
} else {
    output = "Number is less or equal to 3";
}
console.log(output);
//output: "Number is less or equal to 3";

let year = 2017;
if(year > 2016){
    console.log("Year is greter than 2016");
} else {
    console.log("Year is less than 2017");
}
output: //"Year is greter than 2016"
                    

Above code can be written as below with ? operator.


let outputNumber = 2;
let output = outputNumber > 3 ? "Number is greater than 3" : "Number is less or equal to 3";
console.log(output);
//output: "Number is less or equal to 3";

let year = 2017;
year > 2016 ? console.log("Year is greater than 2016") : console.log("Year is less than 2017");
//output: "Year is greater than 2016"

                    

As you can see, ? operator makes syntax smaller.
There is little difference between if...else and ? operator. Please have a look at the following code to know more.


let numToCheck = 12;
if(numToCheck > 11){
    numToCheck++;
    console.log("Number is greater than 11");
    console.log(numToCheck);
} else {
    console.log("Number is less or equal to 11");
}
//output: "Number is greater than 11"
//        13
                    

In above code, if block has three actions to do. This is not possible in ? ( turnary ) operator.
It is also possible to write else...if condition using ? ( unary operator ).
Please have a look at the following code to have more idea.


let numToCheck = 12;
let outNum;
if(numToCheck >= 13){
    outNum = 13;
} else if(numToCheck < 13){
    outNum = 12;
} else {
    outNum = -1;
}
console.log(outNum);
//output: 12
                    

The above code can be written as per following using ? operator.


let numToCheck = 12;
let outNum = numToCheck >= 13 ? 13 : (numToCheck < 13 ? 12 : -1);
console.log(outNum);
//output: 12
                    

It is not advisable to write else...if ( multiple if ) using ? operator because it is less readable.

switch...case statement

switch statement allows to evaluate the expression and compare the value to the labels and if the match found, then associated statements are executed.


switch( expression ) {
    case label1:
        ...
        statements;
        break;
    case label2:
        ...
        statements;
        break;
    ...
    default:
        ...
        statements;
        break;
}
                    

In above code, value of expression is matched to case label. If it matches, then associated statements are executed. If not, then it tries to match the next lable.
If any of the case labels are not match, then default's associated statements are executed.
Now in switch, break statement in case is optional. If it is included, then only statments associated to particular case are executed. Otherwise, every case below the matched case label are executed untill break. So it is good habbit to write the break in every case.
It is not necessary to add default at the end, but again it is good to add it at the last.


let workoutPerWeek = 3;
switch (workoutPerWeek) {
    case 1:
    console.log("Well it is a start");
    break;
    case 2:
    console.log("Good Going");
    break;
    case 3:
    console.log("You are almost there.");
    break;
    default:
    console.log("Either you are best or yet to be.")
    break;
}
//output: "You are almost there"
                    

In above code, workoutPerWeek is 3. So it will match third case.
Now please have a look at the following code.


let favDrink = "tea";
switch (favDrink) {
    case "tea":
    console.log("You will have your tea");
    case "coffee":
    console.log("You will have your coffee");
    break;
    case "colddrink":
    console.log("You will have your colddrink");
    break;
    default:
    console.log("Do you need anything else?")
    break;
}
//output: "You will have your tea"
          "You will have your coffee"
                    

In above code, in first case, there is no break statement. So when it will match the first case with value "tea", associated statements are executed but it won't stop there because of no break statement. It will execute the second case's associated statement too. And in second case, there is a break statement. So there, code will be stopped executing.
So these examples are just for you to know how the script will behave without break.

Conclusion

In this section, you learned about if...else and switch...case. Please practice it with different scenarios as all the example with every type of value is not possible to include and if...else is going to be used widly in programming.
In next section, you will learn about different loops in JavaScript.