by Dinesh Thakur Category: JavaScript Tutorial

JavaScript If Else: Conditional statements are also called “if/then” statements, because they perform a task only if the answer to a question is true: “If I have enough money then I’ll go to the movies.” The basic script of a JavaScript If Else looks like this:

if ( condition ) {// 
   JavaScript If Else Action performed here
}

The if statement lets you put decision making in your javascript code. A javascript without any decisions does the same procedure each time it is executed. JavaScript enables decision making using an if else statement. if statements associate a single statement with a true condition. Javascript if statement is only executed if the conditional expression is true; otherwise, it is not executed at all.

The condition must evaluate to a Boolean value: true or false. Numeric values are also acceptable as an alternative to a Boolean condition. 0 is equivalent to false, and all other values are equivalent to true.

The Javascript if statement associates a single statement with a true condition. A statement can be anything from a simple document.write () to a block of statements, using curly braces ({}). Some if statements require multiple statements, so they use a block in the following form:

if (condition)
{
   Javascript if statement1
   Javascript if statement2
   Javascript if statement3
}

In many cases, the condition is a comparison between two values. For example, say you create a game that the player wins when the score is over 100. In this program, you’ll need a variable to track the player’s score and, at some point, you need to check to see if that score is more than 100 points. In JavaScript, the code to check if the player won could look like this:

if (score > 100) {

alert('You won!');}

The important part is if  (score > 100). That phrase is the javascript if condition, and it simply tests whether the value stored in the score variable is greater than 100. If it is, then a “You won!” dialog box appears; if the player’s score is less than or equal to 100, then the JavaScript interpreter skips the alert and moves onto the next part of the program. In addition to > (greater than), there are several other operators used to compare numbers

A nested statement can be any legal statement, including an additional if statement. Here is a simple example demonstrating the if statement:

<HTML>

  <HEAD>
   <TITLE>A simple if statement</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
     var age = parseInt(prompt("Please enter your age:", 15))
     if (age < 21)
       alert("Sorry, you are too young to enter")
   </SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>

At first, the script asks the user for his or her age.

The age is stored in numeric format in the variable age. The if statement checks if the user’s age is less than 21. If so, the expression age < 21 evaluates to true. Because the condition is true, the next statement is executed, and an alert box is displayed. Note that if the value of age is greater than or equal to 21, no statements are executed. The remedy to this problem is presented in the next section.

Here is another example using multiple statements associated with a true condition:

Javascript if else Statement

if (condition)

   Javascript if else Statement1
else
   Javascript if else Statement2

You might feel limited with the structure of the javascript if statement, because it only lets you execute a statement when the condition is true. The additional javascript else statement specifies a statement that is executed when the condition is false. This construction covers all possibilities, because a condition can be either true or false. Here is a simple example demonstrating the if else statement:

<HTML>

<HEAD>
<TITLE>A Simple Javascript if else Statement </TITLE>
   <SCRIPT LANGUAGE="JavaScript">
    var age = parseInt(prompt("Please enter your age:", 120))
if (age < 21)
    alert("Sorry, you are too young to enter")
else
    alert("Welcome in...")
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>

If the user’s age is greater than 21, he receives a welcoming message.

Nested if-else Statements 

An if statement can execute any legal statement. Obviously, a simple if statement meets this requirement. Statements inside a command block are called nested statements. Consider the following function:

function testChar(ch){

    if (ch >= "A" && ch <= "Z")
     alert("An uppercase letter")
    elseif (ch >= "a" && ch <= "z")
     alert("A lowercase letter")
elsealert("Not a letter")}

The function accepts a character (a one-character string) as its argument. If the character is greater than A and less than Z, it must be an uppercase letter, and an appropriate message is displayed. Only if the character is not an uppercase letter does the execution continue.

If it is a lowercase letter, the appropriate message is provided. Once again, only if it is not a lowercase letter (meaning it is not a letter at all) does the execution proceed. No more tests are performed, so the last message is generated.

This function demonstrates simple nested Javascript if else Statement. Only if the condition is false does the execution continue. If, for example, ch is "H", only the first expression is evaluated. The message “An uppercase letter” is displayed, and the other tests are not performed.

Although it is not required, try to put the condition that is most likely to be true as the top condition. If the condition is true, the other tests are not even performed. Such a practice will make your scripts more efficient, especially if the tests are complex.

C++ requires a semicolon after the first statement (statement1). JavaScript is friendly it lets you choose.

Javascript if else Statement1

else
if (switchingVariable == value2)
Javascript if else Statement2
else
if (switchingVariable == value3)
Javascript if else Statement3
else
Javascript if else Statement4 // default case
Here is a simple example demonstrating the Nested if-else statement:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"" http://www.w3.org/TR/html4/strict.dtd "><html>
<head>
<title>An If Example</title>
</head>
<body>
   <script type="text/javascript">
    var inputNum = prompt("Please enter a number between 50 and 100:");
    if (isNaN(inputNum)) {
    alert(inputNum + " doesn't appear to be a number.");}
    else if ((inputNum > 99) || (inputNum < 51)) {
    alert("That number, " + inputNum + ", is not between 50 and 100.");}
    else {
    alert("You entered a number: " + inputNum);}
    </script><p>This is an example</p>
</body>
</html>

Ternary Conditionals 

Another style of conditional construct is called a ternary conditional. This type of conditional uses the question mark (?) operator to create a compact if/else constructs. The basic structure of a ternary conditional expression is quite simple.

(name == "Steve") ? "Hello Steve": "Hello Unknown Person";

This statement might read as follows, “If name is steve, then “Hello Steve”, else “Hello Unknown Person”.

var greeting = (name == "steve") ? "Hello Steve" : "Hello Unknown Person";
alert(greeting);

This code sets the variable greeting to the value from the outcome of the ternary test. If the value of the name variable is “steve”, the greeting variable gets the string value “Hello Steve”; otherwise, the greeting variable gets the string value “Hello Unknown Person”. Here’s that same code in the traditional if/else form: 

if (name == "steve") {


var greeting = "Hello Steve"; }
else {
var greeting = "Hello Unknown Person"; }
alert(greeting);

The ternary construct can sometimes be confusing if you’ve never seen it before. There’s no shame in sticking to the traditional if/else syntax if you think it will help the readability of your programs in the future especially if the person reading them doesn’t know about the ternary construction!



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.