DEV Community

Cover image for A Comprehensive Guide on the use of If-Else Statement in JavaScript
Ghloriey
Ghloriey

Posted on

A Comprehensive Guide on the use of If-Else Statement in JavaScript

Introduction

If-else statement is a block of code that is executed when a particular condition is met. It is used to perform different actions based on different conditions, such that if a particular condition is true, a certain code should be executed else if the condition is false, another block of code should be executed or returned. The if-else statement can be used in many programming languages, such as JavaScript, MATLAB, C++, and Python, to name a few, but this article will walk you through the use of the if-else statement in JavaScript.

 

Basic Syntax of an if-else Statement

The if-else statement can be categorized into four parts, each with its own unique syntax. This includes;

  • The basic IF statement:

The if statement specifies the block of code to be executed if the condition is met.

Syntax

if(condition){
// block of code to be executed if the condition is true
}

Enter fullscreen mode Exit fullscreen mode

The if-else statement:

The if-else statement is simply the combination of the basic if statement and the else statement. The else in this case specifies the block of code to be executed if the condition is false or not met.

Syntax


if(condition){
// block of code to be executed if the condition is true
}
else{
// block of code to be executed if the condition is false
}



Enter fullscreen mode Exit fullscreen mode
  • Else if statement:

The else-if statement specifies a second condition if the first condition is false.

Syntax

if(condition 1){
// block of code to be executed if the condition is true
}
else if(condition 2){
// block of code to be executed if the first condition is false and the second condition is true
}
else{
// block of code to be executed if both condition 1 and condition 2 are false
}

Enter fullscreen mode Exit fullscreen mode
  • Nested if else statement:

The nested if-else statement is simply having one if statement embedded in another if statement.

Syntax

if(condition 1){
// block of code to be executed if condition 1 is true
}
if(condition 2){
//block of code to be executed if condition 1 is false and condition 2 is true
}
else{
// block of code to be executed if both condition 1 and condition 2 are false
}

Enter fullscreen mode Exit fullscreen mode

 

Examples of an if else Statement in Action

let SchoolProgress = prompt("have you finished primary school? yes/no", "")
if (SchoolProgress === "yes"){
    alert('congratulations, you can now proceed to secondary school')
    }
    else{
    alert("Pls go back to primary school")
    }

Enter fullscreen mode Exit fullscreen mode
let score = prompt ("enter your score", "");
if (score >= 70 && score <= 100){
    alert("your grade is A");
}
if(score >=60 && score <= 69){
    alert("your garde is B");
}
if(score >= 50 && score <= 59){
    alert("your grade is C");
}
if(score >= 45 && score <= 49){
    alert("your grade is D");
}
else {
    alert("i'm sorry but u failed");
}

Enter fullscreen mode Exit fullscreen mode
if (age == 18){
'you are eligible to vote'
}
else{
'you are too young to vote'
}
// output : 8 you are to young to vote
// output: 21 you are eligible to vote

Enter fullscreen mode Exit fullscreen mode

 

Conditional/Ternary Operators

It is an operator that works as an alternative to the if-else statement. It takes in three operands, one of which is a condition, followed by a question mark ? then a code to execute if the condition is true followed by a colon: then another code to execute if the condition is false.

The syntax can be written as:

condition ? exprIfTrue : exprIfFalse
Enter fullscreen mode Exit fullscreen mode

Example of a Ternary Operator

const age = 26;
const beverage = age >= 21 ? "Beer" : "Juice";
console.log(beverage); // "Ber"

Enter fullscreen mode Exit fullscreen mode

 

Comparison Operators

A comparison operator is used to compare or check the difference between two values and returns the answer as a Boolean, that is, True or False.Examples of the comparison operators are;== Equal to=== Strict equal to!= Not equal to!== Strict not equal to>Greater than<Less than>= Greater than or equal to<= Less than or equal toNote: The difference between the == and === is that: the == converts the variable to the same type before performing a comparison, while the === does not do any type of conversion. It simply returns true if the variable types are the same.

Example:

2 == '2' // output: true
2 === '2' // output: false

Enter fullscreen mode Exit fullscreen mode

 

Logical Operators

They perform logical operations between variables or values. Logical operators in JavaScript include;

  • Logical AND which is denoted by &&The AND operator returns true if both values or operands are true else it returns false.
  • LogicalOR which is denoted by ||The OR operator returns true if one of the values or operands is true else it returns false.
  • Logical Not which is denoted by ! The NOT operator returns true if the operand is false and returns false if the operand is true. Example:
let a = 2, b = true and c = false
b || c // output True
b && c // output False
!b // output False

Enter fullscreen mode Exit fullscreen mode

 

Differences between If-else Statements & Conditional Operators

The difference between the if-else statement and conditional operator is that the conditional operator is a single programming language that takes in three operands which is generally faster and shorter than the if-else statement which is a programming block in which statements come under the parenthesis.

 

When to Use the If-else statement and Conditional Operators

If-else statements should be used instead of the ternary operators when you would like to have more than two outcomes, such as when writing an else if within your if-else statement. Generally, if you need to check more than one condition, the if-else statement is a better approach. On the other hand, the ternary operator should be used instead of the if-else statement whenever you would otherwise use a simple if-else statement. Generally, anything that can fit in a single line of code is a great time to use the ternary operator because it’s much more compact and easy to read. Ternary operators are also great when you want to set a value to a given variable.

 

Best Practices for Using if-else Statement

  • Avoid using nested statements: The use of nested statements should be avoided while using the if else statement because this could make your code too clumsy as there will be too many braces and if any mistake is made in the process it could be difficult to debug.
  • W*riting clear and concise code:* It is important to keep your code as brief as possible, this is to improve readability and Clarity.
  • Properly indenting code: Indenting your if else statements is one of the best practices to consider and this can be achieved by installing the prettier extension in your Visual Studio code.
  • Avoid redundancy: Do not repeat different blocks of codes with the same meaning. It creates room for redundancy.

 

Conclusion

The if-else statement in Javascript is used to check if a particular condition is met and it has proven to be one of the easiest methods used by programmers to check for certain conditions. The good part is that it doesn’t only apply to the JavaScript programming language but to many other programming languages. I’ll like you to give it a try and also remember to apply best practices while writing your code.

Top comments (0)