Conversation


Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!

Join the discussion and share your insights now!

Comments 0


advertisement

How If-Else Statements in JavaScript Can Transform Your Code

if-else statements


Decision-making Statements

Statements are referred to as a logical collection of variables, operators, and keywords that perform a specific action to fulfill a required task. For example, the line of code that declares a variable is a statement. Statements help you build a logical flow of the script. In JavaScript, a statement ends with a semicolon. JavaScript is written with multiple statements, wherein the related statements are grouped. Such a group of statements is referred to as a block of code and the statements within it are enclosed in curly braces.

Decision-making statements allow the implementation of logical decisions by executing different blocks to obtain the desired output. They execute a block of statements depending upon a Boolean condition. This condition is an expression that returns either true or false.

JavaScript supports four decision-making statements which are as follows:

  1. if
  2. if-else
  3. if-else if
  4. switch


1. if Statement:

The if statement executes a block of statements based on a logical Boolean condition. If this condition is true, the block following the if statement is executed. If the condition is false, the block after the if statement is not executed, and the immediate statement after the block is executed.

The syntax to use the if statement is as follows:

if(condition)
{
 // one or more statements;
}


Where,

  • Condition: Is the boolean expression.
  • Statements: Consists of instructions when the boolean expression is true.

Check whether the quantity value is a number and whether it is greater than 0 using the if statement.

<script>
var quantity = prompt('Enter quantity of product:', 0);
// Check if the input is a number greater than or equal to 0
if (quantity < 0 || isNaN(quantity)) {
    alert('Please enter a positive number.');
} else {
    alert('You have entered: ' + quantity);
}
</script>

The code accepts a quantity value from the user using the prompt () function and stores it in the quantity variable. The if statement is executed and the value of the variable quantity is checked whether it is less than 0 and whether it is not a number. Suppose the value provided by the user is less than 0 or is a value other than a number. In that case, the condition evaluates to true and the output Please enter a positive number is displayed to the user.


2. if-else Statement:

The if statement specifies a block of statements to be executed when the condition in the if statement is true. However, sometimes it is required to define a block of statements to be executed when a condition is evaluated as false. This is done using the if-else statement.

The if-else statement begins with the if block, which is followed by the else block. The else block begins with the else keyword followed by a block of statements to be executed upon the false condition.

The syntax to use the if-else statement is as follows:

if (condition) {
// one or more statements;
else {
// one or more statements;
}

Performs the division operation and validates that the divisor is not equal to 0 using the if-else statement.

<script>
var firstNumber = prompt('Enter first number:', 0);
var secondNumber = prompt('Enter second number:', 0);
var result = 0;
// Convert input to numbers
firstNumber = parseFloat(firstNumber);
secondNumber = parseFloat(secondNumber);
if (secondNumber == 0) {
    alert('ERROR Message: Cannot divide by zero.');
} else {
    result = firstNumber / secondNumber;
    alert("Result: " + result);
}
</script>

The code accepts two numbers for the division operation and stores them in the variables firstNumber and secondNumber respectively. The if statement checks whether the value of the variable secondNumber is 0. If it is 0, the alert () function displays an error message to the user. If the value is not 0, the else block is executed, which performs the division operation. The quotient is stored in the result variable and is displayed to the user.


3. if-else if statement:

The if-else if statements allow you to check multiple conditions and specify a different block to be executed for each condition. The flow of these statements begins with the if statement followed by multiple else if statements and finally by an optional else block. The entry point of execution in these statements begins with the if statement. If the condition in the if statement is false, the condition in the immediate else if statement is evaluated.

The if-else if statements are also referred to as the if-else if ladder.

The syntax to use the if-else if statements is as follows:

if (condition) {
// one or more statements;
}
else if (condition){
// one or more statements ;
}
else {
// one or more statements;
}

Displays grades according to the percentage value entered by the user using the if-else if statements.

<script>
var percentage = prompt('Enter percentage:', 0);
percentage = parseFloat(percentage); // Convert input to a number
if (percentage >= 60) {
    alert('You have obtained the A grade.');
} else if (percentage >= 35 && percentage < 60) {
    alert('You have obtained the B class.');
} else {
    alert('You have failed.');
}
</script>

The code accepts the percentage value from the user and stores it in the percentage variable. The if statement checks whether the value of the percentage variable is greater than or equal to 60. If this is true, the user has obtained an A grade. If the condition is false, execution control is passed to the else if block. Here, the value of the percentage variable is checked as to whether it is greater than or equal to 35 and less than 60. If this is true, the user has obtained a B grade. If the condition is false, the else block is executed.


4. Nested-if Statement:

The nested-if statements comprise multiple if statements within an if statement. The flow of nested-if statements starts with the if statement, which is referred to as the outer if statement. This outer if statement consists of multiple if statements, which are referred to as inner if statements.

The inner if statements are executed only if the condition in the outer if statement is true. Further, each of the inner if statements are executed, but only if the condition in its previous inner if statement is true.

The syntax to use is nested if statements.

if (condition1) {
    // One or more statements
    if (condition2) {
        // One or more statements
        if (condition3) {
            // One or more statements
        }
    }
}

Validate the username and password using nested-if statements.

<script>
var username = prompt('Enter Username:');
var password = prompt('Enter Password:');
// Check if both fields are not empty
if (username !== "" && password !== "") {
    // Check if credentials match
    if (username === "admin" && password === "admin123") {
        alert('Login Successful');
    } else {
        alert('Login Failed');
    }
} else {
    alert('Username and password cannot be empty');
}
</script>

The code accepts the username and password and stores them in the username and password variables. The if statement checks whether the values of both variables are not empty. If they are not empty, the inner if statement is executed. The inner if statement checks whether the value of the username variable is admin and the value of the password variable is admin123. If this condition is true, the Login Successful message is displayed to the user. If the condition is false, the else block is executed.


5. Switch-case Statement:

A program becomes quite difficult to understand when there are multiple if statements. To simplify coding and avoid using multiple if statements, switch-case statements can be used as a different approach to coding the same logic. The switch-case statement allows comparing a variable or expression with multiple values.

The syntax to use the switch-case statement is as follows:

switch (expression) {
    case value1:
        // Statements for value1
        break;
    case value2:
        // Statements for value2
        break;
    case valueN:
        // Statements for valueN
        break;
    default:
        // Statements if none of the cases match
}

Where,

  • Switch: Executes a specific case statement that holds the value of the expression or the variable.

  • Case: A value and a colon follow the case keyword. The block of a specific case statement is executed when the value of the switch expression and the case value are the same. Each case block must end with the break keyword.

  • Break: Passes execution control to the statement existing immediately out of the switch-case statement. If there is no break statement, the next case statement is executed.

  • Default: The execution control passes to the default block when none of the case values match the switch expression. The default block is the same as the else block in the if-else if statements.

Displays the salary of an employee according to the designation by using the switch-case statement.

<script>
var designation = prompt('Enter designation:');
switch (designation) {
    case 'Manager':
        alert('Salary: $21000');
        break;
    case 'Developer':
        alert('Salary: $16000');
        break;
    default:
        alert('Enter proper designation.');
        break;
}
</script>

The code uses the variable designation to store the designation of an employee, which is accepted by the user. The switch statement takes the value of the designation variable and this value is matched with different case statements. If the value matches, the particular case block is executed. Which displays the respective salary. If none of the case values match the switch variable, the default block is executed.


JavaScript if else statements Decision making statements if statement in javascript if else statement in javascript if else if statement in javascript nested if statement in javascript switch case statement in javascript how if else statement in javascript javascript statements logical collection in javascript

advertisement