DEV Community

Peter Akojede
Peter Akojede

Posted on

Conditional Statement In Javascript

Image description

we use conditional statement in javascript when we want to perform different actions based on different conditions. They are the fundamental part of programming and use when certain conditions are either true or false. uderstanding them will enable you to use them effectively and allows you to execute specific blocks of code based on conditions.

The main type of conditional statement in Javascript are;

  1. If statement
  2. If else Statement.
  3. If else, if else statement (else if).
  4. Switch statement.
  5. Tenary operator (Conditional Operator)

The If statement

The if statement in javascript is the most basic type of expression. it is a statement that always returns true, when an expression is false it will not evalutae the expression, it will only be executed when it is true.

const samuelAge = 18;
const felixAge = 12;

if (samuelAge > felixAge) {
       console.log("Samuel is the eldest brother of Felix");
} 

// output Samuel is the eldest brother of Felix\
Enter fullscreen mode Exit fullscreen mode

The output here will be Samuel is the eldest brother of felix, because the conditions evaluate to be true. However when the statement is false the code will not run.

const felixAge = 12;
const samuelAge = 18;

if (felixAge > SamuelAge) {
  console.log("Felix is older than Samuel");
}

// output: no output because it is false
Enter fullscreen mode Exit fullscreen mode

This code will have no output, since felixAge is less than (<) samuelAge. This will evaluate to false and will be ignored because it is not a truthy statement.
The if keywords is used to create an if statement, which is then followed by a condition enclosed in parenthesis and the code to be executed enclosed in curly brackets. it may be expressed simply as if () {}.

If else Statement

if else statement is applicable when we want the conditions to be either true or false. when we want something to occur in the event that the condition is not fulfilled i.e. false then we use if else statement. the if statement comes first and the else statement comes follows and has no condition in parathesis.

const felixAge = 12;
const samuelAge = 18;

if (felixAge > samuelAge) {
       console.log("Samuel is the eldest brother of Felix");
} else {
console.log("Felix is the eldest brother of Samuel");
}

//output: Felix is the eldest brother of Samuel
Enter fullscreen mode Exit fullscreen mode

This statement above is false!!! when executing an if statement they are always true but when the if statement are not true the codes moves on to the else statement and execute the statement that is false. The condition is false because felix is not older than samuel.

If else if else (The else if Statement)

If else statement is nested to create an else if clause. it is often use for conditions that are true or false. The else if statement can evaluate multiple possibe outcomes or options with different block of code in a single decision-making structure.

let cgpa = 4.5 

if (cgpa >= 4.5) {
console.log("First Class")
} else if (cgpa >= 3.5) {
  console.log("Second Class Upper")
} else if (cgpa >= 2.4) {
console.log("Second Class Lower")
} else if (cgpa >= 1.5) {
console.log("Third Class")
} else {
console.log("pass")
}

// output: First class
Enter fullscreen mode Exit fullscreen mode

we can have so many else if statemets as necessary but then in the case of many else if statement, the switch statement can be preferred for readability, understandability, and clarity in the looks of code.

The Switch Statement

let firstClassCgpa = 4.5 

function cgpaClassification (cgpa) {
switch(true) {
case cgpa >= 4.5:
console.log ("congratulations you have archived a first class");
break;
case cgpa >= 3.5:
console.log ("well done you have archived a second class upper");
break;
case cgpa >= 2.4:
console.log ("second class lower");
break;
case  cgpa >= 1.5:
console.log("Third Class");
break;
default:
console.log("pass");
   }
}

cgpaClassification(firstClassCgpa)

// output: congratulations you have archived a first class
Enter fullscreen mode Exit fullscreen mode

The case keyword is where the expression will be defined regarding the block of code to be executed, The break keyword in the switch statement indicates that javascript should stop the execution inside the switch block when the match case is valid, if there is no break keyword the execution will continue to the next case or default. The default shows that if it does not match any of the expression, the particular code define under the default should execute.

Conditional (Ternary) operator

This actually operate in the same way as if else statement in a simpler version just that it is written in another way or shorter form. it involve a questions mark "?" which indicate that it is true and a semi-colon ":" for false. it reduce the amount of code and make the code more readable to comprehend when dealing with simple conditions.

let samuelAge = 18 
const eligibility = (samuelAge >=18) ? "you are eligible to vote" : "you are not eligible to vote"

//output: you are eligible to vote
Enter fullscreen mode Exit fullscreen mode

Inconclusion, conditional statement is well used in javascript to determine output of our programs based on certain conditions, and it is found in most programming language. however knowing how to use if statement, if else statement, else if statement, switch statement, and ternary operator will determine our programming output and it will go a long way.

Top comments (2)

Collapse
 
tracygjg profile image
Tracy Gilmore • Edited

There are a couple of issues with this article:

  1. You should consider using syntax highlighting. See this.
  2. The switch example has some faults:
    • The cgps variable is unnecessary because a) it would be masked by the parameter of the function and b) the function is not even being called.
    • The parentheses around the conditions are unnecessary.
    • After each case condition there should be a colon to complete the syntax.
    • The case comparing 2.4 is also missing a break statement (which is a common fault with the switch condition), which means values less than 3.5 but greater or equal to 1.5 will produce 2 console logs.

Here is an alternative implementation of the switch solution:

function cgpaClassification(cgpa) {
  switch (true) {
    case cgpa >= 4.5:
      console.log('congratulations you have archived a first class');
      break;
    case cgpa >= 3.5:
      console.log('well done you have archived a second class upper');
      break;
    case cgpa >= 2.4:
      console.log('second class lower');
      break;
    case cgpa >= 1.5:
      console.log('Third Class');
      break;
    default:
      console.log('pass');
  }
}
Enter fullscreen mode Exit fullscreen mode

And here is an alternative approach with needing a switch.

function cgpaClassification(cgpa) {
  const level = (cgpa >= 4.5) + (cgpa >= 3.5) + (cgpa >= 2.4) + (cgpa >= 1.5);
  console.log(
    [
      'pass',
      'Third Class',
      'second class lower',
      'well done you have archived a second class upper',
      'congratulations you have archived a first class',
    ][level]
  );
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
peter_akojede profile image
Peter Akojede

Thank you very much for opening my eyes to the syntax highlighting, I do really appreciate that. I have actually edited and work on the error you pointed out, Thank you for the warm corrections, and some were typo Error.