DEV Community

Cover image for How to use Conditional statement in Javascript
Kokoh Gift Ewerem
Kokoh Gift Ewerem

Posted on

How to use Conditional statement in Javascript

What are conditional statement?
A conditional statement control behavior in Javascript and determine whether or not pieces of code can run. Javascript has different type of conditional statements which includes:
If-else statement, and switch.
• “if” statement: to specify a block of code to be executed, if a specified condition is true.
• “switch” statement to specify many alternative blocks of code to be executed…

As the most common type of conditional, the ”if” statement only runs if the condition enclosed in parentheses () is truthy.

     If (10 > 5) {
    var outcome = “yes”;
   }
      OUTPUT
     “yes”
Enter fullscreen mode Exit fullscreen mode

The example above states:

  1. The keyword “if” tells Javascript to start the conditional statement.
  2. (10 > 5) is the condition to test, which in this case is true – 10 is greater than 5.
  3. The part contained inside the curly braces {} is the block of code to run.
  4. Because the condition passes, the variable outcome is assigned the value “yes”

i. Else declaration;
You can extend an “if” statement with an else statement, which adds another block to run when the if conditional doesn’t pass.
If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening":

 If (hour < 18) {
  greeting = “Good day”;
 } else {
 greeting = “Good evening”;
 }
OUTPUT
“Good day”
Enter fullscreen mode Exit fullscreen mode

ii. “else if” declaration;
Use the “else if” statement to specify a new condition if the first condition is false.
If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00, create a "Good day" greeting, otherwise a "Good evening":

     If (time < 10) {
  greeting = "Good morning";
  } else if (time < 20) {
  greeting = "Good day";
  } else {
  greeting = “Good evening”;
  }
OUTPUT
“Good morning”
Enter fullscreen mode Exit fullscreen mode

“switch” statement declaration;
The switch statements is a multiple-choice selection statement. The general form of the switch statement is as follow

switch( expression ){
case constant1:
statement(s);
break;
case constant2:
statement(s);
break;
case constant3:
statement(s);
break;
.
.
default
statement(s);
}
Enter fullscreen mode Exit fullscreen mode

NOTE:
else statement cannot be declared without an if statement opening the command line.
You can have multiple if statement for multiple choice of statements. In switch, you only have one expression for the multiple choices.

Top comments (0)