JS Conditional Statements

HTML
CSS
C#
SQL

Conditional Control Flow in JavaScript

Conditional statements are crucial in programming for making decisions based on different scenarios. They allow developers to control the flow of a program based on certain conditions. In JavaScript, the most common conditional statements are:

If-Else Statement

The `if-else` statement is used to execute a block of code if a certain condition is true, and another block of code if the condition is false.

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

}

Example :

Nested If-Else Statement

The nested `if-else` statement allows for multiple conditions to be checked hierarchically.

Syntax:

  if (condition1 ) {
 
    //  block of code to be executed if condition1 is true

  } else if (condition2) {

    //  block of code to be executed if the condition1 is false and condition2 is true
 
  } else {
    
    //  block of code to be executed if the condition1 is false and condition2 is false
 
  }

let a = 2;
  let b = 10;

  if (a === b) {

     console.log(“a is equal to b”);

  } else if (a > b) {

    console.log(“a is greater than b”);

  } else {

     console.log(“b is greater than a”);

  }

These conditional statements help developers handle different scenarios and make the code more flexible and responsive. They are essential tools for creating dynamic and intelligent programs.

Switch Case

The `switch` statement in JavaScript is a powerful tool for decision-making. It evaluates an expression and executes the corresponding block of code based on the value of the expression.

Syntax:

switch (variable/expression) {
 case value1:
    // body of case 1
    break;
  case value2:
    // body of case 2
    break;
  // … more cases
  default:
    // body of default
}

Example 1:

let a = 2;

switch (a) {
  case 1:
    a = ‘one’;
    break;
  case 2:
    a = ‘two’;
    break;
  default:
    a = ‘not found’;
    break;
}
console.log(`The value is ${a}`);

Example 2:

let fruit = ‘apple’;

switch (fruit) {
  case ‘apple’:
  case ‘mango’:
  case ‘pineapple’:
    console.log(`${fruit} is a fruit.`);
    break;
  default:
    console.log(`${fruit} is not a fruit.`);
    break;
}

The `switch` statement provides a concise way to handle multiple conditions based on the value of an expression. It improves code readability and can be a more efficient alternative to a series of `if-else` statements in certain cases.

Course Video

Examples for Practice

You have to solve all the questions given below in the editor without copy-pasting.

1. Write a program that checks if a specific substring is contained within a given main string. Using string method.

The task is to write a JavaScript program that checks if a specific substring is present within a given main string. You are required to use string methods to perform this check.
1. Get User Input:
Use the prompt function to ask the user to enter a main string.
2. Check for Substring:
Use a string method (for example, includes()) to check if a specific substring is contained within the main string.
3. Display Result:
Print a message indicating whether the substring is found or not.

Here’s an example program:

// Get user input for the main string
var mainString = prompt(“Enter a main string:”);

// Specify the substring to check
var substringToCheck = prompt(“Enter a substring to check:”);

// Check if the substring is contained within the main string
if (mainString.includes(substringToCheck)) {
console.log(“The substring is found in the main string.”);
} else {
console.log(“The substring is not found in the main string.”);
}

Output

2. Write a program that checks the condition by comparing the lengths of two strings, and print the message as per length.

The task is to write a JavaScript program that compares the lengths of two strings and prints a message based on the comparison.
1. Get User Input:
– Use the prompt function to ask the user to enter the first string.
– Use the prompt function again to ask the user to enter the second string.
2. Compare String Lengths:
– Use the length property of strings to find the lengths of the two strings.
– Compare the lengths to determine which string is longer, shorter, or if they have equal lengths.
3. Display Result:
Print a message indicating the result of the comparison.

Here’s an example program:

// Get user input for the first string
var firstString = prompt(“Enter the first string:”);

// Get user input for the second string
var secondString = prompt(“Enter the second string:”);

// Compare the lengths of the two strings
if (firstString.length > secondString.length) {
console.log(“The first string is longer than the second string.”);
} else if (firstString.length < secondString.length) {
console.log(“The second string is longer than the first string.”);
} else {
console.log(“Both strings have equal lengths.”);
}

Output

3. Write a JavaScript program that takes a user’s age as input. Using an if-else statement, check if the user is eligible to vote. If the user is 18 years or older, display a message saying, “You are eligible to vote,” and if not, display a message saying, “You are not eligible to vote.” What will the program display if the user enters an age of 21?

The task is to write a JavaScript program that takes the user’s age as input, checks if the user is eligible to vote using an if-else statement, and displays an appropriate message.
1. Get User Input:
Use the prompt function to ask the user to enter their age.
2. Check Eligibility:
– Use an if-else statement to check if the user’s age is 18 or older.
– If the age is 18 or older, display a message saying, “You are eligible to vote.”
– If the age is less than 18, display a message saying, “You are not eligible to vote.”
3. Display Result:
Depending on the user’s age, the program will print messages to the console.

Here’s an example program:

// Get user input for age
var userAge = parseInt(prompt(“Enter your age:”));

// Check eligibility to vote
if (userAge >= 18) {
console.log(“You are eligible to vote.”);
} else {
console.log(“You are not eligible to vote.”);
}

Output

4. Write a program to determine the sign of a number. If the number is positive, Negative OR Zero. Using Switch Case.

1. Get User Input: Use the prompt function to ask the user to enter a number.
2. Determine Sign:
– Use a switch-case statement to check the sign of the entered number using the Math.sign function.
– If the number is positive, display a message saying “Positive.”
– If the number is negative, display a message saying “Negative.”
– If the number is zero, display a message saying “Zero.”
3. Display Result:
Print messages to the console.

Here’s an example program:

// Get user input for a number
var userNumber = parseFloat(prompt(“Enter a number:”));

// Determine the sign using switch-case
switch (Math.sign(userNumber)) {
case 1:
console.log(“Positive.”);
break;
case -1:
console.log(“Negative.”);
break;
case 0:
console.log(“Zero.”);
break;
default:
console.log(“Invalid input.”);
}

Output

5. Write a JS program to print the name of the month using Switch Statement for example:- if a user enters 5 then it will print “May” if a user enters 1 then print “January” and if a user enters a number greater than 12 then print an error message “Incorrect Input”.

The task is to write a JavaScript program that prints the name of a month based on user input using a switch statement.
1. Get User Input:
Use the prompt function to ask the user to enter a number representing a month.
2. Determine the Month:
– Use a switch statement to check the user input and print the corresponding month name.
– Provide cases for each valid month number and a default case for an incorrect input.
3. Display Result:
Display the output in an HTML document (document.write).

Here’s an example program:

// Get user input for the month number
var userMonthNumber = parseInt(prompt(“Enter a month number:”));

// Determine the month name using switch
var outputMessage;

switch (userMonthNumber) {
case 1:
outputMessage = “January”;
break;
case 2:
outputMessage = “February”;
break;
case 3:
outputMessage = “March”;
break;
case 4:
outputMessage = “April”;
break;
case 5:
outputMessage = “May”;
break;
case 6:
outputMessage = “June”;
break;
case 7:
outputMessage = “July”;
break;
case 8:
outputMessage = “August”;
break;
case 9:
outputMessage = “September”;
break;
case 10:
outputMessage = “October”;
break;
case 11:
outputMessage = “November”;
break;
case 12:
outputMessage = “December”;
break;
default:
outputMessage = “Incorrect Input”;
}

// Display the result in the HTML document
document.write(“<p>The month is: ” + outputMessage + “</p>”);

Output

6. Create a simple calculator program that prompts the user for two numbers and an operator (addition, subtraction, multiplication, or division). Use a switch-case statement to perform the chosen calculation and display the result. If the user inputs 7, 3, and selects the multiplication operator, what result will the program display?

The task is to write a JavaScript calculator program that prompts the user for two numbers and an operator, performs the chosen calculation using a switch-case statement and displays the result.
1. Get User Input:
– Use the prompt function to ask the user to enter the first number.
– Use the prompt function again to ask the user to enter the second number.
– Use the prompt function once more to ask the user to choose an operator (addition, subtraction, multiplication, or division).
2. Perform Calculation:
– Use a switch-case statement to check the chosen operator and perform the corresponding calculation.
– Provide cases for each operator and a default case for an invalid operator.
3. Result for Inputs 7, 3, and Operator ‘*’: If the user inputs 7, 3, and selects the multiplication operator (*), the program will display the result: “Result: 21.”
4. Display Result: Display the output in an HTML document (document.write).

Here’s an example program:

// Get user input for the first number
var firstNumber = parseFloat(prompt(“Enter the first number:”));

// Get user input for the second number
var secondNumber = parseFloat(prompt(“Enter the second number:”));

// Get user input for the operator
var operator = prompt(“Choose an operator (+, -, *, /):”);

// Perform calculation using switch-case
var result;

switch (operator) {
case ‘+’:
result = firstNumber + secondNumber;
break;
case ‘-‘:
result = firstNumber – secondNumber;
break;
case ‘*’:
result = firstNumber * secondNumber;
break;
case ‘/’:
result = firstNumber / secondNumber;
break;
default:
result = “Invalid Operator”;
}

// Display the result in the HTML document
document.write(“<p>Result: ” + result + “</p>”);

Output