Logic is a part of our everyday lives – it’s a very familiar concept, therefore one of the easiest to understand. We are faced with questions all the time, with the “If” question being the most common. If I go to sleep early, I will be able to get up early. If I take this job, I will make more money. If I go to school, I will learn JavaScript. Using JavaScript, you can answer all of these questions using conditional statements.

Conditional statements allow you to setup the question or logic within your script, and if it is a true statement, then actions can be taken which are defined by you. Conditional statements create smarter scripts by performing an action based on something that has been setup in the program – it makes your scripts dynamic!

Similar to other languages, JavaScript offers designers and developers the use of the following conditional statements:

  • If
  • else
  • else if
  • switch

If Statement

An “if” conditional statement is setup with 3 parts: the if keyword that sets up the condition, which is located between the parenthesis, and the curly brackets is where the action is placed. The following is an example of how this is setup:
[js]
if (condition) {
//action or event will go here if condition is equal to true
}
[/js]

The if statement allows you to test a condition by seeing if it evaluates to true, then something will occur. The condition will often test two values (strings, numbers, and boolean values) using a comparison operator.
The following example uses the comparison operator “for is not equal to” (!=), to compare var a and 100. If the statement executes as true, the browser will display an alert message that says “Not Equal”.
[js]
var main = 25;
if (main != 100) {
alert("Not Equal");
}
[/js]

If you wanted to test the same variables above to see if they are equal to each other, all you need to do is switch in the (==) comparison operator.
[js]
var main = 25;
if (main == 100) {
alert("Numbers are Equal");
}
[/js]

This conditional statement will work fine in some situations, but there will be situations where you will want something else to happen if it doesn’t evaluate as true.

Else Statement

One of the main problems with using just an “if” statement is that if the condition returns false, the action will be ignored. If you are wondering what I mean, think about this scenario. If I get the job, I will take it. But what if you don’t get the job, this is where the else statement comes into play. As you could then say; If I get the job, I will take it. Otherwise, I will keep looking and interviewing for other jobs. The important thing to remember about the else statement is that it doesn’t have a condition, it is the condition.

The else statement gives you the option of doing something if the “if condition” comes back as false. In the example below, the value of foo has been set to 100. If the value of foo is not equal to 100, then show an alert that says “foo is not equal to 100!”. Otherwise show the alert “foo is equal to 100!”. Otherwise in this case means else, or the condition in the if statement returned false.
[js]
var main = 100;

if (main != 100) {
alert("main is not equal to 100!");
}
else {
alert("main is equal to 100!");
}
[/js]

Else/If Statement

If you would like to test multiple conditional statements, you can add in “else if” after the first if statement. The script will first test the first if condition, if that is false, then it will run the second else if condition, if that is still false, it will execute the statement between the last else.
[js]
var topMenu = 25;

if (topMenu != 100) {
alert("a is not equal to 100!");
}
else if (topMenu < 100) {
alert("a is less than 100!");
}
else {
alert("top menu rocks!");
}
[/js]

You can use else/if statements to test multiple conditions, which is very useful in JavaScript. If you have a web form with 5 required fields, you can use an else/if statement to run through each field and check that something has been entered. If the user did not enter any value, you can create an alert that will show and apply the focus back to that form field. The following example code outlines how you would achieve this problem with JavaScript:
[html]
<form name="form">
<input type="text" name="name" id="name"/>
<input type="text" name="email" id="email"/>
<input type="text" name="street" id="street"/>
<input type="text" name="city" id="city"/>
<input type="text" name="state" id="state"/>
</form>
[/html]
[js]
<script>
if (form.name.value == "") {
alert("Please add your name");
form.name.focus();
return false;
}
else if (form.email.value == "") {
alert("Please add your email");
form.email.focus();
return false;
}
else if (form.street.value == "") {
alert("Please add your street");
form.street.focus();
return false;
}
else if (form.city.value == "") {
alert("Please add your city");
form.city.focus();
return false;
}
else if (form.state.value == "") {
alert("Please add your state");
form.state.focus();
return false;
}
else {
// If all the fields have been filled out, then continue.
return true;
}
</script>
[/js]

Advanced Conditional Statements

If you would like to test if multiple conditions are true within one if statement, you can do so using the logical operators.

In order to make a decision based on a variety of conditions, a logical operator to link those conditions together can be used.

In the following example: If I get the job and the salary is over 50,000, then I will take the job. The following code shows how this can be achieved in javascript.
[js]
var job = true;
var salary = 55000;

if (job == true && salary > 50000) {
alert("Accept the job");
}
[/js]
You can link as many conditions together as you need to, but it is important to remember that they all need to return true in order for your action within the curly brackets to occur. In the following example there are five conditions listed, although the fifth condition has an OR logical operator that precedes it. So either the first four conditions have to be true or the fifth condition has to be true, in order for the alert to show up. If none are true, then the else statement will come into effect and that alert will show.
[js]
var job = true;
var salary = 55000;
var dress = "casual";
var hours = 8;
var lunch = false;

if (job == true && salary > 50000 && hours == 8 && dress == "casual" || lunch == true) {
alert("Accept the job");
}
else {
alert("Don’t accept the job, there will be others.");
}
[/js]

Switch

If you were planning on testing many conditional statements, the if/else/if can get hard to manage and you will end up with a lot of repetitive code, as seen in the example above. An alternative is to use a switch statement.

  1. Declare a variable to test against.
    [js]
    var job = 5;
    [/js]
  2. . Set up the initial test using the switch keyword
    switch(job)
  3. Set up different cases to which I want to compare against the switch statement. In the following code, I am testing to see if the value of job matches any of the cases, and if so to show the alert, then stop the switch by using the keyword break.
    [js]
    {
    case 5:
    alert("This is the one.");
    break;
    case 4:
    alert("This is the one.");
    break;
    case 3:
    alert("This is the one.");
    break;
    case 2:
    alert("This is the one.");
    break;
    case 1:
    alert("This is the one.");
    break;
    }
    [/js]
  4. Similar to the Else statement, I will setup a default case if none of the cases equate to true. In the following example, I am showing the switch statement from start to finish including the default case.
    [js]
    var job = 5;

    switch(job) {
    case 5:
    alert("This is five.");
    break;
    case 4:
    alert("This is four.");
    break;
    case 3:
    alert("This is three.");
    break;
    case 2:
    alert("This is two.");
    break;
    case 1:
    alert("This is one.");
    break;
    default:
    alert("This is the default");
    break;
    }
    [/js]

Categories: BasicsJavaScript/Ajax

1 thought on “JavaScript Basics Part 6: Conditionals”

Pikks · November 19, 2010 at 9:55 pm

Whenever you are definite about the types of the operands there you can use strict equal to operator. You can read more in https://developer.mozilla.org/en/JavaScript/Refer

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Basics

JavaScript Basics Part 7: Loops

Loops are used to execute the same statement of code a set number of times, which can be hardcoded or based on variable. Loops are very common within programming, as they solve the problem of Read more…

Basics

JavaScript Basics Part 5: Arrays

An array is a variable which can store many values inside it. A variable can only store one value. Those values can be accessed at any time using the array’s index. The values stored within Read more…

Basics

JavaScript Basics Part 4: Variables

Variables offer a way to store values of strings, numbers, and boolean data types, as well as being able to reuse at any point within your script. Declaring or creating variables is a common practice Read more…