×
Community Blog Let's Talk about JavaScript Conditional Statements

Let's Talk about JavaScript Conditional Statements

This tutorial guides you through the world of JavaScript Conditional Statements.

By Alex Muchiri.

There's virtually an infinite number of cases in programming where you are required to execute tasks based on certain conditions. Such conditions may be that the user inputs something, or certain results are achieved, besides many other possible conditions. So, you can imagine, then, that conditional statements are pretty prevalent and important in coding, especially in JavaScript.

In essence, conditional statements work on the basis of true and false scenarios, which inform the decision for running a specific task. One reason why conditional statements are so numerous is because they represent one of the most basic foundational pillars of any programming language. JavaScript is no exception to this. In JavaScript, conditional statements guide actions based on a specific true-or-false logic.

On examination, there fundamentally are four approaches to JavaScript conditional statements, which namely are:

  1. if: This conditional specifies a condition which triggers an action if found to be true.
  2. if...else: This conditional specifies an action to be triggered if a certain condition is true and an alternative action to be triggered if the condition is false.
  3. if...else if...else: This conditional statement specifies a series of conditions that trigger an action, and an alternative script is executed if all specified conditions are false.
  4. switch: The switch condition is a way of executing different scripts based on the set conditions.

The premise of true or false conditions has been used in JavaScript executions for a long time. Below are some of the examples where they could be used:

  • To ensure that all required fields in forms are filled appropriately before submission.
  • To adjust the language based on the location information of a user.
  • To allow access to a webpage based on conditions such as age, location or language.
  • To open a booking form for an event or venue if the booking has not been done or close such a form if it has already been booked.
  • To run a computation of a certain date, such as check billing status operation.

In many ways, conditional statements enable the formulation of sophisticated flows of information and for solving the problems of having multiple inputs. In this tutorial, we will be exploring these conditional statements and their various combinations.

In particular, there are three key statements that we will be looking into: if, else, and else if. This tutorial will also look at some aspects known as ternary operators, which are equally important when evaluating conditional statements.

Conditional Statement "If"

An if statement is by far the most basic of the conditional statements that we are going to look at today. It is the statement that evaluates the true or false status of statements and usually will execute some instruction if a statement is true. In the event that the statement is false, the would-be code instruction is ignored and the program moves over to the next step.

The example below demonstrates the execution of an if statement.

if (the condition)
{
One or several lines of code to be executed if the condition is determined to be true
}

Let's consider a simple voter registration app. If the voting age is specified as 18, one would need to be at least 18 to be eligible to vote. See the example below:

voter.js
var eligible_age = 18;
var person_age = prompt ("Please enter your age");

// Let us assume that the given age is 20, which is greater than eligible age provided
// This next statement will determine if the person is an eligible voter
if (person_age >= eligible_age) {
  console.log("You are eligible to vote");
}

For such an application, you should see an output similar to the one below:

Output
You are eligible to vote!

Now, let's consider a different scenario where the person's age is lower than the eligible voting age of 18:

voter.js
var eligible_age = 18;
var person_age = prompt ("Please enter your age");

// Let us assume that the given age is 16, which is less than eligible age provided

// This next statement will determine if the person is an eligible voter
if (person_age < eligible_age) {
  console.log("You are not eligible to vote");
}

For such an application, you should see an output similar to the one below:

Output
You are not eligible to vote!

It is compulsory to use an if keyword when making an if statement. The stipulated conditions for the statement are enclosed in parentheses.

Conditional Statement "Else"

We use an else statement if we intend to execute a different task if the initial condition has failed. In the previous section, we have seen how to evaluate if a person is an eligible voter in the example. However, neither application above evaluate for both of the conditions we mentioned, such as if a voter is eligible or if they are not. The else statement solves this ambiguity. An else statement precedes a code to run if the first one failed to execute and it has no conditions of its own. Consider the example below:

if (condition) {
    // this code snippet that runs if condition is true
} else {
    // this section of the code runs if the condition is false
}

From the voter example that we have looked at before, let us include a message for low account balances:

voter.js
// the application should prompt the user to specify their age
var eligible_age = 18;
var person_age = prompt ("Please enter your age");

// This next statement will determine if the user is an eligible voter or not
// Let us assume that the given age is 16, which is less than eligible age provided

if (person_age >= eligible_age) {
  console.log("You are eligible to vote");
} else {
    console.log("You are not eligible to vote ");
}

For such a scenario, you should see an output similar to the one below:

Output
You are not eligible to vote!

In the example above, the else statement has directed the program to execute the code after the first condition failed. As we have seen from the example for our sample application above, users benefit immensely from such condition because it outputs warnings and details the next steps of action. In real life applications, the if...else conditional is very widely used.

Conditional Statement: "Else If"

The conditional if...else if...else can be described as a series of compound statements that specifies a series of conditions that trigger an action and also details an alternative script, which will be executed if all specified conditions are false. A combination of if and else can increase the number of conditional code blocks to run all based on a simple true or false condition. It may also be used if the outputs are potentially many or with multiple options. Specifically, the statement evaluates multiple outcomes if needed. Below is a typical else if statement, which also includes an else statement for the case that all the conditions were determined to be false.

if (condition a) {
    // this coded instruction that runs if condition a is true
} else if (condition b) {
    // the instruction that runs if condition b is true
} else {
    // the instruction that runs if conditions are false
}

JavaScript will attempt executing all the statements preceding the final block, and it terminates the process if none of the conditions are met. Let's examine the example below, which is a script used for determining if a number is positive or negative.

numbers.js
// Determine if number is positive or negative
var x = prompt ("Please enter a number!");

// assuming that the user provided the number 10

if (x > 0) {
    console.log('x is positive');
} else if (x < 0) {
    console.log('x is negative');
} else {
    console.log('x is zero');
} 
Output
X is positive  

The example above has laid out a set of conditions to look for. JavaScript first runs a test to check if the value is greater than 0. Next, it checks if the value is less than 0. Finally, it checks if the value is equal to 0. If only the first condition is satisfied in the above case, then the result is positive, as shown in our example output.

Conditional Statement "Switch"

A switch statement does not evaluate if a condition is true or false as is the case with if statements. But, it can specify what happens if a certain condition is met. switch is preferred in the case that using if...else if...else conditions results in too many conditions. Let's consider the below example of an appropriate use case for this conditional.

switch.js
// Using the switch evaluation
var number = 3;
switch(number)
{
   case 3:
      console.log("number is equal to 3");
      break;
   case 6:
      console.log("number is equal to 6");
      break;
   default:
      console.log("number is: "+ number);
}

The syntax is quite different from the corresponding if statements. Note also that the use of case and default clauses, and the break statement is required for this type of condition. Their roles are as outlined below:

  • break statement: The statement stop any further execution of the statements, meaning that the case has been satisfied.
  • case clause: This compares the value of switch and the provided value to determine if they are equal.
  • default clause: This is the script that runs if the case values have not satisfied the condition (whether the value case is equal to switch or not). It also applies if there are no break statements associated with the case clauses.

The switch statement can perform very complex evaluations such as evaluating a user's input. Consider the example below.

<html>
<body>

<p>Input a number between 5 and 9 in the input field to determine if it is the lucky number</p>

<input id="luckyNumber" type="text">

<button onclick="myFunction()">Run program</button>

<p id="function"></p>

<script>
function myFunction() {
  var text;
  var numbers = document.getElementById("luckyNumber").value;

  switch(numbers) {
    case "5":
      text = "Five is second luckiest!";
    break;
    case "6":
    text = "You are not lucky.";
    break;
    case "7":
    text = "You are not lucky";
    break;
    case "8":
    text = "You are the unluckiest person ever";
    break;
    case "9":
    text = "You are the luckiest person ever!";
    break;
    default:
    text = "That number is not in the list";
  }
  document.getElementById("function").innerHTML = text;
}
</script>

</body>
</html>

Conclusion

Conditional statements in JavaScript, or virtually any other programming language for that matter, are very useful for structuring the output of programs. In fact, they can be said to be the fundamental building block for any sophisticated program. In this article, we have explored the conditional if, else, switch and else... if.

Don't have an Alibaba Cloud account? Sign up for an account and try over 40 products for free. This deal is worth up to $1300. Get Started with Alibaba Cloud to learn more.

The views expressed herein are for reference only and don't necessarily represent the official views of Alibaba Cloud.

0 0 0
Share on

Alibaba Clouder

1,863 posts | 372 followers

You may also like

Comments

Alibaba Clouder

1,863 posts | 372 followers

Related Products

  • Web Hosting Solution

    Explore Web Hosting solutions that can power your personal website or empower your online business.

    Learn More
  • Server Load Balancer

    Respond to sudden traffic spikes and minimize response time with Server Load Balancer

    Learn More
  • Log Service

    An all-in-one service for log-type data

    Learn More
  • Server Load Balancer(SLB)

    Alibaba Cloud Server Load Balancer is built to cope with high volume traffic and each year in November is put to the test during Alibaba’s annual Global Shopping Festival. Alibaba relies on Server Load Balancer to provide uninterrupted service during the festival by switching requests between data centers and transferring transactions to the most available server.

    Learn More