Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 6161

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 27, 20242024-11-27T03:59:06+00:00 2024-11-27T03:59:06+00:00

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

  • 60k

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.

beginnersjavascripttutorialwebdev
  • 0 0 Answers
  • 9 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.